From b2d7a9bb08d04d158a6d6bbe5e2dafd88f23fe85 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 11:40:21 +0330 Subject: [PATCH 01/14] fix(panel): break Xray restart deadlock and bound panel reload (#7346) Fix the production-confirmed ABBA lock inversion introduced in v3.12.0: Xray restart held the lifecycle mutex while synchronously waiting for the serialized traffic writer, which needed the same mutex to amend the committed live configuration snapshot. This blocked API writes and node synchronization, and made panel reload wait indefinitely for cron shutdown. Run traffic maintenance before acquiring the Xray lifecycle mutex, keep config generation free of writer submissions, and retain the live-snapshot generation guard. Bound panel-only reload with one 75-second deadline across shutdown and startup; fence replacement workers until the old generation drains, and exit nonzero for supervised recovery on failure. Preserve Xray on healthy reloads, gracefully handle termination signals, log phase timings and bounded function-only stack diagnostics, and distinguish accepted restart requests from successful completion. Validation: all 13 GitHub checks passed on the reviewed head, including Go tests, race, PostgreSQL durable-first/migration, node and Xray E2E, frontend, lint, codegen, vulnerability check and docs. PR validation reports isolated SQLite/PostgreSQL 18 reload tests with 15,844 clients and 30,270 memberships, stable real Xray PIDs, and legacy/current node interoperability. Addresses the primary deadlock and bounded panel reload; writer cancellation and per-source listener admission diagnostics remain follow-ups. Supervised failure recovery may interrupt Xray sessions. Fixes #7345 --- docs/content/docs/en/help/troubleshooting.mdx | 12 ++ internal/nodee2e/harness_test.go | 28 ++++- internal/sub/sub.go | 15 ++- internal/web/controller/setting.go | 2 +- internal/web/global/global.go | 9 ++ internal/web/service/xray.go | 9 +- .../web/service/xray_restart_writer_test.go | 83 +++++++++++++ internal/web/translation/ar-EG.json | 2 +- internal/web/translation/en-US.json | 2 +- internal/web/translation/es-ES.json | 2 +- internal/web/translation/fa-IR.json | 2 +- internal/web/translation/id-ID.json | 2 +- internal/web/translation/ja-JP.json | 2 +- internal/web/translation/pt-BR.json | 2 +- internal/web/translation/ru-RU.json | 2 +- internal/web/translation/sk-SK.json | 2 +- internal/web/translation/tr-TR.json | 2 +- internal/web/translation/uk-UA.json | 2 +- internal/web/translation/vi-VN.json | 2 +- internal/web/translation/zh-CN.json | 2 +- internal/web/translation/zh-TW.json | 2 +- internal/web/web.go | 39 ++++-- internal/web/web_shutdown_test.go | 43 ++++++- main.go | 83 +++++++------ panel_restart.go | 114 ++++++++++++++++++ panel_restart_test.go | 86 +++++++++++++ 26 files changed, 475 insertions(+), 76 deletions(-) create mode 100644 internal/web/service/xray_restart_writer_test.go create mode 100644 panel_restart.go create mode 100644 panel_restart_test.go diff --git a/docs/content/docs/en/help/troubleshooting.mdx b/docs/content/docs/en/help/troubleshooting.mdx index d9b72d373..014247621 100644 --- a/docs/content/docs/en/help/troubleshooting.mdx +++ b/docs/content/docs/en/help/troubleshooting.mdx @@ -13,6 +13,18 @@ A checklist for the most common issues. When in doubt, raise the log level - Make sure the **panel port isn't already in use** by another service. - Verify the database path is writable (default `/etc/x-ui/x-ui.db`). +## Panel restart takes too long + +The restart action acknowledges that a request was accepted. The service logs +successful completion once the panel and subscription listeners have both started. +A normal panel restart keeps the running Xray process. Each restart has a +75-second budget shared by both listener drains and the other shutdown and startup phases. + +If a phase fails or overruns that budget, the panel exits with an error so its +supervisor can restart it. This recovery can interrupt Xray sessions. On a +systemd installation, inspect `journalctl -u x-ui` for the phase and elapsed +time. Use a supervisor configured to restart the service after failures. + ## 502 / panel unreachable behind a proxy - Confirm the panel is actually listening on the upstream port (e.g. `2053`). diff --git a/internal/nodee2e/harness_test.go b/internal/nodee2e/harness_test.go index 8b9101efa..09c65a619 100644 --- a/internal/nodee2e/harness_test.go +++ b/internal/nodee2e/harness_test.go @@ -16,6 +16,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" @@ -49,14 +50,31 @@ type panel struct { logOut *os.File } +// The fixture processes bind after their databases have been prepared. Keep +// each assignment unique for the run and below the default ephemeral range on +// CI, where outbound HTTP connections could otherwise take the same port. +var fixturePortOffset atomic.Uint32 + func freePort(t *testing.T) int { t.Helper() - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("free port: %v", err) + var lastErr error + for range 64 { + port := 19999 + int(fixturePortOffset.Add(1)) + if port > 29999 { + t.Fatal("exhausted node fixture ports") + } + listener, err := net.Listen("tcp", ":"+strconv.Itoa(port)) + if err != nil { + lastErr = err + continue + } + if err := listener.Close(); err != nil { + t.Fatalf("release fixture port %d: %v", port, err) + } + return port } - defer l.Close() - return l.Addr().(*net.TCPAddr).Port + t.Fatalf("no available node fixture port: %v", lastErr) + return 0 } func (p *panel) env() []string { diff --git a/internal/sub/sub.go b/internal/sub/sub.go index 64821c886..a2d1f4066 100644 --- a/internal/sub/sub.go +++ b/internal/sub/sub.go @@ -5,6 +5,7 @@ package sub import ( "context" "crypto/tls" + "errors" "io" "io/fs" "net" @@ -485,6 +486,13 @@ func (s *Server) Start() (err error) { // Stop gracefully shuts down the subscription server and closes the listener. func (s *Server) Stop() error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return s.StopWithContext(ctx) +} + +// StopWithContext drains subscription HTTP connections within the caller's deadline. +func (s *Server) StopWithContext(ctx context.Context) error { s.cancel() if s.sub != nil { s.sub.Close() @@ -493,12 +501,13 @@ func (s *Server) Stop() error { var err1 error var err2 error if s.httpServer != nil { - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) - defer shutdownCancel() - err1 = s.httpServer.Shutdown(shutdownCtx) + err1 = s.httpServer.Shutdown(ctx) } if s.listener != nil { err2 = s.listener.Close() + if errors.Is(err2, net.ErrClosed) { + err2 = nil + } } return common.Combine(err1, err2) } diff --git a/internal/web/controller/setting.go b/internal/web/controller/setting.go index ca5c25fad..977c86401 100644 --- a/internal/web/controller/setting.go +++ b/internal/web/controller/setting.go @@ -241,7 +241,7 @@ func (a *SettingController) restartPanel(c *gin.Context) { } answer.NextPort, _ = a.settingService.GetListenPort() err := a.panelService.RestartPanel(time.Second * 3) - jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelSuccess"), answer, err) + jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelAccepted"), answer, err) } // getDefaultXrayConfig retrieves the default Xray configuration. diff --git a/internal/web/global/global.go b/internal/web/global/global.go index 89bd52c1a..d8b229f75 100644 --- a/internal/web/global/global.go +++ b/internal/web/global/global.go @@ -10,6 +10,7 @@ import ( ) var ( + serverMu sync.RWMutex webServer WebServer subServer SubServer @@ -31,21 +32,29 @@ type SubServer interface { // SetWebServer sets the global web server instance. func SetWebServer(s WebServer) { + serverMu.Lock() + defer serverMu.Unlock() webServer = s } // GetWebServer returns the global web server instance. func GetWebServer() WebServer { + serverMu.RLock() + defer serverMu.RUnlock() return webServer } // SetSubServer sets the global subscription server instance. func SetSubServer(s SubServer) { + serverMu.Lock() + defer serverMu.Unlock() subServer = s } // GetSubServer returns the global subscription server instance. func GetSubServer() SubServer { + serverMu.RLock() + defer serverMu.RUnlock() return subServer } diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index ed1a6f5d4..3f9c5306e 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -202,8 +202,6 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) { xrayConfig.OutboundConfigs = forceUserspaceWireGuardTun(xrayConfig.OutboundConfigs) } - _, _, _ = s.inboundService.AddTraffic(nil, nil) - inbounds, err := s.inboundService.GetAllInbounds() if err != nil { return nil, err @@ -1555,6 +1553,13 @@ func (s *XrayService) RestartXrayFrom(isForce bool, origin XrayOrigin) error { // dropSessions replaces a running core whatever its config says: only a new process // ends the sessions of clients the API has already removed. func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin, dropSessions bool) error { + if !isForce && isManuallyStopped.Load() { + return nil + } + // Committed traffic maintenance can take the Xray lock to update the live snapshot. + if _, _, err := s.inboundService.AddTraffic(nil, nil); err != nil { + logger.Warning("traffic maintenance before Xray restart failed:", err) + } lock.Lock() defer lock.Unlock() logger.Debug("restart Xray, force:", isForce) diff --git a/internal/web/service/xray_restart_writer_test.go b/internal/web/service/xray_restart_writer_test.go new file mode 100644 index 000000000..d84df7d58 --- /dev/null +++ b/internal/web/service/xray_restart_writer_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + + "gorm.io/gorm" +) + +func TestPendingXrayRestartDoesNotHoldLifecycleLockWhileWaitingForWriter(t *testing.T) { + db := initTrafficTestDB(t) + stopped := isManuallyStopped.Swap(false) + pending := pendingXrayRestart.Swap(nil) + reconcile := isNeedXrayReconcile.Swap(false) + depletion := pendingXraySessionDrop.Swap(false) + t.Cleanup(func() { + isManuallyStopped.Store(stopped) + pendingXrayRestart.Store(pending) + isNeedXrayReconcile.Store(reconcile) + pendingXraySessionDrop.Store(depletion) + }) + var configRead atomic.Bool + const hook = "test:reject-restart-config-before-starting-core" + if err := db.Callback().Query().Before("gorm:query").Register(hook, func(tx *gorm.DB) { + if _, ok := tx.Statement.Dest.(*[]*model.Inbound); ok && tx.Statement.ConnPool == db.Statement.ConnPool { + configRead.Store(true) + _ = tx.AddError(errors.New("injected config read failure")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(hook) }) + + StartTrafficWriter() + t.Cleanup(StopTrafficWriter) + parked, release, writerDone := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + var lifecycleAvailable bool + go func() { + defer close(writerDone) + _ = submitTrafficWriteBackground(func() error { + close(parked) + <-release + lifecycleAvailable = lock.TryLock() + if lifecycleAvailable { + lock.Unlock() + } + return nil + }) + }() + t.Cleanup(func() { unblock(); <-writerDone }) + select { + case <-parked: + case <-time.After(3 * time.Second): + t.Fatal("traffic writer did not start") + } + + svc := &XrayService{} + svc.SetToNeedRestartFrom(XrayOriginConfigChange) + restartDone := make(chan struct{}) + go func() { defer close(restartDone); svc.ApplyPendingRestart() }() + t.Cleanup(func() { unblock(); <-restartDone }) + for deadline := time.Now().Add(3 * time.Second); trafficWriterQueueLen() == 0; time.Sleep(time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("pending restart never queued lifecycle maintenance") + } + } + unblock() + <-writerDone + <-restartDone + if !lifecycleAvailable { + t.Fatal("restart held the Xray lifecycle lock while waiting for the traffic writer") + } + if !configRead.Load() || pendingXrayRestart.Load() == nil { + t.Fatal("restart skipped config construction or failed to re-arm the request") + } +} diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 7238b0965..f8766bf36 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -1339,7 +1339,7 @@ "infoDesc": "كل تغيير هتعمله هنا لازم يتخزن. ياريت تعيد تشغيل البانل عشان التعديلات تتفعل.", "restartPanel": "إعادة تشغيل اللوحة", "restartPanelDesc": "متأكد إنك عايز تعيد تشغيل البانل؟ لو ماقدرتش تدخل بعد إعادة التشغيل، شوف سجل البانل على السيرفر.", - "restartPanelSuccess": "تم إعادة تشغيل اللوحة بنجاح", + "restartPanelAccepted": "تم قبول طلب إعادة تشغيل اللوحة.", "actions": "إجراءات", "resetDefaultConfig": "استرجاع الافتراضي", "panelSettings": "عام", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 5df5f1e61..24af28443 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -1460,7 +1460,7 @@ "infoDesc": "Every change made here needs to be saved. Please restart the panel to apply changes.", "restartPanel": "Restart Panel", "restartPanelDesc": "Are you sure you want to restart the panel? If you cannot access the panel after restarting, please view the panel log info on the server.", - "restartPanelSuccess": "The panel was successfully restarted.", + "restartPanelAccepted": "Panel restart request accepted.", "actions": "Actions", "resetDefaultConfig": "Reset to Default", "panelSettings": "General", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index df05bd18f..42429f419 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -1339,7 +1339,7 @@ "infoDesc": "Cada cambio realizado aquí debe ser guardado. Por favor, reinicie el panel para aplicar los cambios.", "restartPanel": "Reiniciar panel", "restartPanelDesc": "¿Está seguro de que desea reiniciar el panel? Haga clic en Aceptar para reiniciar después de 3 segundos. Si no puede acceder al panel después de reiniciar, por favor, consulte la información de registro del panel en el servidor.", - "restartPanelSuccess": "El panel se reinició correctamente", + "restartPanelAccepted": "Se aceptó la solicitud de reinicio del panel.", "actions": "Acciones", "resetDefaultConfig": "Restablecer a Configuración Predeterminada", "panelSettings": "Configuraciones del Panel", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index b89862162..5f8bf7016 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -1339,7 +1339,7 @@ "infoDesc": "برای اعمال تغییرات در این بخش باید پس از ذخیره کردن، پنل را ریستارت کنید", "restartPanel": "راه‌اندازی مجدد پنل", "restartPanelDesc": "آیا مطمئن به ریستارت پنل هستید؟ اگر پس‌از ریستارت نمی‌توانید به پنل دسترسی پیدا کنید، لطفاً گزارش‌های موجود در اسکریپت پنل را بررسی کنید", - "restartPanelSuccess": "پنل با موفقیت راه‌اندازی مجدد شد", + "restartPanelAccepted": "درخواست راه‌اندازی مجدد پنل پذیرفته شد.", "actions": "عملیات ها", "resetDefaultConfig": "برگشت به پیش‌فرض", "panelSettings": "پیکربندی", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 77df99297..209bdc64e 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -1339,7 +1339,7 @@ "infoDesc": "Setiap perubahan yang dibuat di sini perlu disimpan. Harap restart panel untuk menerapkan perubahan.", "restartPanel": "Mulai ulang panel", "restartPanelDesc": "Apakah Anda yakin ingin merestart panel? Jika Anda tidak dapat mengakses panel setelah merestart, lihat info log panel di server.", - "restartPanelSuccess": "Panel berhasil dimulai ulang", + "restartPanelAccepted": "Permintaan untuk memulai ulang panel telah diterima.", "actions": "Tindakan", "resetDefaultConfig": "Reset ke Default", "panelSettings": "Umum", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 34cdd4de0..58837eb0a 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -1339,7 +1339,7 @@ "infoDesc": "ここでのすべての変更は、保存してパネルを再起動する必要があります", "restartPanel": "パネルを再起動", "restartPanelDesc": "パネルを再起動してもよろしいですか?再起動後にパネルにアクセスできない場合は、サーバーでパネルログを確認してください", - "restartPanelSuccess": "パネルの再起動に成功しました", + "restartPanelAccepted": "パネルの再起動リクエストを受け付けました。", "actions": "操作", "resetDefaultConfig": "デフォルト設定にリセット", "panelSettings": "一般", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 781f6cdb6..f5454593c 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -1339,7 +1339,7 @@ "infoDesc": "Toda alteração feita aqui precisa ser salva. Reinicie o painel para aplicar as alterações.", "restartPanel": "Reiniciar painel", "restartPanelDesc": "Tem certeza de que deseja reiniciar o painel? Se não conseguir acessar o painel após reiniciar, consulte os logs do painel no servidor.", - "restartPanelSuccess": "O painel foi reiniciado com sucesso", + "restartPanelAccepted": "A solicitação de reinicialização do painel foi aceita.", "actions": "Ações", "resetDefaultConfig": "Redefinir para Padrão", "panelSettings": "Geral", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 5b5065d8f..3e336f3fe 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -1339,7 +1339,7 @@ "infoDesc": "Сохраните изменения и перезапустите панель для их применения.", "restartPanel": "Перезапустить панель", "restartPanelDesc": "Вы уверены, что хотите перезапустить панель? Подтвердите, и перезапуск произойдёт через 3 секунды. Если панель будет недоступна, проверьте лог сервера", - "restartPanelSuccess": "Панель успешно перезапущена", + "restartPanelAccepted": "Запрос на перезапуск панели принят.", "actions": "Действия", "resetDefaultConfig": "Восстановить настройки по умолчанию", "panelSettings": "Панель", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 175906240..d564f6aad 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -1460,7 +1460,7 @@ "infoDesc": "Každú zmenu najprv uložte. Na jej použitie reštartujte panel.", "restartPanel": "Reštartovať panel", "restartPanelDesc": "Naozaj chcete reštartovať panel? Ak sa po reštarte nedá otvoriť, skontrolujte záznamy panelu na serveri.", - "restartPanelSuccess": "Panel bol úspešne reštartovaný.", + "restartPanelAccepted": "Požiadavka na reštart panela bola prijatá.", "actions": "Akcie", "resetDefaultConfig": "Obnoviť predvolené nastavenia", "panelSettings": "Všeobecné", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index fbab4b889..6baa7a495 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -1339,7 +1339,7 @@ "infoDesc": "Burada yapılan her değişikliğin kaydedilmesi gerekir. Değişikliklerin uygulanması için paneli yeniden başlatın.", "restartPanel": "Paneli Yeniden Başlat", "restartPanelDesc": "Paneli yeniden başlatmak istediğinizden emin misiniz? Yeniden başlattıktan sonra panele erişemezseniz, sunucudaki panel loglarını kontrol edin.", - "restartPanelSuccess": "Panel başarıyla yeniden başlatıldı.", + "restartPanelAccepted": "Paneli yeniden başlatma isteği kabul edildi.", "actions": "İşlemler", "resetDefaultConfig": "Varsayılana Sıfırla", "panelSettings": "Genel", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index fb302d746..defd6b693 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -1339,7 +1339,7 @@ "infoDesc": "Кожна внесена тут зміна повинна бути збережена. Перезапустіть панель, щоб застосувати зміни.", "restartPanel": "Перезапустити панель", "restartPanelDesc": "Ви впевнені, що бажаєте перезапустити панель? Якщо ви не можете отримати доступ до панелі після перезапуску, будь ласка, перегляньте інформацію журналу панелі на сервері.", - "restartPanelSuccess": "Панель успішно перезапущено", + "restartPanelAccepted": "Запит на перезапуск панелі прийнято.", "actions": "Дії", "resetDefaultConfig": "Відновити значення за замовчуванням", "panelSettings": "Загальні", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 52570f998..9ac29d089 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -1339,7 +1339,7 @@ "infoDesc": "Mọi thay đổi được thực hiện ở đây cần phải được lưu. Vui lòng khởi động lại bảng điều khiển để áp dụng các thay đổi.", "restartPanel": "Khởi động lại bảng điều khiển", "restartPanelDesc": "Bạn có chắc chắn muốn khởi động lại bảng điều khiển? Nhấn OK để khởi động lại sau 3 giây. Nếu bạn không thể truy cập bảng điều khiển sau khi khởi động lại, vui lòng xem thông tin nhật ký của bảng điều khiển trên máy chủ.", - "restartPanelSuccess": "Đã khởi động lại bảng điều khiển thành công", + "restartPanelAccepted": "Yêu cầu khởi động lại bảng điều khiển đã được chấp nhận.", "actions": "Hành động", "resetDefaultConfig": "Đặt lại cấu hình mặc định", "panelSettings": "Bảng điều khiển", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index d10a4f91b..fbfd10cd6 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -1339,7 +1339,7 @@ "infoDesc": "此处的所有更改都需要保存并重启面板才能生效", "restartPanel": "重启面板", "restartPanelDesc": "确定要重启面板吗?若重启后无法访问面板,请前往服务器查看面板日志信息", - "restartPanelSuccess": "面板已成功重启", + "restartPanelAccepted": "已接受面板重启请求。", "actions": "操作", "resetDefaultConfig": "重置为默认配置", "panelSettings": "常规", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index a736e06b7..a1d96b556 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -1339,7 +1339,7 @@ "infoDesc": "此處的所有更改都需要儲存並重啟面板才能生效", "restartPanel": "重新啟動面板", "restartPanelDesc": "確定要重啟面板嗎?若重啟後無法訪問面板,請前往伺服器檢視面板日誌資訊", - "restartPanelSuccess": "面板已成功重新啟動", + "restartPanelAccepted": "已接受面板重新啟動請求。", "actions": "操作", "resetDefaultConfig": "重置為預設配置", "panelSettings": "常規", diff --git a/internal/web/web.go b/internal/web/web.go index 65a49d319..f00823791 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -789,24 +789,32 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) { // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot. func (s *Server) Stop() error { - return s.stop(true, true) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return s.stop(ctx, true, true) } -func (s *Server) StopPanelOnly() error { - return s.stop(false, true) +func (s *Server) StopPanelOnly(ctx context.Context) error { + return s.stop(ctx, false, true) } -func (s *Server) stop(stopXray bool, stopTgBot bool) error { +func (s *Server) stop(ctx context.Context, stopXray bool, stopTgBot bool) error { s.cancel() var err1 error var err2 error if s.httpServer != nil { - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) - err1 = s.httpServer.Shutdown(shutdownCtx) - shutdownCancel() + err1 = runPanelStopPhase("http drain", func() error { + return s.httpServer.Shutdown(ctx) + }) + if err1 != nil && !stopXray { + return fmt.Errorf("drain old panel HTTP requests: %w", err1) + } } if s.cron != nil { - <-s.cron.Stop().Done() + _ = runPanelStopPhase("cron drain", func() error { + <-s.cron.Stop().Done() + return nil + }) } if stopXray { tuic.GetManager().StopAll() @@ -830,9 +838,12 @@ func (s *Server) stop(stopXray bool, stopTgBot bool) error { s.tgbotService.Stop() } if s.bus != nil { - s.bus.Stop() + _ = runPanelStopPhase("event subscribers", func() error { + s.bus.Stop() + return nil + }) } - if err := service.PersistSystemMetrics(); err != nil { + if err := runPanelStopPhase("system metrics", service.PersistSystemMetrics); err != nil { logger.Warning("persist system metrics on shutdown failed:", err) } if stopXray { @@ -854,6 +865,14 @@ func (s *Server) stop(stopXray bool, stopTgBot bool) error { return common.Combine(err1, err2) } +func runPanelStopPhase(name string, run func() error) error { + started := time.Now() + logger.Infof("panel stop phase=%s state=started", name) + err := run() + logger.Infof("panel stop phase=%s state=finished duration=%s error=%v", name, time.Since(started), err) + return err +} + // GetCtx returns the server's context for cancellation and deadline management. func (s *Server) GetCtx() context.Context { return s.ctx diff --git a/internal/web/web_shutdown_test.go b/internal/web/web_shutdown_test.go index 599c1cd77..0d5c9c24b 100644 --- a/internal/web/web_shutdown_test.go +++ b/internal/web/web_shutdown_test.go @@ -2,6 +2,7 @@ package web import ( "context" + "errors" "net" "net/http" "testing" @@ -32,7 +33,47 @@ func TestServerStopPanelOnlyWithPreclosedListenerSucceeds(t *testing.T) { defer cancel() _ = s.httpServer.Shutdown(shutdownCtx) - if err := s.StopPanelOnly(); err != nil { + if err := s.StopPanelOnly(context.Background()); err != nil { t.Fatalf("expected nil error when listener is already closed, got: %v", err) } } + +func TestServerStopPanelOnlyHonorsCallerDeadline(t *testing.T) { + t.Setenv("XUI_DB_FOLDER", t.TempDir()) + s := NewServer(nil) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s.listener = ln + entered, release := make(chan struct{}), make(chan struct{}) + s.httpServer = &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(entered) + <-release + w.WriteHeader(http.StatusNoContent) + })} + t.Cleanup(func() { + close(release) + _ = s.httpServer.Close() + }) + go func() { _ = s.httpServer.Serve(ln) }() + requestDone := make(chan error, 1) + go func() { + client := &http.Client{Timeout: 3 * time.Second} + res, err := client.Get("http://" + ln.Addr().String()) + if err == nil { + _ = res.Body.Close() + } + requestDone <- err + }() + select { + case <-entered: + case err := <-requestDone: + t.Fatalf("handler did not start: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if err := s.StopPanelOnly(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("active HTTP drain ignored its caller deadline: %v", err) + } +} diff --git a/main.go b/main.go index 70bbfd739..0f53f15cf 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ package main import ( "context" _ "embed" + "errors" "flag" "fmt" "log" @@ -161,7 +162,7 @@ func runWebServer() { monitor, err := tunnelmonitor.New(monitorCfg, func(_ context.Context) error { logger.Warning("Tunnel health monitor threshold reached, restarting xray-core") - return server.RestartXray(service.XrayOriginTunnelHealth) + return (&service.XrayService{}).RestartXrayFrom(true, service.XrayOriginTunnelHealth) }) if err != nil { logger.Warning("Tunnel health monitor disabled: ", err) @@ -169,38 +170,42 @@ func runWebServer() { go monitor.Run(monitorCtx) } } - for { - sig := <-sigCh - - switch sig { + for shutdown := false; !shutdown; { + switch <-sigCh { case syscall.SIGHUP: logger.Info("Received SIGHUP signal. Restarting servers...") - err := server.StopPanelOnly() + var nextWeb *web.Server + var nextSub *sub.Server + pending, err := runPanelRestart(sigCh, panelRestartTimeout, + panelRestartPhase{"panel shutdown", server.StopPanelOnly}, + panelRestartPhase{"subscription shutdown", subServer.StopWithContext}, + panelRestartPhase{"panel startup", func(context.Context) error { + nextWeb = web.NewServer(sub.NewLinkProvider()) + global.SetWebServer(nextWeb) + return nextWeb.StartPanelOnly() + }}, + panelRestartPhase{"subscription startup", func(context.Context) error { + nextSub = sub.NewServer() + global.SetSubServer(nextSub) + return nextSub.Start() + }}, + ) if err != nil { - logger.Debug("Error stopping web server:", err) - } - err = subServer.Stop() - if err != nil { - logger.Debug("Error stopping sub server:", err) - } - - server = web.NewServer(sub.NewLinkProvider()) - global.SetWebServer(server) - err = server.StartPanelOnly() - if err != nil { - log.Fatalf("Error restarting web server: %v", err) + if errors.Is(err, context.DeadlineExceeded) { + logPanelRestartStacks() + } + log.Fatalf("Panel restart failed, exiting for supervisor recovery: %v", err) } + server, subServer = nextWeb, nextSub log.Println("Web server restarted successfully.") - - sub.SetDistFS(web.EmbeddedDist()) - subServer = sub.NewServer() - global.SetSubServer(subServer) - err = subServer.Start() - if err != nil { - log.Fatalf("Error restarting sub server: %v", err) - } log.Println("Sub server restarted successfully.") + shutdown = pending.shutdown + if pending.restartXray && !shutdown { + if err := server.RestartXray(service.XrayOriginSignal); err != nil { + logger.Error("Failed to restart xray-core:", err) + } + } case sys.SIGUSR1: logger.Info("Received USR1 signal, restarting xray-core...") err := server.RestartXray(service.XrayOriginSignal) @@ -209,22 +214,20 @@ func runWebServer() { } default: - if stopTunnelHealthMonitor != nil { - stopTunnelHealthMonitor() - } - - // --- FIX FOR TELEGRAM BOT CONFLICT (409) on full shutdown --- - tgbot.StopBot() - // ------------------------------------------------------------ - - if err := server.Stop(); err != nil { - logger.Error("Server shutdown failed:", err) - } - _ = subServer.Stop() - log.Println("Shutting down servers.") - return + shutdown = true } } + + if stopTunnelHealthMonitor != nil { + stopTunnelHealthMonitor() + } + // Stop polling before process exit to avoid Telegram 409 conflicts. + tgbot.StopBot() + if err := server.Stop(); err != nil { + logger.Error("Server shutdown failed:", err) + } + _ = subServer.Stop() + log.Println("Shutting down servers.") } // resetSetting resets all panel settings to their default values. diff --git a/panel_restart.go b/panel_restart.go new file mode 100644 index 000000000..8db21a60a --- /dev/null +++ b/panel_restart.go @@ -0,0 +1,114 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "runtime" + "strings" + "sync/atomic" + "syscall" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/util/sys" +) + +// Each listener can take up to 30 seconds to drain ordinary HTTP traffic. +const panelRestartTimeout = 75 * time.Second + +type panelRestartPhase struct { + name string + run func(context.Context) error +} + +type panelRestartSignals struct { + shutdown bool + restartXray bool +} + +func runPanelRestart(signals <-chan os.Signal, budget time.Duration, phases ...panelRestartPhase) (panelRestartSignals, error) { + ctx, cancel := context.WithTimeout(context.Background(), budget) + defer cancel() + var phase atomic.Pointer[panelRestartPhase] + result := make(chan error, 1) + go func() { + for i := range phases { + if err := ctx.Err(); err != nil { + result <- err + return + } + step := &phases[i] + phase.Store(step) + started := time.Now() + log.Printf("panel restart phase=%s state=started", step.name) + err := step.run(ctx) + log.Printf("panel restart phase=%s state=finished duration=%s error=%v", step.name, time.Since(started), err) + if err != nil { + result <- fmt.Errorf("%s: %w", step.name, err) + return + } + } + result <- ctx.Err() + }() + + var pending panelRestartSignals + phaseName := func() string { + if current := phase.Load(); current != nil { + return current.name + } + return "dispatch" + } + for { + select { + case err := <-result: + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return pending, fmt.Errorf("%s exceeded the %s panel restart deadline: %w", phaseName(), budget, ctx.Err()) + } + return pending, err + case <-ctx.Done(): + return pending, fmt.Errorf("%s exceeded the %s panel restart deadline: %w", phaseName(), budget, ctx.Err()) + case sig, ok := <-signals: + if !ok { + signals = nil + continue + } + switch sig { + case syscall.SIGHUP: + continue + case sys.SIGUSR1: + pending.restartXray = true + default: + // Let the current restart finish within its existing deadline, + // then let the signal loop stop the new generation gracefully. + pending.shutdown = true + } + } + } +} + +// Log function names only. Argument values and goroutine labels can contain panel data. +func logPanelRestartStacks() { + records := make([]runtime.StackRecord, 2048) + n, ok := runtime.GoroutineProfile(records) + if !ok { + log.Printf("panel restart goroutine profile omitted: %d goroutines exceed diagnostic capacity", n) + return + } + log.Printf("panel restart goroutine profile: %d goroutines, showing up to 24 stacks", n) + for _, record := range records[:min(n, 24)] { + frames := runtime.CallersFrames(record.Stack()) + names := make([]string, 0, 12) + for range cap(names) { + frame, more := frames.Next() + if frame.Function != "" { + names = append(names, frame.Function) + } + if !more { + break + } + } + log.Print(strings.Join(names, " <- ")) + } +} diff --git a/panel_restart_test.go b/panel_restart_test.go new file mode 100644 index 000000000..75a32707c --- /dev/null +++ b/panel_restart_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "errors" + "os" + "strings" + "sync" + "syscall" + "testing" + "time" +) + +func TestPanelRestartDeadlineFencesBlockedDrain(t *testing.T) { + entered, release, drained := make(chan struct{}), make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + t.Cleanup(unblock) + newGeneration := make(chan struct{}) + _, err := runPanelRestart(nil, 250*time.Millisecond, + panelRestartPhase{"panel drain", func(context.Context) error { + close(entered) + <-release + close(drained) + return nil + }}, + panelRestartPhase{"panel startup", func(context.Context) error { close(newGeneration); return nil }}, + ) + if !errors.Is(err, context.DeadlineExceeded) || !strings.Contains(err.Error(), "panel drain") { + t.Fatalf("blocked drain: %v", err) + } + <-entered + unblock() + <-drained + select { + case <-newGeneration: + t.Fatal("new workers started after a failed drain") + case <-time.After(75 * time.Millisecond): + } +} + +func TestPanelRestartDrainsBeforeGracefulShutdown(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + t.Cleanup(unblock) + signals := make(chan os.Signal) + type outcome struct { + pending panelRestartSignals + err error + } + result := make(chan outcome, 1) + started := false + go func() { + pending, err := runPanelRestart(signals, 3*time.Second, + panelRestartPhase{"panel shutdown", func(context.Context) error { + close(entered) + <-release + return nil + }}, + panelRestartPhase{"panel startup", func(context.Context) error { + started = true + return nil + }}, + ) + result <- outcome{pending, err} + }() + <-entered + signals <- syscall.SIGHUP + signals <- syscall.SIGTERM + unblock() + got := <-result + if got.err != nil || !got.pending.shutdown || !started { + t.Fatalf("current restart must finish before graceful cleanup: started=%v, result=%+v", started, got) + } +} + +func TestPanelRestartDoesNotStartListenersAfterShutdownFailure(t *testing.T) { + failure := errors.New("old listener did not drain") + started := false + _, err := runPanelRestart(nil, time.Second, + panelRestartPhase{"panel shutdown", func(context.Context) error { return failure }}, + panelRestartPhase{"panel startup", func(context.Context) error { started = true; return nil }}, + ) + if started || !errors.Is(err, failure) { + t.Fatalf("started=%t, error=%v", started, err) + } +} From 9f483d94653142d72290cbb10ff29cb55db88791 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 12:30:15 +0330 Subject: [PATCH 02/14] fix(inbounds): check WebSocket snapshot size before loading (#7309) Avoid materializing full inbound settings and client statistics only to discard the snapshot above the existing 5,000-row WebSocket cutoff. Probe user-scoped direct and sibling-backed traffic rows with bounded SQL before loading the snapshot; skip work without subscribers, fall back to invalidation on probe failure, and retain the post-read guard for concurrent growth. Coalesce WebSocket invalidations by resource in a 200 ms window so paired Inbounds and Clients events refresh both query roots without duplicate same-resource refetches. Regression coverage exercises the real inbound mutation route and WebSocket hub at and above the cutoff, shared traffic, user scoping, no subscribers, and frontend paired invalidations. All 12 CI jobs passed on the reviewed PR head. The author also reports SQLite/PostgreSQL 16 validation and make verify. Static review of the current merge candidate found no overlapping file changes with main; CI on that exact combined revision was not independently run before merge. The reported synthetic SQLite notification benchmark (30 inbounds, 7,101 clients, 115,041 associations) improved from 323.87 ms to 0.24 ms and from 324,751,126 to 5,393 allocated bytes per operation. These figures do not establish production HTTP or browser latency improvements. Fixes #7297 --- frontend/src/api/websocketBridge.ts | 24 +-- .../test/websocket-bridge-inbounds.test.tsx | 63 ++++++ internal/web/controller/inbound.go | 12 +- .../web/controller/inbound_broadcast_test.go | 192 ++++++++++++++++++ internal/web/service/inbound.go | 26 +++ 5 files changed, 300 insertions(+), 17 deletions(-) create mode 100644 frontend/src/test/websocket-bridge-inbounds.test.tsx create mode 100644 internal/web/controller/inbound_broadcast_test.go diff --git a/frontend/src/api/websocketBridge.ts b/frontend/src/api/websocketBridge.ts index 9394398c8..b475a20a0 100644 --- a/frontend/src/api/websocketBridge.ts +++ b/frontend/src/api/websocketBridge.ts @@ -7,26 +7,27 @@ import { isRecentLocalInvalidate } from '@/api/invalidationTracker'; type Handler = (payload: unknown) => void; -let invalidateTimer: number | null = null; - export function useWebSocketBridge() { const queryClient = useQueryClient(); useEffect(() => { const client = getSharedWebSocketClient(); + const pendingInvalidations = new Set<'inbounds' | 'clients'>(); + let invalidateTimer: number | undefined; const onInvalidate: Handler = (payload) => { const p = payload as { type?: string } | undefined; if (!p || (p.type !== 'inbounds' && p.type !== 'clients')) return; - if (invalidateTimer != null) clearTimeout(invalidateTimer); + pendingInvalidations.add(p.type); + if (invalidateTimer !== undefined) return; invalidateTimer = window.setTimeout(() => { - invalidateTimer = null; - if (isRecentLocalInvalidate()) return; - if (p.type === 'inbounds') { - queryClient.invalidateQueries({ queryKey: ['inbounds'] }); - } else { - queryClient.invalidateQueries({ queryKey: ['clients'] }); + invalidateTimer = undefined; + if (!isRecentLocalInvalidate()) { + for (const type of pendingInvalidations) { + queryClient.invalidateQueries({ queryKey: keys[type].root() }); + } } + pendingInvalidations.clear(); }, 200); }; @@ -56,10 +57,7 @@ export function useWebSocketBridge() { client.off('outbounds', onOutbounds); client.off('nodes', onNodes); client.off('inbounds', onInbounds); - if (invalidateTimer != null) { - clearTimeout(invalidateTimer); - invalidateTimer = null; - } + clearTimeout(invalidateTimer); }; }, [queryClient]); } diff --git a/frontend/src/test/websocket-bridge-inbounds.test.tsx b/frontend/src/test/websocket-bridge-inbounds.test.tsx new file mode 100644 index 000000000..2849f27af --- /dev/null +++ b/frontend/src/test/websocket-bridge-inbounds.test.tsx @@ -0,0 +1,63 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClientProvider, useQuery } from '@tanstack/react-query'; +import type { ReactNode } from 'react'; +import { expect, it, vi } from 'vitest'; + +import { keys } from '@/api/queryKeys'; +import { getSharedWebSocketClient } from '@/api/websocket'; +import { useWebSocketBridge } from '@/api/websocketBridge'; + +import { makeTestQueryClient } from './test-utils'; + +it('refreshes inbounds and clients when a mutation invalidates both resources', async () => { + const sockets: EventTarget[] = []; + class FixtureSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + readyState = FixtureSocket.CONNECTING; + constructor() { + super(); + sockets.push(this); + } + close() {} + } + vi.stubGlobal('WebSocket', FixtureSocket); + const queryClient = makeTestQueryClient(); + let rows = [{ id: 1, remark: 'Before update' }]; + const fetchInbounds = vi.fn(async () => rows); + const fetchClients = vi.fn(async () => []); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const { result, unmount } = renderHook( + () => { + useWebSocketBridge(); + useQuery({ queryKey: keys.clients.all(), queryFn: fetchClients }); + return useQuery({ queryKey: keys.inbounds.slim(), queryFn: fetchInbounds }); + }, + { wrapper }, + ); + + try { + await waitFor(() => expect(result.current.data).toEqual(rows)); + const [connected] = sockets; + if (!connected) throw new Error('WebSocket was not connected'); + rows = [{ id: 1, remark: 'After update' }]; + act(() => { + for (const type of ['inbounds', 'inbounds', 'clients']) { + connected.dispatchEvent( + new MessageEvent('message', { + data: JSON.stringify({ type: 'invalidate', payload: { type } }), + }), + ); + } + }); + await waitFor(() => expect(result.current.data).toEqual(rows)); + expect(fetchInbounds).toHaveBeenCalledTimes(2); + expect(fetchClients).toHaveBeenCalledTimes(2); + } finally { + unmount(); + getSharedWebSocketClient().disconnect(); + vi.unstubAllGlobals(); + } +}); diff --git a/internal/web/controller/inbound.go b/internal/web/controller/inbound.go index ad4020ddf..f89aea5bb 100644 --- a/internal/web/controller/inbound.go +++ b/internal/web/controller/inbound.go @@ -39,18 +39,22 @@ func NewInboundController(g *gin.RouterGroup) *InboundController { // Mirrors the same heuristic used by the periodic traffic job. const broadcastInboundsUpdateClientLimit = 5000 -// broadcastInboundsUpdate fetches and broadcasts the inbound list for userId. -// At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling, -// so we send an invalidate signal instead — frontend re-fetches via REST. -// Skipped entirely when no WebSocket clients are connected. +// broadcastInboundsUpdate sends either a small snapshot or an invalidate. +// Skip all snapshot work when no WebSocket clients are connected. func (a *InboundController) broadcastInboundsUpdate(userId int) { if !websocket.HasClients() { return } + overLimit, err := a.inboundService.InboundClientStatsOverLimit(userId, broadcastInboundsUpdateClientLimit) + if err != nil || overLimit { + websocket.BroadcastInvalidate(websocket.MessageTypeInbounds) + return + } inbounds, err := a.inboundService.GetInbounds(userId) if err != nil { return } + // Stats can grow between the probe and the snapshot read. totalClients := 0 for _, ib := range inbounds { totalClients += len(ib.ClientStats) diff --git a/internal/web/controller/inbound_broadcast_test.go b/internal/web/controller/inbound_broadcast_test.go new file mode 100644 index 000000000..9587de484 --- /dev/null +++ b/internal/web/controller/inbound_broadcast_test.go @@ -0,0 +1,192 @@ +package controller + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/robfig/cron/v3" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/entity" + "github.com/mhsanaei/3x-ui/v3/internal/web/global" + "github.com/mhsanaei/3x-ui/v3/internal/web/session" + "github.com/mhsanaei/3x-ui/v3/internal/web/websocket" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type inboundBroadcastServer struct{ hub *websocket.Hub } + +func (s inboundBroadcastServer) GetWSHub() any { return s.hub } +func (inboundBroadcastServer) GetCtx() context.Context { return context.Background() } +func (inboundBroadcastServer) GetCron() *cron.Cron { return nil } + +func TestInboundMutationSkipsSnapshotReadsAboveWebSocketCutoff(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "panel.db")) + db := database.GetDB() + seed := func(userID, port, count int) model.Inbound { + t.Helper() + row := model.Inbound{UserId: userID, Port: port, Tag: fmt.Sprintf("in-%d", port), Protocol: model.VLESS, Settings: `{"clients":[],"decryption":"none"}`} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + stats := make([]xray.ClientTraffic, count) + for i := range stats { + stats[i] = xray.ClientTraffic{InboundId: row.Id, Email: fmt.Sprintf("client-%d-%d", port, i)} + } + if count > 0 { + if err := db.CreateInBatches(&stats, 100).Error; err != nil { + t.Fatal(err) + } + } + return row + } + const limit = broadcastInboundsUpdateClientLimit + owned := seed(1, 29100, limit-1) + sibling := seed(1, 29101, 0) + seed(2, 29102, limit+1) + attach := func(inbound model.Inbound, statsIndex int) { + t.Helper() + row := model.ClientRecord{Email: fmt.Sprintf("client-%d-%d", owned.Port, statsIndex)} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id} + if err := db.Create(&link).Error; err != nil { + t.Fatal(err) + } + } + attach(sibling, 0) + attach(owned, 1) + + snapshotReads, probes := 0, 0 + if err := db.Callback().Query().After("gorm:query").Register("test:inbound_snapshot", func(tx *gorm.DB) { + sql := tx.Statement.SQL.String() + if _, ok := tx.Statement.Dest.(*[]*model.Inbound); ok && + strings.Contains(sql, "WHERE user_id =") && strings.HasSuffix(sql, "ORDER BY id ASC") { + snapshotReads++ + } + }); err != nil { + t.Fatal(err) + } + if err := db.Callback().Row().After("gorm:row").Register("test:inbound_stats_probe", func(tx *gorm.DB) { + if strings.Contains(tx.Statement.SQL.String(), "AS candidate_stats") { + probes++ + } + }); err != nil { + t.Fatal(err) + } + + router := gin.New() + group := router.Group("/panel/api/inbounds", func(c *gin.Context) { + session.SetAPIAuthUser(c, &model.User{Id: 1}) + }) + NewInboundController(group) + previous := global.GetWebServer() + t.Cleanup(func() { global.SetWebServer(previous) }) + + for i, tc := range []struct { + name string + ws bool + wantType websocket.MessageType + reads int + prepare func() + }{ + {name: "no subscribers"}, + {name: "at cutoff with shared traffic and unrelated user", ws: true, wantType: websocket.MessageTypeInbounds, reads: 1}, + {name: "above cutoff from sibling counter", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { attach(sibling, 2) }}, + {name: "above cutoff from direct traffic", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { seed(1, 29110, 2) }}, + } { + t.Run(tc.name, func(t *testing.T) { + var subscriber *websocket.Client + if tc.ws { + hub := websocket.NewHub() + done := make(chan struct{}) + go func() { + defer close(done) + hub.Run() + }() + t.Cleanup(func() { hub.Stop(); <-done }) + global.SetWebServer(inboundBroadcastServer{hub}) + subscriber = websocket.NewClient("test") + hub.Register(subscriber) + for deadline := time.Now().Add(2 * time.Second); hub.GetClientCount() == 0; { + if time.Now().After(deadline) { + t.Fatal("subscriber did not register") + } + time.Sleep(time.Millisecond) + } + } else { + global.SetWebServer(nil) + } + if tc.prepare != nil { + tc.prepare() + } + snapshotReads, probes = 0, 0 + port := 29103 + i + body := fmt.Sprintf(`{"protocol":"vless","enable":false,"remark":"created","port":%d,"settings":"{\"clients\":[],\"decryption\":\"none\"}","streamSettings":"{\"network\":\"tcp\",\"security\":\"none\"}"}`, port) + req := httptest.NewRequest(http.MethodPost, "/panel/api/inbounds/add", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + var response entity.Msg + if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil || !response.Success { + t.Fatalf("add failed: %s (%v)", rec.Body, err) + } + if snapshotReads != tc.reads { + t.Errorf("full inbound snapshot reads = %d, want %d", snapshotReads, tc.reads) + } + wantProbes := 0 + if tc.ws { + wantProbes = 1 + } + if probes != wantProbes { + t.Errorf("snapshot size probes = %d, want %d", probes, wantProbes) + } + if subscriber == nil { + return + } + select { + case data := <-subscriber.Send: + var event struct { + Type websocket.MessageType + Payload json.RawMessage + } + if err := json.Unmarshal(data, &event); err != nil || event.Type != tc.wantType { + t.Fatalf("unexpected WebSocket type %q: %v, want %q", event.Type, err, tc.wantType) + } + if tc.wantType == websocket.MessageTypeInbounds { + var rows []model.Inbound + if err := json.Unmarshal(event.Payload, &rows); err != nil { + t.Fatal(err) + } + total, created := 0, false + for _, row := range rows { + if row.Port == 29102 { + t.Fatal("snapshot contains another user's inbound") + } + total += len(row.ClientStats) + created = created || row.Port == port + } + if !created || total != limit { + t.Fatalf("snapshot missing updated state: created=%t client stats=%d", created, total) + } + } else if string(event.Payload) != `{"type":"inbounds"}` { + t.Fatalf("unexpected invalidation payload %s", event.Payload) + } + case <-time.After(2 * time.Second): + t.Fatal("mutation did not publish an inbound event") + } + }) + } +} diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 4761e279d..1d9c194db 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -199,6 +199,32 @@ func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) { return inbounds, nil } +// InboundClientStatsOverLimit probes direct stats and eligible sibling counters +// without fetching inbound settings or materializing stats. +func (s *InboundService) InboundClientStatsOverLimit(userID, limit int) (bool, error) { + var count int + // Exact email matches include every row eligible for backfill. Case folding + // can only reduce the number actually appended by backfillClientStats. + err := database.GetDB().Raw(` + SELECT COUNT(*) FROM ( + SELECT 1 + FROM inbounds AS ib + JOIN client_traffics AS stats ON stats.inbound_id = ib.id + WHERE ib.user_id = ? + UNION ALL + SELECT 1 + FROM inbounds AS ib + JOIN client_inbounds AS link ON link.inbound_id = ib.id + JOIN clients AS client ON client.id = link.client_id + JOIN client_traffics AS stats ON stats.email = client.email + WHERE ib.user_id = ? AND client.email <> '' + AND (stats.inbound_id <> ib.id OR stats.inbound_id IS NULL) + LIMIT ? + ) AS candidate_stats + `, userID, userID, limit+1).Row().Scan(&count) + return count > limit, err +} + func (s *InboundService) getInboundsFromDB(db *gorm.DB, userId int) ([]*model.Inbound, error) { var inbounds []*model.Inbound err := db.Model(model.Inbound{}).Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error From bdddb08249f343b2e063bdf4158d18da2cbe6caa Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 13:02:15 +0330 Subject: [PATCH 03/14] fix(nodes): shorten the traffic merge lock window (#7315) Stage existing client traffic updates in snapshot order and flush them after client reconciliation to shorten PostgreSQL row-lock lifetime. Keep configuration, traffic counters, renewals and baselines atomic in the same serialized transaction, preserve concurrent last_sub_fetch updates, and retain rollback and idempotent replay semantics. Batch baseline upserts by (node_id, email) within SQLite parameter limits. Decode snapshot claims before opening the transaction while retaining transactional ownership checks. Add debug metrics for queue wait, writer execution and transaction duration. Validation: all 12 GitHub CI jobs passed on reviewed head 6dc504b67575576c00ec89aca4b646aa409f88e7, including race, PostgreSQL, node and Xray E2E. PostgreSQL CI logs explicitly confirm both contention and baseline batching regressions. The author reports PostgreSQL 16/18 validation, rollback/replay coverage and a reduction from 4,187 baseline upserts to 28 in a local fixture. Scope: this resolves the reproduced subscription row-lock window, not the full serialized writer hold, shared-client cache restriction, historical 41-second SQL tail or cross-process migration/restore deadlock. These require follow-up. No independent production measurements or successful CI run on the exact latest combined revision were verified before merge. Refs #7305 --- .github/workflows/ci.yml | 10 + internal/web/service/inbound_node.go | 132 +++++++++----- internal/web/service/inbound_node_claims.go | 51 ++++-- .../web/service/node_merge_contention_test.go | 172 ++++++++++++++++++ 4 files changed, 299 insertions(+), 66 deletions(-) create mode 100644 internal/web/service/node_merge_contention_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 99def0a71..2e83d681e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,6 +214,16 @@ jobs: exit 1 fi + - name: PostgreSQL node merge contention + run: | + set -o pipefail + go test ./internal/web/service -run '^TestNodeMerge(LetsSubscriptionTouchDuringClientReconciliationPostgres|BatchesBaselinesForActiveClients)$' -count=1 -v | tee /tmp/postgres-node-merge-contention.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-merge-contention.log || true) + if [ "$passed" -ne 2 ]; then + echo "expected both PostgreSQL node merge contention tests to pass, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL schema and migration tests run: | set -o pipefail diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 6f855bda0..5ca1f4bc8 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -248,19 +248,48 @@ type nodeTrafficCounter struct { Down int64 } -func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, counter nodeTrafficCounter, dippedWhileFrozen bool) error { +func upsertNodeBaselines(tx *gorm.DB, changes map[string]model.NodeClientTraffic) error { + if len(changes) == 0 { + return nil + } + rows := make([]model.NodeClientTraffic, 0, len(changes)) + for _, email := range slices.Sorted(maps.Keys(changes)) { + rows = append(rows, changes[email]) + } return tx.Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}}, DoUpdates: clause.AssignmentColumns([]string{"up", "down", "dipped_while_frozen"}), - }).Create(&model.NodeClientTraffic{ - NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dippedWhileFrozen, - }).Error + }).CreateInBatches(rows, sqliteMaxVars/6).Error } -// mergeNodeClientTraffic folds one node-reported client into its central row. -// While frozen (a push pending or just landed) only the counters may move. -func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraffic, canon nodeTrafficCounter, frozen bool, deltaUp, deltaDown, now int64) error { - if frozen { +type nodeClientTrafficWrite struct { + stats xray.ClientTraffic + canon nodeTrafficCounter + deltaUp, deltaDown int64 + frozen, renewed bool +} + +// apply folds a planned change into the existing counter row without touching last_sub_fetch. +func (write nodeClientTrafficWrite) apply(tx *gorm.DB, now int64) error { + cs, canon := write.stats, write.canon + if write.renewed { + if err := tx.Exec( + fmt.Sprintf( + `UPDATE client_traffics + SET up = ?, down = ?, enable = ?, total = ?, + expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s + WHERE email = ?`, + database.GreatestExpr("last_online", "?"), + ), + canon.Up, canon.Down, cs.Enable, cs.Total, + cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount, + cs.LastOnline, cs.Email, + ).Error; err != nil { + return err + } + return clearGlobalTraffic(tx, cs.Email) + } + if write.frozen { return tx.Exec( fmt.Sprintf( `UPDATE client_traffics @@ -270,7 +299,7 @@ func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraff database.ClampedAddExpr("down"), database.GreatestExpr("last_online", "?"), ), - deltaUp, deltaDown, cs.LastOnline, cs.Email, + write.deltaUp, write.deltaDown, cs.LastOnline, cs.Email, ).Error } return tx.Exec( @@ -286,8 +315,8 @@ func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraff database.ClientTrafficExpiryMergeExpr(), database.GreatestExpr("last_online", "?"), ), - deltaUp, deltaDown, - cs.Enable, now, deltaUp, deltaDown, canon.Up, canon.Down, + write.deltaUp, write.deltaDown, + cs.Enable, now, write.deltaUp, write.deltaDown, canon.Up, canon.Down, cs.Total, cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.LastOnline, cs.Email, @@ -433,11 +462,15 @@ func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime. // config push just landed, whose snapshot may still predate it (#6228). func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { var structuralChange bool + queuedAt := time.Now() // Node merges take the background lane: a per-client mutation the operator // is waiting on must not queue behind the next batch of 5s snapshots. err := submitTrafficWriteBackground(func() error { + started := time.Now() var inner error structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty, justPushed) + logger.Debugf("node traffic writer: node_id=%d queue_wait_ms=%d writer_ms=%d success=%t", + nodeID, started.Sub(queuedAt).Milliseconds(), time.Since(started).Milliseconds(), inner == nil) return inner }) if err != nil { @@ -793,18 +826,27 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + var claimInputs nodeClaimInputs + if !skipStructure { + claimInputs = readNodeClaimInputs(snap) + } + txStarted := time.Now() tx := db.Begin() + if tx.Error != nil { + return false, tx.Error + } committed := false defer func() { if !committed { tx.Rollback() + logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=false", nodeID, time.Since(txStarted).Milliseconds()) } }() claims := &nodeClientClaims{} rawSettings := make(map[*model.Inbound]string, len(snap.Inbounds)) if !skipStructure { - claims, err = loadNodeClientClaims(tx, nodeID, snap) + claims, err = loadNodeClientClaims(tx, nodeID, claimInputs) if err != nil { return false, err } @@ -1167,6 +1209,19 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + baselineChanges := make(map[string]model.NodeClientTraffic) + var trafficWrites []nodeClientTrafficWrite + stageBaseline := func(email string, counter nodeTrafficCounter, dipped bool) { + baselineChanges[email] = model.NodeClientTraffic{ + NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dipped, + } + nodeBaselines[email] = counter + if dipped { + dippedWhileFrozen[email] = true + } else { + delete(dippedWhileFrozen, email) + } + } for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -1260,11 +1315,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi activatedEmails[row.Email] = struct{}{} } structuralChange = true - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, false); err != nil { - return false, err - } - nodeBaselines[cs.Email] = canon - delete(dippedWhileFrozen, cs.Email) + stageBaseline(cs.Email, canon, false) continue } @@ -1295,23 +1346,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if renewed { // A renewal starts a fresh quota window: adopt the node's counters // and enable state, drop stale pushes (mirrors autoRenewClients). - if err := tx.Exec( - fmt.Sprintf( - `UPDATE client_traffics - SET up = ?, down = ?, enable = ?, total = ?, - expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s - WHERE email = ?`, - database.GreatestExpr("last_online", "?"), - ), - canon.Up, canon.Down, cs.Enable, cs.Total, - cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount, - cs.LastOnline, cs.Email, - ).Error; err != nil { - return false, err - } - if err := clearGlobalTraffic(tx, cs.Email); err != nil { - return false, err - } + trafficWrites = append(trafficWrites, nodeClientTrafficWrite{stats: cs, canon: canon, renewed: true}) existing.Up = canon.Up existing.Down = canon.Down existing.Enable = cs.Enable @@ -1343,9 +1378,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi // A multi-attached client is reported once per inbound and an idle one // every tick: rewriting an unchanged row only holds its lock longer. if next != *row { - if err := s.mergeNodeClientTraffic(tx, cs, canon, clientFrozen, deltaUp, deltaDown, now); err != nil { - return false, err - } + trafficWrites = append(trafficWrites, nodeClientTrafficWrite{ + stats: cs, canon: canon, frozen: clientFrozen, deltaUp: deltaUp, deltaDown: deltaDown, + }) if row.ExpiryTime <= 0 && next.ExpiryTime > 0 { activatedEmails[cs.Email] = struct{}{} } @@ -1358,15 +1393,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if seen && base == canon && stillOwed == dippedWhileFrozen[cs.Email] { continue } - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, stillOwed); err != nil { - return false, err - } - nodeBaselines[cs.Email] = canon - if stillOwed { - dippedWhileFrozen[cs.Email] = true - } else { - delete(dippedWhileFrozen, cs.Email) - } + stageBaseline(cs.Email, canon, stillOwed) } if skipStructure { @@ -1509,7 +1536,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi adoptedSettings := p.wireSettings liftChanged := false if adopt && !isNew { - // Use the traffic deltas just applied to this transaction (#6228). + // Use the staged traffic values before flushing their SQL updates (#6228). if lifted, changed := liftClientLifecycleInSettings(p.wireSettings, statByEmail); changed { adoptedSettings, liftChanged = lifted, true } @@ -1595,6 +1622,16 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + if err := upsertNodeBaselines(tx, baselineChanges); err != nil { + return false, err + } + // Client reconciliation used the planned traffic values in memory. Lock + // the existing traffic rows only now, in snapshot order, before commit. + for _, write := range trafficWrites { + if err := write.apply(tx, now); err != nil { + return false, err + } + } for _, emails := range chunkStrings(slices.Sorted(maps.Keys(activatedEmails)), sqlInChunk) { if err := liftActivatedClientRecordExpiries(tx.Model(&model.ClientRecord{}).Where("email IN ?", emails)); err != nil { return false, err @@ -1605,6 +1642,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi return false, err } committed = true + logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=true", nodeID, time.Since(txStarted).Milliseconds()) if adoptedSettingsChanged { InvalidateSubData() } diff --git a/internal/web/service/inbound_node_claims.go b/internal/web/service/inbound_node_claims.go index 1e655a591..248a587c9 100644 --- a/internal/web/service/inbound_node_claims.go +++ b/internal/web/service/inbound_node_claims.go @@ -39,17 +39,20 @@ var nodeKeptSharedKeys = []string{"flow", "privateKey", "publicKey", "allowedIPs type clientLinkScope struct{ here, elsewhere bool } -func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot) (*nodeClientClaims, error) { - claims := &nodeClientClaims{ - refused: map[string]string{}, - shared: map[string]*model.ClientRecord{}, - storedSubID: map[string]string{}, - usageOnly: map[string]struct{}{}, +type nodeClaimInputs struct { + subIDByEmail map[string]string + refused map[string]string + sharesSubID map[string]struct{} +} + +func readNodeClaimInputs(snap *runtime.TrafficSnapshot) nodeClaimInputs { + inputs := nodeClaimInputs{ + subIDByEmail: map[string]string{}, + refused: map[string]string{}, + sharesSubID: map[string]struct{}{}, } - subIDByEmail := map[string]string{} // A subId selects a whole subscription, so within one snapshot it may name one client only. firstEmailBySub := map[string]string{} - sharesSubID := map[string]struct{}{} for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -64,28 +67,38 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot continue } if c.Email != strings.TrimSpace(c.Email) { - claims.refused[c.Email] = "its email carries surrounding white space" + inputs.refused[c.Email] = "its email carries surrounding white space" continue } - if _, seen := subIDByEmail[c.Email]; !seen { + if _, seen := inputs.subIDByEmail[c.Email]; !seen { var subID string _ = json.Unmarshal(c.SubID, &subID) - subIDByEmail[c.Email] = subID + inputs.subIDByEmail[c.Email] = subID if first, taken := firstEmailBySub[subID]; subID != "" && taken && !strings.EqualFold(first, c.Email) { - sharesSubID[c.Email] = struct{}{} + inputs.sharesSubID[c.Email] = struct{}{} } else if subID != "" && !taken { firstEmailBySub[subID] = c.Email } } } } - if len(subIDByEmail) == 0 { + return inputs +} + +func loadNodeClientClaims(tx *gorm.DB, nodeID int, inputs nodeClaimInputs) (*nodeClientClaims, error) { + claims := &nodeClientClaims{ + refused: inputs.refused, + shared: map[string]*model.ClientRecord{}, + storedSubID: map[string]string{}, + usageOnly: map[string]struct{}{}, + } + if len(inputs.subIDByEmail) == 0 { logRefusedClaims(nodeID, claims.refused) return claims, nil } - reported := make([]string, 0, len(subIDByEmail)) - for email := range subIDByEmail { + reported := make([]string, 0, len(inputs.subIDByEmail)) + for email := range inputs.subIDByEmail { reported = append(reported, email) } // SQLite's LOWER folds ASCII only, so a non-ASCII capital is matched by its spellings too. @@ -104,8 +117,8 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot byLower[strings.ToLower(records[i].Email)] = records[i].Email } - subIDs := make([]string, 0, len(subIDByEmail)) - for _, subID := range subIDByEmail { + subIDs := make([]string, 0, len(inputs.subIDByEmail)) + for _, subID := range inputs.subIDByEmail { if subID != "" { subIDs = append(subIDs, subID) } @@ -132,7 +145,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot holdersBySub[h.SubID] = append(holdersBySub[h.SubID], h) } subIDTaken := func(email, subID string) bool { - if _, shared := sharesSubID[email]; shared { + if _, shared := inputs.sharesSubID[email]; shared { return true } for _, h := range holdersBySub[subID] { @@ -143,7 +156,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot return false } - for email, subID := range subIDByEmail { + for email, subID := range inputs.subIDByEmail { rec, exact := byEmail[email] if !exact { if _, variant := byLower[strings.ToLower(email)]; variant { diff --git a/internal/web/service/node_merge_contention_test.go b/internal/web/service/node_merge_contention_test.go new file mode 100644 index 000000000..b5721132b --- /dev/null +++ b/internal/web/service/node_merge_contention_test.go @@ -0,0 +1,172 @@ +package service + +import ( + "context" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/config" + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestNodeMergeLetsSubscriptionTouchDuringClientReconciliationPostgres(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL row locks") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "contention.db")) + node := &model.Node{Name: "merge-lock-window", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const email = "subscription-touch@example.test" + snapshot := func(up, quota int64) *runtime.TrafficSnapshot { + settings := fmt.Sprintf(`{"clients":[{"email":%q,"subId":"touch-sub","enable":true,"totalGB":%d}]}`, email, quota) + return snapshotWithClients(t, "contention", settings, xray.ClientTraffic{Email: email, Up: up, Enable: true, Total: quota}) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil { + t.Fatal(err) + } + before := readTraffic(t, db, email) + + const touchedAt = 1730000000123 + probed := false + var probeErr error + if err := db.Callback().Update().Before("gorm:update").Register("test:touch_during_reconcile", func(tx *gorm.DB) { + if tx.Statement.Table != "clients" || probed { + return + } + probed = true + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + probeErr = db.WithContext(ctx).Transaction(func(other *gorm.DB) error { + if err := other.Exec("SET LOCAL lock_timeout = '150ms'").Error; err != nil { + return err + } + return other.Model(&xray.ClientTraffic{}). + Where("email IN (SELECT email FROM clients WHERE sub_id = ?)", "touch-sub"). + Update("last_sub_fetch", touchedAt).Error + }) + }); err != nil { + t.Fatal(err) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err != nil { + t.Fatal(err) + } + if !probed || probeErr != nil { + t.Fatalf("subscription update during client reconciliation: probed=%t err=%v", probed, probeErr) + } + if after := readTraffic(t, db, email); after.Up != before.Up+30 || after.Total != 2000 || after.LastSubFetch != touchedAt { + t.Fatalf("merge or subscription touch lost data: before=%+v after=%+v", before, after) + } +} + +func TestNodeMergeBatchesBaselinesForActiveClients(t *testing.T) { + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "batch.db")) + node := &model.Node{Name: "batch-baselines", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const clients = 24 + snapshot := func(up int64) *runtime.TrafficSnapshot { + rows := make([]xray.ClientTraffic, 0, clients) + entries := make([]model.Client, 0, clients) + for i := range clients { + email := fmt.Sprintf("batch-%d@x", i) + rows = append(rows, xray.ClientTraffic{Email: email, Enable: true, Up: up}) + entries = append(entries, model.Client{Email: email, Enable: true}) + } + return snapshotWithClients(t, "batch-baselines", clientsSettings(t, entries), rows...) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100), false, false); err != nil { + t.Fatal(err) + } + trace := &snapshotReadLog{Interface: logger.Discard} + previous := db.Logger + db.Logger = trace + t.Cleanup(func() { db.Logger = previous }) + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(107), false, false); err != nil { + t.Fatal(err) + } + writes := 0 + for _, sql := range trace.statements { + if strings.HasPrefix(strings.ToUpper(sql), "INSERT INTO") && strings.Contains(sql, "node_client_traffics") { + writes++ + } + } + if writes != 1 { + t.Errorf("baseline upserts=%d for %d changed clients, want one", writes, clients) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(107), false, false); err != nil { + t.Fatal(err) + } + var rows []model.NodeClientTraffic + if err := db.Where("node_id = ?", node.Id).Find(&rows).Error; err != nil { + t.Fatal(err) + } + if len(rows) != clients { + t.Fatalf("stored %d baselines, want %d", len(rows), clients) + } + for _, row := range rows { + if row.Up != 107 { + t.Errorf("%s baseline up=%d, want 107", row.Email, row.Up) + } + if traffic := readTraffic(t, db, row.Email); traffic.Up != 107 { + t.Errorf("%s stored up=%d, want one 7-byte delta on top of adoption", row.Email, traffic.Up) + } + } +} + +func TestNodeMergeRollsBackConfigTrafficAndBaselineOnLateWriteFailure(t *testing.T) { + if config.GetDBKind() == database.DialectPostgres { + t.Skip("uses a SQLite trigger to fail the final traffic update") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "rollback.db")) + node := &model.Node{Name: "late-traffic-rollback", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const email = "late-traffic@x" + snapshot := func(up, quota int64) *runtime.TrafficSnapshot { + settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true,"totalGB":%d}]}`, email, quota) + return snapshotWithClients(t, "late-write", settings, xray.ClientTraffic{Email: email, Up: up, Enable: true, Total: quota}) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil { + t.Fatal(err) + } + if err := db.Exec(`CREATE TRIGGER fail_late_traffic BEFORE UPDATE OF up ON client_traffics + WHEN NEW.email = 'late-traffic@x' AND NEW.up > OLD.up + BEGIN SELECT RAISE(ABORT, 'injected late traffic failure'); END`).Error; err != nil { + t.Fatal(err) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err == nil || !strings.Contains(err.Error(), "injected late traffic failure") { + t.Fatalf("merge failure=%v, want triggered write failure", err) + } + assertState := func(up, quota int64) { + t.Helper() + var baseline model.NodeClientTraffic + if err := db.Where("node_id = ? AND email = ?", node.Id, email).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + traffic := readTraffic(t, db, email) + record := lookupClientRecord(t, email) + if baseline.Up != up || traffic.Up != up || traffic.Total != quota || record.TotalGB != quota { + t.Fatalf("inconsistent merge: baseline=%d up=%d traffic quota=%d record quota=%d", baseline.Up, traffic.Up, traffic.Total, record.TotalGB) + } + } + assertState(100, 1000) + if err := db.Exec("DROP TRIGGER fail_late_traffic").Error; err != nil { + t.Fatal(err) + } + for range 2 { + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err != nil { + t.Fatal(err) + } + } + assertState(130, 2000) +} From 2e0c751a807b2b1446513845e3219d76eb53ad44 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 14:23:45 +0330 Subject: [PATCH 04/14] fix(nodes): order client pushes outside inbound mutation locks (#7314) Release inbound mutation locks after durable local commit and reserve conflicting remote dispatch turns in writer commit order. Allow independent inbounds to progress concurrently while reconciliation and full client deletes retain node-wide ordering. Bound queue waits and live batches separately, advance dirty revisions strictly, and invalidate only affected remote fingerprints. Persist permanent-delete intents transactionally per node/email and replay bounded pages during reconciliation. Match acknowledgements to the queued generation and retain failed/ambiguous deliveries. Supersede pending deletes only when the client is desired on the target node, so recreation on another node does not leave an old orphan record. Preserve pending rows during database migration and accept legacy backups without the outbox table. Validation: reproduced the cross-node orphan on the previous head; fixed regression passed locally on Lenovo with focused SQLite (9/9) and PostgreSQL 16 (7/7). All 12 CI jobs passed on 5459316fbd38fa4a4380a203e2548f697f5c2a49 (run 46862646487), including race, PostgreSQL migration and durable-first, and node/Xray E2E. PostgreSQL logs confirm all seven ordering tests including cross-node recreation, lost acknowledgement and bulk recovery after database reopen. Branch is up to date with main. No measured production latency claim; requests still wait for their own bounded ordered remote apply. Coordinate overlapping #7308 before its integration. Fixes #7304. --- .github/workflows/ci.yml | 10 + internal/database/db.go | 1 + internal/database/migrate_data.go | 12 + internal/database/migrate_data_test.go | 46 +- .../model/node_pending_client_delete.go | 10 + internal/web/runtime/reconcile_skip_test.go | 32 + internal/web/runtime/remote.go | 64 +- internal/web/service/client_bulk.go | 134 ++-- internal/web/service/client_inbound_apply.go | 190 +++-- internal/web/service/client_link.go | 17 +- internal/web/service/client_node_dispatch.go | 194 +++++ .../web/service/client_node_order_test.go | 734 ++++++++++++++++++ internal/web/service/client_node_push_test.go | 25 +- internal/web/service/inbound_node.go | 14 +- internal/web/service/inbound_traffic.go | 13 +- internal/web/service/inbound_traffic_apply.go | 41 +- internal/web/service/node.go | 6 +- .../web/service/node_bulk_dispatch_test.go | 4 +- .../web/service/node_client_delete_queue.go | 123 +++ .../service/node_reset_undelivered_test.go | 2 +- internal/web/service/traffic_writer.go | 8 + 21 files changed, 1473 insertions(+), 207 deletions(-) create mode 100644 internal/database/model/node_pending_client_delete.go create mode 100644 internal/web/service/client_node_dispatch.go create mode 100644 internal/web/service/client_node_order_test.go create mode 100644 internal/web/service/node_client_delete_queue.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e83d681e..cd6827ab2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,6 +144,16 @@ jobs: exit 1 fi + - name: PostgreSQL node client push ordering + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) + if [ "$passed" -ne 7 ]; then + echo "expected 7 passing PostgreSQL node client ordering tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL global-traffic heartbeat regressions run: | set -o pipefail diff --git a/internal/database/db.go b/internal/database/db.go index 666f737da..f5f530211 100644 --- a/internal/database/db.go +++ b/internal/database/db.go @@ -91,6 +91,7 @@ func allModels() []any { &model.NodeClientIp{}, &model.ClientGlobalTraffic{}, &model.NodePendingReset{}, + &model.NodePendingClientDelete{}, &model.OutboundSubscription{}, &model.SubBalancer{}, &model.TuicTrafficReceipt{}, diff --git a/internal/database/migrate_data.go b/internal/database/migrate_data.go index b9e840104..0f7bf68e8 100644 --- a/internal/database/migrate_data.go +++ b/internal/database/migrate_data.go @@ -8,6 +8,7 @@ import ( "os" "path" "reflect" + "slices" "strings" "time" @@ -59,6 +60,7 @@ func migrationModels() []any { &model.NodeClientIp{}, &model.ClientGlobalTraffic{}, &model.NodePendingReset{}, + &model.NodePendingClientDelete{}, &model.OutboundSubscription{}, &model.SubBalancer{}, &model.TuicTrafficReceipt{}, @@ -225,6 +227,16 @@ func copyTable(src, dst *gorm.DB, mdl any) (int, error) { } order := strings.Join(stmt.Schema.PrimaryFieldDBNames, ", ") table := stmt.Schema.Table + if _, optional := mdl.(*model.NodePendingClientDelete); optional { + // Backups predating the outbox have no pending deletes to copy. + tables, err := src.Migrator().GetTables() + if err != nil { + return 0, err + } + if !slices.Contains(tables, table) { + return 0, nil + } + } columns := stmt.Schema.DBNames ctx := context.Background() diff --git a/internal/database/migrate_data_test.go b/internal/database/migrate_data_test.go index 685463dd0..16d959a17 100644 --- a/internal/database/migrate_data_test.go +++ b/internal/database/migrate_data_test.go @@ -18,13 +18,16 @@ func TestMigrateData_CompositeKeyTableLargerThanBatch(t *testing.T) { t.Skip("set XUI_TEST_PG_DSN to a reachable Postgres to run this test") } - // Seed a SQLite source with the full schema and >500 client_inbounds rows. + // Seed a pre-outbox SQLite source with >500 client_inbounds rows. srcPath := t.TempDir() + "/x-ui.db" src, err := gorm.Open(sqlite.Open(srcPath), &gorm.Config{Logger: logger.Discard}) if err != nil { t.Fatalf("open sqlite: %v", err) } for _, m := range migrationModels() { + if _, pending := m.(*model.NodePendingClientDelete); pending { + continue + } if err := src.AutoMigrate(m); err != nil { t.Fatalf("automigrate %T: %v", m, err) } @@ -61,6 +64,9 @@ func TestMigrateData_CompositeKeyTableLargerThanBatch(t *testing.T) { if got != n { t.Fatalf("client_inbounds rows = %d, want %d", got, n) } + if err := dst.Model(&model.NodePendingClientDelete{}).Count(&got).Error; err != nil || got != 0 { + t.Fatalf("migrated pending delete rows = %d, want 0 (%v)", got, err) + } } func TestMigrateData_PreservesFalseDefaultedColumns(t *testing.T) { @@ -207,3 +213,41 @@ func TestMigrateData_FailedCopyLeavesDestinationUntouched(t *testing.T) { t.Fatalf("failed migration leaked partial rows: evil count = %d, want 0", evil) } } + +func TestCopyPendingClientDeletesAcceptsLegacySourceAndPreservesNewRows(t *testing.T) { + openDB := func(path string) *gorm.DB { + t.Helper() + db, err := gorm.Open(sqlite.Open(path), &gorm.Config{Logger: logger.Discard}) + if err != nil { + t.Fatal(err) + } + conn, err := db.DB() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + return db + } + src := openDB(t.TempDir() + "/source.db") + dst := openDB(t.TempDir() + "/destination.db") + pending := &model.NodePendingClientDelete{NodeId: 1, Email: "pending@example.test", ClientId: 3, Generation: "queue-generation", LastAttemptAt: 17} + if err := dst.AutoMigrate(pending); err != nil { + t.Fatal(err) + } + if n, err := copyTable(src, dst, pending); err != nil || n != 0 { + t.Fatalf("copy from source without delete queue: %d rows, %v", n, err) + } + if err := src.AutoMigrate(pending); err != nil { + t.Fatal(err) + } + if err := src.Create(pending).Error; err != nil { + t.Fatal(err) + } + if n, err := copyTable(src, dst, pending); err != nil || n != 1 { + t.Fatalf("copy persisted delete queue: %d rows, %v", n, err) + } + var got model.NodePendingClientDelete + if err := dst.Take(&got).Error; err != nil || got != *pending { + t.Fatalf("copied delete intent = %+v, want %+v (%v)", got, pending, err) + } +} diff --git a/internal/database/model/node_pending_client_delete.go b/internal/database/model/node_pending_client_delete.go new file mode 100644 index 000000000..9d48cc53d --- /dev/null +++ b/internal/database/model/node_pending_client_delete.go @@ -0,0 +1,10 @@ +package model + +// NodePendingClientDelete tracks a permanent delete that the node has not confirmed. +type NodePendingClientDelete struct { + NodeId int `gorm:"primaryKey;autoIncrement:false;index:idx_node_delete_order,priority:1"` + Email string `gorm:"primaryKey;index:idx_node_delete_order,priority:3"` + ClientId int `gorm:"not null"` + Generation string `gorm:"not null"` + LastAttemptAt int64 `gorm:"not null;index:idx_node_delete_order,priority:2"` +} diff --git a/internal/web/runtime/reconcile_skip_test.go b/internal/web/runtime/reconcile_skip_test.go index 7bff47238..1d7ba96f0 100644 --- a/internal/web/runtime/reconcile_skip_test.go +++ b/internal/web/runtime/reconcile_skip_test.go @@ -65,6 +65,38 @@ func TestReconcileInbound_SkipsUnchanged(t *testing.T) { } } +func TestDeleteClientInvalidatesOnlyInboundsStampedWithThatClient(t *testing.T) { + for _, response := range []struct { + name string + body string + failed bool + }{ + {name: "acknowledged", body: `{"success":true}`}, + {name: "uncertain", body: `{"success":false,"msg":"apply failed"}`, failed: true}, + } { + t.Run(response.name, func(t *testing.T) { + srv, _ := newCountingNodeServer(t, response.body) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + affected := &model.Inbound{Tag: "in-1", Protocol: model.VLESS, Settings: `{"clients":[{"email":"delete@example.test"}]}`} + unaffected := &model.Inbound{Tag: "in-2", Protocol: model.VLESS, Settings: `{"clients":[{"email":"keep@example.test"}]}`} + r.AdoptInboundAlias(affected, RemoteInboundOption{Tag: "adopted-1", Id: 1}) + r.AdoptInboundAlias(unaffected, RemoteInboundOption{Tag: "adopted-2", Id: 2}) + if err := r.DeleteClient(t.Context(), "delete@example.test"); (err != nil) != response.failed { + t.Fatalf("unexpected delete result: %v", err) + } + if pushed, err := r.ReconcileInbound(t.Context(), unaffected, true); err != nil || pushed { + t.Fatalf("unaffected inbound: pushed=%v err=%v", pushed, err) + } + if pushed, err := r.ReconcileInbound(t.Context(), affected, true); err != nil || !pushed { + t.Fatalf("affected inbound: pushed=%v err=%v", pushed, err) + } + if id, err := r.resolveRemoteID(t.Context(), unaffected.Tag); err != nil || id != 2 { + t.Fatalf("unaffected alias: id=%d err=%v", id, err) + } + }) + } +} + type nodeCallCounts struct { adds atomic.Int32 inboundUpdates atomic.Int32 diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index df8e2d721..8a2288868 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -97,7 +97,7 @@ type Remote struct { // pushedFP holds the fingerprint of the last inbound wire payload successfully // pushed, keyed by panel-side tag, so reconcile can skip re-sending an // unchanged inbound. Guarded by mu; dropped with the Remote on node config change. - pushedFP map[string]string + pushedFP map[string]pushedInboundState // supportsZstd is learned from the node's X-3x-Node-Caps response header; once // seen, config pushes to this node are zstd-compressed. Old nodes never set // it, so they keep receiving plain bodies (mixed-version safe). @@ -137,7 +137,7 @@ func NewRemote(n *model.Node, r NodeEgressResolver) *Remote { snapshotGate: make(chan struct{}, 1), remoteIDByTag: make(map[string]int), adoptedAliases: make(map[string]string), - pushedFP: make(map[string]string), + pushedFP: make(map[string]pushedInboundState), egressResolver: r, } } @@ -655,7 +655,7 @@ func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, exists r.mu.RLock() prev, ok := r.pushedFP[ib.Tag] r.mu.RUnlock() - if ok && prev == fp { + if ok && prev.fingerprint == fp { return false, nil } } else { @@ -670,9 +670,9 @@ func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, exists // recordPushedInbound stamps the fingerprint after a full-payload push — the // only operation that proves the node holds the entire wire payload. func (r *Remote) recordPushedInbound(ib *model.Inbound) { - fp := wireFingerprint(wireInbound(ib, r.node.Id)) + state := stampPushedInbound(ib, r.node.Id) r.mu.Lock() - r.pushedFP[ib.Tag] = fp + r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -713,11 +713,12 @@ func (r *Remote) ForgetInbound(tag string) { // AdoptInboundAlias records a deployed alias without mutating either panel. // The runtime association is rediscovered after a master restart. func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption) { + state := stampPushedInbound(ib, r.node.Id) r.mu.Lock() r.remoteIDByTag[remote.Tag] = remote.Id r.remoteIDByTag[ib.Tag] = remote.Id r.adoptedAliases[ib.Tag] = remote.Tag - r.pushedFP[ib.Tag] = wireFingerprint(wireInbound(ib, r.node.Id)) + r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -738,14 +739,50 @@ func (r *Remote) AdoptedInboundAliases() []string { // the next reconcile re-sends the full inbound. func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) { prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id)) - nextFP := wireFingerprint(wireInbound(ib, r.node.Id)) + next := stampPushedInbound(ib, r.node.Id) r.mu.Lock() - if r.pushedFP[ib.Tag] == prevFP { - r.pushedFP[ib.Tag] = nextFP + if r.pushedFP[ib.Tag].fingerprint == prevFP { + r.pushedFP[ib.Tag] = next } r.mu.Unlock() } +type pushedInboundClient struct { + Email string `json:"email"` +} + +type pushedInboundState struct { + fingerprint string + clients []pushedInboundClient + clientsKnown bool +} + +func stampPushedInbound(ib *model.Inbound, nodeID int) pushedInboundState { + var settings struct { + Clients []pushedInboundClient `json:"clients"` + } + err := json.Unmarshal([]byte(ib.Settings), &settings) + return pushedInboundState{ + fingerprint: wireFingerprint(wireInbound(ib, nodeID)), + clients: settings.Clients, + clientsKnown: err == nil, + } +} + +// A node-wide delete can remove a client from several inbounds, even when its +// reply times out. Only those previously stamped with that client can change. +func (r *Remote) forgetPushedClient(email string) { + r.mu.Lock() + defer r.mu.Unlock() + for tag, state := range r.pushedFP { + if !state.clientsKnown || slices.ContainsFunc(state.clients, func(client pushedInboundClient) bool { + return client.Email == email + }) { + delete(r.pushedFP, tag) + } + } +} + // wireFingerprint hashes a wire payload so an unchanged inbound is cheap to detect. func wireFingerprint(v url.Values) string { sum := sha256.Sum256([]byte(v.Encode())) @@ -805,12 +842,17 @@ func (r *Remote) DeleteClient(ctx context.Context, email string) error { } _, err := r.do(ctx, http.MethodPost, "panel/api/clients/del/"+url.PathEscape(email), nil) + r.forgetPushedClient(email) if err == nil { return nil } var apiErr *remoteAPIError - if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.msg), "not found") { - return nil + if errors.As(err, &apiErr) { + absent := fmt.Sprintf("client %q not found in any inbound or client record", email) + message := strings.TrimSpace(apiErr.msg) + if message == absent || strings.HasSuffix(message, " ("+absent+")") { + return nil + } } return err } diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index ea249ba19..5bb9050eb 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "slices" "strings" "time" @@ -681,7 +682,8 @@ func (s *ClientService) bulkAdjustInboundClients( adTagIneligible: map[string]bool{}, } - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -816,7 +818,7 @@ func (s *ClientService) bulkAdjustInboundClients( // Serialize against the traffic poll to avoid the cross-transaction // lock-order deadlock on inbounds/client_records (runSerializedTx). - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil { return err } @@ -827,9 +829,6 @@ func (s *ClientService) bulkAdjustInboundClients( if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }) if txErr != nil { @@ -847,28 +846,28 @@ func (s *ClientService) bulkAdjustInboundClients( if perr != nil { logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr) } else if push { - for email := range foundEmails { - entry := plan[email] - updated := *entry.record.ToClient() - if entry.applyExpiry { - updated.ExpiryTime = entry.newExpiry + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for email := range foundEmails { + entry := plan[email] + updated := *entry.record.ToClient() + if entry.applyExpiry { + updated.ExpiryTime = entry.newExpiry + } + if entry.applyTotal { + updated.TotalGB = entry.newTotal + } + if adTag != "" && oldInbound.Protocol == model.MTProto { + updated.AdTag = wantAdTag + } + updated.UpdatedAt = nowMs + err := rt.UpdateUser(ctx, oldInbound, email, updated) + if err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } } - if entry.applyTotal { - updated.TotalGB = entry.newTotal - } - if adTag != "" && oldInbound.Protocol == model.MTProto { - updated.AdTag = wantAdTag - } - updated.UpdatedAt = nowMs - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, email, updated) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - // First failure ends the batch push; the reconcile converges the rest. - break - } - } + return true + }) } } } @@ -1057,7 +1056,8 @@ func (s *ClientService) bulkDelInboundClients( res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}} defer InvalidateSubData() - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1190,9 +1190,17 @@ func (s *ClientService) bulkDelInboundClients( } } - // Serialize against the traffic poll to avoid the cross-transaction - // lock-order deadlock on inbounds/client_records (runSerializedTx). - txErr := runSerializedTx(func(tx *gorm.DB) error { + var dispatchEmails []string + if oldInbound.NodeID != nil { + for email := range wantedEmails { + if _, skip := res.perEmailSkipped[email]; !skip { + dispatchEmails = append(dispatchEmails, email) + } + } + slices.Sort(dispatchEmails) + } + var pending []model.NodePendingClientDelete + txErr := mutation.commit(oldInbound, nodeFullClientDelete, func(tx *gorm.DB) error { if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil { return err } @@ -1203,10 +1211,8 @@ func (s *ClientService) bulkDelInboundClients( if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } - return nil + pending, err = queueNodeClientDeletes(tx, oldInbound.NodeID, dispatchEmails) + return err }) if txErr != nil { for email := range wantedEmails { @@ -1238,30 +1244,22 @@ func (s *ClientService) bulkDelInboundClients( } } } else { - dispatchEmails := make([]string, 0, len(wantedEmails)) - for email := range wantedEmails { - if _, skip := res.perEmailSkipped[email]; !skip { - dispatchEmails = append(dispatchEmails, email) - } - } - if len(dispatchEmails) > nodeBulkPushThreshold { + if len(pending) == 0 || len(pending) > nodeBulkPushThreshold { return res } rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { logger.Warning("BulkDelete: node runtime lookup after commit failed:", perr) } else if push { - for _, email := range dispatchEmails { - ctx, cancel := nodePushContext() - err1 := rt.DeleteClient(ctx, email) - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err1) - // The node is already dirty, so one reconcile converges the rest of - // the batch instead of paying another deadline per client. - break + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for _, row := range pending { + if err := applyNodeClientDelete(ctx, rt, row); err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } } - } + return true + }) } } @@ -1714,7 +1712,8 @@ func applyBulkSidecar(inboundSvc *InboundService, inboundId int, protocol model. func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult { res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}} - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1813,7 +1812,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, push = false } - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil { return e } @@ -1824,9 +1823,6 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }) if txErr != nil { @@ -1862,23 +1858,19 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, } } } else if push { - pushFailed := false - for _, ch := range changed { - updated := ch.client - updated.UpdatedAt = nowMs - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, ch.email, updated) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - pushFailed = true - // First failure ends the batch push; the reconcile converges the rest. - break + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for _, ch := range changed { + updated := ch.client + updated.UpdatedAt = nowMs + err := rt.UpdateUser(ctx, oldInbound, ch.email, updated) + if err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } } - } - if !pushFailed { advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) } return res diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 6a1c4842c..2ee15e988 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -140,7 +140,8 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if len(recs) == 0 { return false, nil } - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -248,7 +249,7 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId // Persist the batch deletion atomically, serialized against the traffic poll // to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { for _, t := range targets { if t.emailShared || keepTraffic { continue @@ -276,63 +277,50 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if err := s.ApplyInboundClientDelta(tx, inboundId, nil, detached); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return needRestart, txErr } - // Resolve the node push plan once for the whole batch instead of per email. - var nodeRt runtime.Runtime - nodePush := false if oldInbound.NodeID != nil { rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { return needRestart, perr } - nodeRt, nodePush = rt, push - // Large batches collapse into one reconcile push rather than M deletes. - if nodePush && len(targets) > nodeBulkPushThreshold { - nodePush = false + if push && len(targets) <= nodeBulkPushThreshold { + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for _, target := range targets { + if target.email == "" { + continue + } + err := rt.DeleteUser(ctx, oldInbound, target.email) + if err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } + } + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + return true + }) } + return needRestart, nil } - // Apply runtime deletes after commit — outside the serialized writer so a - // slow node call can't stall traffic accounting. - nodePushFailed := false for _, t := range targets { - if len(t.email) == 0 { + if t.email == "" || !t.needApiDel || !t.notDepleted { continue } - if oldInbound.NodeID == nil { - if t.needApiDel && t.notDepleted { - rt, rterr := inboundSvc.runtimeFor(oldInbound) - if rterr != nil { - needRestart = true - } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil { - if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) { - needRestart = true - } - } else if endDroppedClientSessions(oldInbound) { - needRestart = true - } - } - } else if nodePush && !nodePushFailed { - // First failure ends the batch push; the reconcile converges the rest. - ctx, cancel := nodePushContext() - err1 := nodeRt.DeleteUser(ctx, oldInbound, t.email) - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1) - nodePushFailed = true + rt, rterr := inboundSvc.runtimeFor(oldInbound) + if rterr != nil { + needRestart = true + } else if err := rt.RemoveUser(context.Background(), oldInbound, t.email); err != nil { + if !strings.Contains(err.Error(), fmt.Sprintf("User %s not found.", t.email)) { + needRestart = true } + } else if endDroppedClientSessions(oldInbound) { + needRestart = true } } - if nodePush && !nodePushFailed { - advancePushedInbound(nodeRt, prevSettings, string(newSettings), oldInbound) - } return needRestart, nil } @@ -406,8 +394,8 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) { defer InvalidateSubData() - lock := lockInbound(data.Id) - defer lock.Unlock() + mutation := beginInboundClientMutation(data.Id) + defer mutation.close() clients, err := inboundSvc.GetClients(data) if err != nil { @@ -611,7 +599,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } needRestart := false - nextOrphanOffset := lock.orphanOffset + nextOrphanOffset := mutation.lock.orphanOffset prunedOrphans := false rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) @@ -621,7 +609,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model // Persist client stats + inbound atomically, serialized against the traffic // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { // lockInbound is per-inbound, so the pre-tx cross-inbound checks race // concurrent writers on other inbounds — re-run them in here (#6225). if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG { @@ -651,7 +639,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } // Confirm absence in the writer so an earlier committed re-add survives. - compacted, next, err := compactAddOrphans(tx, oldClients, lock.orphanOffset) + compacted, next, err := compactAddOrphans(tx, oldClients, mutation.lock.orphanOffset) if err != nil { return err } @@ -679,14 +667,11 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, addedClients, nil); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr } - lock.orphanOffset = nextOrphanOffset + mutation.lock.orphanOffset = nextOrphanOffset // Apply to the running runtime after commit — outside the serialized writer // so a slow node call can't stall traffic accounting. @@ -721,34 +706,25 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } } - } else { - // Large batches would be M sequential per-client RPCs; the inbound's saved - // settings already hold the final set, so mark dirty and let one reconcile - // push converge the node instead. - if push && len(clients) > nodeBulkPushThreshold { - push = false - } - for _, client := range clients { - // /clients/add on the node historically coerced enable=true; skip live - // push for disabled clients and leave dirty so reconcile converges. - if !client.Enable { - push = false - continue - } - if push { - ctx, cancel := nodePushContext() + } else if push && len(clients) <= nodeBulkPushThreshold { + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for _, client := range clients { + // Older nodes coerce enable=true. Reconcile the rest of this batch. + if !client.Enable { + return false + } err1 := rt.AddClient(ctx, oldInbound, client) - cancel() if err1 != nil { logger.Warning("Error in adding client on", rt.Name(), ":", err1) - push = false + return false } } - } - // AddClient only pushed the new clients. Reconcile any orphan removals. - if push && !prunedOrphans { - advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + // AddClient only pushed the new clients. Reconcile any orphan removals. + if !prunedOrphans { + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + } + return !prunedOrphans + }) } return needRestart, nil @@ -756,7 +732,8 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) { defer InvalidateSubData() - defer lockInbound(data.Id).Unlock() + mutation := beginInboundClientMutation(data.Id) + defer mutation.close() clients, err := inboundSvc.GetClients(data) if err != nil { @@ -1058,7 +1035,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo // Persist client stats + inbound atomically, serialized against the traffic // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { // Same re-check-inside-the-writer rule as AddInboundClient (#6225): // the pre-tx pass can race a concurrent writer on another inbound. if oldInbound.Protocol == model.WireGuard { @@ -1164,9 +1141,6 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, changedClients, detachEmails); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr @@ -1216,14 +1190,14 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo } } } else if push { - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - } else { + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + if err := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]); err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) } } else { logger.Debug("Client old email not found") @@ -1235,7 +1209,8 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) { defer InvalidateSubData() - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1270,7 +1245,7 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo } } - if !found { + if !found && (!fullDelete || oldInbound.NodeID == nil) { return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email) } db := database.GetDB() @@ -1320,7 +1295,12 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // Persist the deletion atomically, serialized against the traffic poll to // avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + var pending []model.NodePendingClientDelete + work := nodeClientDelta + if fullDelete { + work = nodeFullClientDelete + } + if txErr := mutation.commit(oldInbound, work, func(tx *gorm.DB) error { if !emailShared && !keepTraffic { if e := inboundSvc.DelClientIPs(tx, email); e != nil { logger.Error("Error in delete client IPs") @@ -1339,8 +1319,9 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo if err := s.ApplyInboundClientDelta(tx, inboundId, nil, []string{email}); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) + if fullDelete { + pending, err = queueNodeClientDeletes(tx, oldInbound.NodeID, []string{email}) + return err } return nil }); txErr != nil { @@ -1386,19 +1367,24 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // must remove the node's client record too, not just detach it from // this inbound (#5797). if push { - ctx, cancel := nodePushContext() - var err1 error - if fullDelete { - err1 = rt.DeleteClient(ctx, email) - } else { - err1 = rt.DeleteUser(ctx, oldInbound, email) - } - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err1) - } else { - advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + var err error + if fullDelete { + for _, row := range pending { + err = applyNodeClientDelete(ctx, rt, row) + } + } else { + err = rt.DeleteUser(ctx, oldInbound, email) + } + if err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } + if !fullDelete { + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + } + return true + }) } } } diff --git a/internal/web/service/client_link.go b/internal/web/service/client_link.go index e457d830f..1eda01a15 100644 --- a/internal/web/service/client_link.go +++ b/internal/web/service/client_link.go @@ -303,7 +303,7 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ wantedIds = append(wantedIds, id) } - relinked, err := s.reconcileInboundLinks(tx, inboundId, wantedFlow, wantedIds, detachEmails, prune) + relinked, err := s.reconcileInboundLinks(tx, inboundId, inbound.NodeID, wantedFlow, wantedIds, detachEmails, prune) if err != nil { return err } @@ -359,7 +359,7 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ // reconcileInboundLinks writes only the client_inbounds rows that differ and returns // their clients. prune also removes links absent from wantedFlow, as only a full sync may. -func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) { +func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID *int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) { var current []model.ClientInbound if prune { if err := tx.Where("inbound_id = ?", inboundId).Find(¤t).Error; err != nil { @@ -447,6 +447,19 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted }).CreateInBatches(toInsert, 200).Error; err != nil { return nil, err } + if nodeID != nil { + reattached := make([]int, 0, len(toInsert)) + for _, link := range toInsert { + reattached = append(reattached, link.ClientId) + } + for _, batch := range chunkInts(reattached, sqlInChunk) { + emails := tx.Model(&model.ClientRecord{}).Select("email").Where("id IN ?", batch) + if err := tx.Where("node_id = ? AND email IN (?)", *nodeID, emails). + Delete(&model.NodePendingClientDelete{}).Error; err != nil { + return nil, err + } + } + } } relinked := append([]int(nil), toDelete...) diff --git a/internal/web/service/client_node_dispatch.go b/internal/web/service/client_node_dispatch.go new file mode 100644 index 000000000..b00a47ec2 --- /dev/null +++ b/internal/web/service/client_node_dispatch.go @@ -0,0 +1,194 @@ +package service + +import ( + "container/list" + "context" + "sync" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +var ( + nodeConfigDispatchMu sync.Mutex + nodeConfigDispatch = map[int]*nodeConfigQueue{} +) + +type nodeConfigQueue struct { + groups list.List + reconciles int +} + +// Inbounds in the same group can push concurrently. A node-wide operation +// waits for the preceding group to drain before the next group can run. +type nodeConfigGroup struct { + position *list.Element + exclusive bool + inbounds map[int]*list.List +} + +type nodeConfigTurn struct { + nodeID int + inboundID int + queue *nodeConfigQueue + group *nodeConfigGroup + position *list.Element + ready chan struct{} + work nodeConfigWork +} + +type nodeConfigWork uint8 + +const ( + nodeClientDelta nodeConfigWork = iota + nodeFullClientDelete + nodeFullReconcile +) + +func reserveNodeConfigTurn(nodeID, inboundID int, work nodeConfigWork) *nodeConfigTurn { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + q := nodeConfigDispatch[nodeID] + if q == nil { + q = &nodeConfigQueue{} + nodeConfigDispatch[nodeID] = q + } + // A reconcile can see later commits. It converges overlapping deltas, + // while node-wide deletes still run because they also remove client records. + if q.reconciles > 0 && work == nodeClientDelta { + return nil + } + exclusive := work != nodeClientDelta + if exclusive { + inboundID = 0 + } + var group *nodeConfigGroup + if last := q.groups.Back(); last != nil { + group = last.Value.(*nodeConfigGroup) + } + if group == nil || group.exclusive != exclusive { + group = &nodeConfigGroup{exclusive: exclusive, inbounds: make(map[int]*list.List)} + group.position = q.groups.PushBack(group) + } + lane := group.inbounds[inboundID] + if lane == nil { + lane = &list.List{} + group.inbounds[inboundID] = lane + } + turn := &nodeConfigTurn{ + nodeID: nodeID, inboundID: inboundID, queue: q, group: group, ready: make(chan struct{}), work: work, + } + turn.position = lane.PushBack(turn) + if work == nodeFullReconcile { + q.reconciles++ + } + if q.groups.Front() == group.position && lane.Front() == turn.position { + close(turn.ready) + } + return turn +} + +func (t *nodeConfigTurn) wait(ctx context.Context) bool { + select { + case <-t.ready: + return ctx.Err() == nil + case <-ctx.Done(): + return false + } +} + +func (t *nodeConfigTurn) release() { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if t.position == nil { + return + } + q, group := t.queue, t.group + lane := group.inbounds[t.inboundID] + wasReady := q.groups.Front() == group.position && lane.Front() == t.position + lane.Remove(t.position) + t.position = nil + if t.work == nodeFullReconcile { + q.reconciles-- + } + if front := lane.Front(); front != nil { + if wasReady { + close(front.Value.(*nodeConfigTurn).ready) + } + return + } + delete(group.inbounds, t.inboundID) + if len(group.inbounds) > 0 { + return + } + q.groups.Remove(group.position) + if next := q.groups.Front(); next == nil { + delete(nodeConfigDispatch, t.nodeID) + } else if wasReady { + for _, lane := range next.Value.(*nodeConfigGroup).inbounds { + close(lane.Front().Value.(*nodeConfigTurn).ready) + } + } +} + +type inboundClientMutation struct { + lock *inboundMutationLock + turn *nodeConfigTurn +} + +func beginInboundClientMutation(inboundID int) *inboundClientMutation { + return &inboundClientMutation{lock: lockInbound(inboundID)} +} + +func (m *inboundClientMutation) unlock() { + if m.lock != nil { + m.lock.Unlock() + m.lock = nil + } +} + +func (m *inboundClientMutation) close() { + m.unlock() + if m.turn != nil { + m.turn.release() + } +} + +func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWork, write func(*gorm.DB) error) error { + if inbound.NodeID == nil { + return runSerializedTx(write) + } + nodeID := *inbound.NodeID + return runSerializedTxThen(func(tx *gorm.DB) error { + if err := write(tx); err != nil { + return err + } + return (&NodeService{}).MarkNodeDirtyTx(tx, nodeID) + }, func() { + m.turn = reserveNodeConfigTurn(nodeID, inbound.Id, work) + }) +} + +func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, apply func(context.Context) bool) { + m.unlock() + if m.turn == nil { + return + } + waitCtx, stopWaiting := nodePushContext() + ready := m.turn.wait(waitCtx) + stopWaiting() + if !ready { + return + } + ctx, cancel := nodePushContext() + defer cancel() + complete := false + defer func() { + if remote, ok := rt.(*runtime.Remote); ok && !complete && m.turn.work != nodeFullClientDelete { + remote.ForgetPushedInbound(inbound.Tag) + } + }() + complete = apply(ctx) +} diff --git a/internal/web/service/client_node_order_test.go b/internal/web/service/client_node_order_test.go new file mode 100644 index 000000000..f3f1d1a5b --- /dev/null +++ b/internal/web/service/client_node_order_test.go @@ -0,0 +1,734 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type blockedClientPushRuntime struct { + fakeNodeRuntime + calls chan string + release <-chan struct{} + blockedEmail string + waitForTimeout bool + expired atomic.Bool +} + +func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbound, client model.Client) error { + r.calls <- "add " + client.Email + if client.Email != r.blockedEmail { + return nil + } + if r.waitForTimeout { + if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > nodeClientPushTimeout { + return errors.New("push timeout was not enforced") + } + // Give the node a shorter deadline so this case exercises RPC ordering + // and the queue-expiry regression can test the separate wait budget. + call, cancel := context.WithTimeout(ctx, nodeClientPushTimeout/2) + defer cancel() + <-call.Done() + r.expired.Store(errors.Is(call.Err(), context.DeadlineExceeded)) + return call.Err() + } + select { + case <-r.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) error { + r.calls <- "update " + email + " " + client.Comment + return nil +} + +func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) error { + r.calls <- "detach " + email + return nil +} + +func (r *blockedClientPushRuntime) UpdateInbound(_ context.Context, _ *model.Inbound, inbound *model.Inbound) error { + r.calls <- "lifecycle " + inbound.Tag + return nil +} + +func setupClientNodeOrderDB(t *testing.T) { + t.Helper() + cleanup, err := testpg.IsolatePackage("client_node_order") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + setupBulkDB(t) + startSerializedWriter(t) +} + +func TestNodeClientMutationsCommitWhileAnEarlierPushIsBlocked(t *testing.T) { + for _, tc := range []struct { + name string + timeout bool + }{ + {name: "successful push"}, + {name: "ambiguous timeout", timeout: true}, + } { + t.Run(tc.name, func(t *testing.T) { + setupClientNodeOrderDB(t) + nodeID, _ := setupNodeRuntime(t) + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + const email = "ordered@example.test" + blocked := &blockedClientPushRuntime{ + calls: make(chan string, 8), release: release, blockedEmail: email, waitForTimeout: tc.timeout, + } + mgr := runtime.GetManager() + mgr.SetRuntimeOverride(nodeID, blocked) + ib := nodeInbound(t, nodeID, 46001, nil) + siblingInbound := nodeInbound(t, nodeID, 46003, nil) + controlNode := model.Node{Name: "control", Address: "127.0.0.1", Port: 2097, ApiToken: "token", Enable: true, Status: "online"} + if err := database.GetDB().Create(&controlNode).Error; err != nil { + t.Fatal(err) + } + control := &fakeNodeRuntime{} + mgr.SetRuntimeOverride(controlNode.Id, control) + other := nodeInbound(t, controlNode.Id, 46002, nil) + clientSvc, inboundSvc := &ClientService{}, &InboundService{} + client := model.Client{Email: email, ID: uuid.NewString(), Enable: true} + changed := client + changed.Comment = "committed update" + sibling := model.Client{Email: "control@example.test", ID: uuid.NewString(), Enable: true} + sameNode := model.Client{Email: "same-node@example.test", ID: uuid.NewString(), Enable: true} + data := func(inbound *model.Inbound, client model.Client) *model.Inbound { + return &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client})} + } + addData, updateData, controlData := data(ib, client), data(ib, changed), data(other, sibling) + siblingData := data(siblingInbound, sameNode) + + var wg sync.WaitGroup + t.Cleanup(func() { + unblock() + wg.Wait() + }) + async := func(operation func() (bool, error)) <-chan error { + done := make(chan error, 1) + wg.Go(func() { + restart, err := operation() + if restart { + err = errors.Join(err, errors.New("requested a local restart for a remote mutation")) + } + done <- err + }) + return done + } + expectCall := func(want string) { + t.Helper() + select { + case got := <-blocked.calls: + if got != want { + t.Fatalf("node operation = %q, want %q", got, want) + } + case <-time.After(nodeClientPushTimeout + time.Second): + t.Fatalf("node never received %q", want) + } + } + waitSettings := func(id int, contains string, present bool) { + t.Helper() + start := time.Now() + for { + current, err := inboundSvc.GetInbound(id) + if err == nil && strings.Contains(current.Settings, contains) == present { + t.Logf("local commit observed after %s while first RPC was blocked", time.Since(start)) + return + } + if time.Since(start) >= time.Second { + t.Fatalf("local settings did not reach %q present=%t while first RPC was blocked (last read err=%v)", contains, present, err) + } + time.Sleep(5 * time.Millisecond) + } + } + + add := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, addData) }) + expectCall("add " + client.Email) + start := time.Now() + locked := make(chan time.Duration, 1) + wg.Go(func() { + start := time.Now() + lockInbound(ib.Id).Unlock() + locked <- time.Since(start) + }) + select { + case took := <-locked: + t.Logf("inbound mutation lock acquired in %s while first RPC was blocked", took) + case <-time.After(time.Second): + t.Fatal("first RPC still holds the inbound mutation lock") + } + writerStart := time.Now() + if err := runSerializedTx(func(*gorm.DB) error { return nil }); err != nil { + t.Fatal(err) + } + t.Logf("independent writer turn took %s while first RPC was blocked", time.Since(writerStart)) + update := async(func() (bool, error) { return clientSvc.UpdateInboundClient(inboundSvc, updateData, client.Email) }) + waitSettings(ib.Id, changed.Comment, true) + detach := async(func() (bool, error) { + return clientSvc.DelInboundClientByEmail(inboundSvc, ib.Id, client.Email, true, false) + }) + waitSettings(ib.Id, client.Email, false) + sameNodeDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, siblingData) }) + waitSettings(siblingInbound.Id, sameNode.Email, true) + expectCall("add " + sameNode.Email) + if err := waitTrafficWriterErr(t, sameNodeDone); err != nil { + t.Fatal(err) + } + controlDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, controlData) }) + select { + case err := <-controlDone: + if err != nil || control.addClient.Load() != 1 { + t.Fatalf("control inbound did not complete independently: %v (pushes=%d)", err, control.addClient.Load()) + } + case <-time.After(time.Second): + t.Fatal("control inbound waited for unrelated node") + } + select { + case got := <-blocked.calls: + t.Fatalf("%q overtook the first RPC", got) + default: + } + unblock() + expectCall("update " + client.Email + " " + changed.Comment) + t.Logf("first RPC held its dispatch turn for %s", time.Since(start)) + if tc.timeout && !blocked.expired.Load() { + t.Fatal("the first push did not finish through its deadline") + } + expectCall("detach " + client.Email) + for i, done := range []<-chan error{add, update, detach} { + select { + case err := <-done: + if err != nil { + t.Fatal(fmt.Errorf("operation %d reported %w after commit", i, err)) + } + case <-time.After(time.Second): + t.Fatalf("operation %d did not complete", i) + } + } + if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty { + t.Fatalf("node dirty=%t error=%v after committed client batch", dirty, err) + } + }) + } +} + +func TestNodeClientQueueTimeoutDefersCommittedDelta(t *testing.T) { + setupClientNodeOrderDB(t) + nodeID, fake := setupNodeRuntime(t) + inbound := nodeInbound(t, nodeID, 46004, nil) + first := reserveNodeConfigTurn(nodeID, inbound.Id, nodeClientDelta) + t.Cleanup(first.release) + + email := "wait-deadline@example.test" + data := &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{{ + Email: email, ID: uuid.NewString(), Enable: true, + }})} + inboundSvc, clientSvc := &InboundService{}, &ClientService{} + done := make(chan error, 1) + completed := make(chan struct{}) + t.Cleanup(func() { + first.release() + <-completed + }) + go func() { + defer close(completed) + _, err := clientSvc.AddInboundClient(inboundSvc, data) + done <- err + }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(nodeClientPushTimeout + 2*time.Second): + t.Fatal("client request waited for a dispatch turn past its deadline") + } + if fake.addClient.Load() != 0 { + t.Fatal("expired client push overtook the in-flight operation") + } + current, err := inboundSvc.GetInbound(inbound.Id) + if err != nil || !strings.Contains(current.Settings, email) { + t.Fatalf("expired queue wait lost the committed client: %v", err) + } + if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty { + t.Fatalf("expired queue wait did not leave the node dirty: dirty=%v err=%v", dirty, err) + } + first.release() + next := reserveNodeConfigTurn(nodeID, inbound.Id, nodeClientDelta) + defer next.release() + select { + case <-next.ready: + default: + t.Fatal("expired dispatch turn blocked the next mutation") + } +} + +func TestTrafficDepletionWaitsForEarlierNodeClientPush(t *testing.T) { + setupClientNodeOrderDB(t) + nodeID, _ := setupNodeRuntime(t) + mgr := runtime.GetManager() + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + const email = "depleted-while-pushing@example.test" + blocked := &blockedClientPushRuntime{calls: make(chan string, 4), release: release, blockedEmail: email} + mgr.SetRuntimeOverride(nodeID, blocked) + ib := nodeInbound(t, nodeID, 46012, nil) + inboundSvc := &InboundService{} + client := model.Client{Email: email, ID: uuid.NewString(), Enable: true, TotalGB: 5} + add := &model.Inbound{Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client})} + var wg sync.WaitGroup + t.Cleanup(func() { + unblock() + wg.Wait() + }) + addDone := make(chan error, 1) + wg.Go(func() { + _, err := (&ClientService{}).AddInboundClient(inboundSvc, add) + addDone <- err + }) + select { + case got := <-blocked.calls: + if got != "add "+client.Email { + t.Fatalf("first node operation = %q", got) + } + case <-time.After(3 * time.Second): + t.Fatal("node did not receive the add") + } + depletionDone := make(chan error, 1) + wg.Go(func() { + _, disabled, err := inboundSvc.AddTraffic(nil, []*xray.ClientTraffic{{Email: client.Email, Up: 10}}) + if !disabled { + err = errors.Join(err, errors.New("traffic did not disable the depleted client")) + } + depletionDone <- err + }) + deadline := time.Now().Add(time.Second) + for readTraffic(t, database.GetDB(), client.Email).Enable { + if time.Now().After(deadline) { + t.Fatal("depletion did not commit while the add was blocked") + } + time.Sleep(5 * time.Millisecond) + } + select { + case got := <-blocked.calls: + t.Fatalf("node operation %q overtook the pending add", got) + case <-time.After(100 * time.Millisecond): + } + unblock() + select { + case got := <-blocked.calls: + if got != "lifecycle "+ib.Tag { + t.Fatalf("second node operation = %q, want the depletion update", got) + } + case <-time.After(time.Second): + t.Fatal("node did not receive the depletion update") + } + for _, done := range []<-chan error{addDone, depletionDone} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } +} + +func TestReconcileDoesNotOvertakeCommittedClientState(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const tag = "in-46011" + listStarted := make(chan struct{}) + releaseList := make(chan struct{}) + release := sync.OnceFunc(func() { close(releaseList) }) + var lists atomic.Int32 + pushedSettings := make(chan string, 4) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any + switch r.URL.Path { + case "/panel/api/inbounds/list": + if lists.Add(1) == 1 { + close(listStarted) + select { + case <-r.Context().Done(): + return + case <-releaseList: + } + } + obj = []map[string]any{{"id": 1, "tag": tag}} + case "/panel/api/inbounds/update/1": + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + pushedSettings <- r.Form.Get("settings") + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + t.Cleanup(release) + + node := reconcileTestNode(t, server, "reconcile-overlap", "all", nil) + remote := runtime.NewRemote(node, nil) + fast := &fakeNodeRuntime{} + mgr.SetRuntimeOverride(node.Id, fast) + ib := nodeInbound(t, node.Id, 46011, nil) + clientSvc, inboundSvc, nodeSvc := &ClientService{}, &InboundService{}, &NodeService{} + // Exercise generation ordering even when the previous timestamp is ahead of the clock. + oldGeneration := time.Now().Add(time.Minute).UnixMilli() + if err := database.GetDB().Model(node).Updates(map[string]any{ + "config_dirty": true, "config_dirty_at": oldGeneration, + }).Error; err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + reconciled := make(chan error, 1) + go func() { reconciled <- inboundSvc.ReconcileNode(ctx, remote, node) }() + waitTrafficWriterSignal(t, listStarted, "reconcile never reached the remote list") + + client := model.Client{Email: "during-reconcile@example.test", ID: uuid.NewString(), Enable: true} + if needRestart, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); needRestart || err != nil { + t.Fatalf("add during reconcile: restart=%t err=%v", needRestart, err) + } + if got := fast.addClient.Load(); got != 0 { + t.Fatalf("%d incremental pushes overlapped a reconcile of older settings", got) + } + release() + if err := waitTrafficWriterErr(t, reconciled); err != nil { + t.Fatal(err) + } + select { + case pushed := <-pushedSettings: + if strings.Contains(pushed, client.Email) { + t.Fatalf("first reconcile should still carry the pre-add settings, got %s", pushed) + } + default: + t.Fatal("first reconcile did not push the captured configuration") + } + + if err := nodeSvc.ClearNodeDirty(node.Id, oldGeneration); err != nil { + t.Fatal(err) + } + _, _, dirty, generation, err := nodeSvc.NodeSyncState(node.Id) + if err != nil || !dirty || generation <= oldGeneration { + t.Fatalf("new generation lost after stale reconcile: dirty=%t generation=%d previous=%d err=%v", dirty, generation, oldGeneration, err) + } + if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + select { + case pushed := <-pushedSettings: + if !strings.Contains(pushed, client.Email) { + t.Fatalf("next reconcile did not deliver the committed client: %s", pushed) + } + default: + t.Fatal("next reconcile did not push the new configuration") + } +} + +func TestNodeWideDeleteSkipsReattachmentSentByQueuedReconcile(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const primaryTag, blockerTag, recreatedTag = "in-46013", "in-46014", "in-46015" + const email = "recreated@example.test" + firstPush := make(chan struct{}) + releaseFirstPush := make(chan struct{}) + release := sync.OnceFunc(func() { close(releaseFirstPush) }) + var hasClient atomic.Bool + hasClient.Store(true) + var adds, deletes, blockerUpdates, recreatedUpdates atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any + switch r.URL.Path { + case "/panel/api/inbounds/list": + obj = []map[string]any{{"id": 1, "tag": primaryTag}, {"id": 2, "tag": blockerTag}, {"id": 3, "tag": recreatedTag}} + case "/panel/api/clients/add": + if adds.Add(1) == 1 { + close(firstPush) + select { + case <-r.Context().Done(): + return + case <-releaseFirstPush: + } + } + case "/panel/api/inbounds/update/1": + case "/panel/api/inbounds/update/3": + recreatedUpdates.Add(1) + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + hasClient.Store(strings.Contains(r.Form.Get("settings"), "recreated configuration")) + case "/panel/api/inbounds/update/2": + blockerUpdates.Add(1) + case "/panel/api/clients/del/" + email: + deletes.Add(1) + hasClient.Store(false) + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + var wg sync.WaitGroup + t.Cleanup(func() { + release() + wg.Wait() + }) + + node := reconcileTestNode(t, server, "reconcile-full-delete", "all", nil) + remote := runtime.NewRemote(node, nil) + mgr.SetRuntimeOverride(node.Id, remote) + client := model.Client{Email: email, ID: uuid.NewString(), SubID: "reconcile-recreated", Enable: true} + inbound := nodeInbound(t, node.Id, 46013, []model.Client{client}) + blocker := nodeInbound(t, node.Id, 46014, nil) + recreated := nodeInbound(t, node.Id, 46015, nil) + inboundSvc, clientSvc := &InboundService{}, &ClientService{} + addPayload := &model.Inbound{Id: blocker.Id, Protocol: model.VLESS, Settings: clientsSettings(t, []model.Client{{ + Email: "first-push@example.test", ID: uuid.NewString(), Enable: true, + }})} + async := func(run func() error) <-chan error { + done := make(chan error, 1) + wg.Go(func() { done <- run() }) + return done + } + waitUntil := func(message string, ready func() bool) { + t.Helper() + deadline := time.Now().Add(time.Second) + for !ready() { + if time.Now().After(deadline) { + t.Fatal(message) + } + time.Sleep(5 * time.Millisecond) + } + } + + added := async(func() error { + _, err := clientSvc.AddInboundClient(inboundSvc, addPayload) + return err + }) + waitTrafficWriterSignal(t, firstPush, "first AddClient never reached the node") + ctx, cancel := context.WithTimeout(t.Context(), 6*time.Second) + defer cancel() + reconciled := async(func() error { return inboundSvc.ReconcileNode(ctx, remote, node) }) + waitUntil("reconcile did not queue behind the first add", func() bool { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + queue := nodeConfigDispatch[node.Id] + return queue != nil && queue.reconciles > 0 + }) + deleted := async(func() error { + _, err := clientSvc.DelInboundClientByEmail(inboundSvc, inbound.Id, email, true, true) + return err + }) + waitUntil("full delete did not commit behind the reconcile", func() bool { + current, err := inboundSvc.GetInbound(inbound.Id) + return err == nil && !strings.Contains(current.Settings, email) + }) + client.Comment = "recreated configuration" + if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: recreated.Id, Protocol: recreated.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + release() + for _, done := range []<-chan error{added, reconciled, deleted} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } + if adds.Load() != 1 || deletes.Load() != 0 || !hasClient.Load() { + t.Fatalf("queued delete touched the reattachment: adds=%d deletes=%d client=%t", adds.Load(), deletes.Load(), hasClient.Load()) + } + if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + if !hasClient.Load() || recreatedUpdates.Load() != 1 { + t.Fatalf("reconcile unnecessarily re-sent the reattachment (pushes=%d)", recreatedUpdates.Load()) + } + if blockerUpdates.Load() != 1 { + t.Fatalf("reconcile re-sent unrelated inbound (pushes=%d)", blockerUpdates.Load()) + } +} + +func TestNodeWideDeleteRetriesAfterQueueExpiry(t *testing.T) { + for _, mode := range []string{"expired queue", "lost acknowledgment", "recreated client", "recreated on another node"} { + t.Run(mode, func(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const email = "durable-delete@example.test" + const tag = "in-46019" + var remoteRecord, remoteLink, dropAck atomic.Bool + var deletes atomic.Int32 + remoteRecord.Store(true) + remoteLink.Store(true) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + response := map[string]any{"success": true} + switch r.URL.Path { + case "/panel/api/inbounds/list": + response["obj"] = []map[string]any{{"id": 1, "tag": tag}} + case "/panel/api/inbounds/update/1": + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + remoteLink.Store(strings.Contains(r.Form.Get("settings"), email)) + case "/panel/api/clients/add": + remoteLink.Store(true) + remoteRecord.Store(true) + case "/panel/api/clients/del/" + email: + deletes.Add(1) + remoteLink.Store(false) + if !remoteRecord.Swap(false) { + response["success"] = false + response["msg"] = fmt.Sprintf("Error (client %q not found in any inbound or client record)", email) + } + if dropAck.CompareAndSwap(true, false) { + <-r.Context().Done() + return + } + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(response) + })) + t.Cleanup(server.Close) + node := reconcileTestNode(t, server, "durable-client-delete", "all", nil) + remote := runtime.NewRemote(node, nil) + mgr.SetRuntimeOverride(node.Id, remote) + client := model.Client{Email: email, ID: uuid.NewString(), SubID: "durable-delete", Enable: true} + inbound := nodeInbound(t, node.Id, 46019, []model.Client{client}) + inboundSvc, clientSvc := &InboundService{}, &ClientService{} + record := lookupClientRecord(t, email) + + if mode == "expired queue" { + earlier := reserveNodeConfigTurn(node.Id, inbound.Id, nodeClientDelta) + defer earlier.release() + start := time.Now() + if _, err := clientSvc.Delete(inboundSvc, record.Id, false); err != nil { + t.Fatal(err) + } + if elapsed := time.Since(start); elapsed >= 2*nodeClientPushTimeout || deletes.Load() != 0 { + t.Fatalf("delete ignored its queue budget: elapsed=%v RPCs=%d", elapsed, deletes.Load()) + } + earlier.release() + } else { + if err := database.GetDB().Model(node).Update("status", "offline").Error; err != nil { + t.Fatal(err) + } + if _, err := clientSvc.Delete(inboundSvc, record.Id, false); err != nil { + t.Fatal(err) + } + if err := database.GetDB().Model(node).Update("status", "online").Error; err != nil { + t.Fatal(err) + } + } + + if _, err := clientSvc.GetRecordByEmail(nil, email); !errors.Is(err, gorm.ErrRecordNotFound) { + t.Fatalf("master still has the deleted record: %v", err) + } + if !remoteRecord.Load() || !remoteLink.Load() { + t.Fatal("fixture deleted the node client before delivery") + } + wantCalls := int32(1) + var otherNode *model.Node + var otherInbound *model.Inbound + var otherRuntime *fakeNodeRuntime + if mode == "recreated on another node" { + otherNode = &model.Node{Name: "other-delete-node", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true, Status: "online"} + if err := database.GetDB().Create(otherNode).Error; err != nil { + t.Fatal(err) + } + otherRuntime = &fakeNodeRuntime{} + mgr.SetRuntimeOverride(otherNode.Id, otherRuntime) + otherInbound = nodeInbound(t, otherNode.Id, 46020, nil) + client.ID = uuid.NewString() + if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: otherInbound.Id, Protocol: otherInbound.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + if got := lookupClientRecord(t, email); got.Id == record.Id { + t.Fatal("test did not create a new client incarnation on the other node") + } + var pending int64 + if err := database.GetDB().Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email = ?", node.Id, email).Count(&pending).Error; err != nil || pending != 1 { + t.Fatalf("recreation on another node must keep the original pending delete: %d (%v)", pending, err) + } + } + if mode == "recreated client" { + client.ID = uuid.NewString() + if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + if got := lookupClientRecord(t, email); got.Id == record.Id { + t.Fatal("test did not create a new client incarnation") + } + wantCalls = 0 + } + if mode == "lost acknowledgment" { + dropAck.Store(true) + ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond) + err := inboundSvc.ReconcileNode(ctx, remote, node) + cancel() + if !errors.Is(err, context.DeadlineExceeded) || remoteRecord.Load() || remoteLink.Load() { + t.Fatalf("expected remote commit with an uncertain reply: %v", err) + } + wantCalls = 2 + } + if err := inboundSvc.ReconcileNode(t.Context(), remote, node); err != nil { + t.Fatal(err) + } + wantPresent := mode == "recreated client" + if deletes.Load() != wantCalls || remoteRecord.Load() != wantPresent || remoteLink.Load() != wantPresent { + t.Fatalf("node after replay: RPCs=%d record=%v membership=%v", deletes.Load(), remoteRecord.Load(), remoteLink.Load()) + } + if otherNode != nil { + current, err := inboundSvc.GetInbound(otherInbound.Id) + if err != nil || !strings.Contains(current.Settings, email) { + t.Fatalf("reconcile changed the other node's desired client: %v", err) + } + if otherRuntime.addClient.Load() != 1 || otherRuntime.deleteClient.Load() != 0 { + t.Fatalf("other node RPCs: adds=%d deletes=%d", otherRuntime.addClient.Load(), otherRuntime.deleteClient.Load()) + } + if got := lookupClientRecord(t, email); got.Id == record.Id { + t.Fatal("reconcile did not preserve the new client record") + } + } + var pending int64 + if err := database.GetDB().Model(&model.NodePendingClientDelete{}).Where("node_id = ?", node.Id).Count(&pending).Error; err != nil || pending != 0 { + t.Fatalf("pending deletes after reconciliation: %d (%v)", pending, err) + } + }) + } +} diff --git a/internal/web/service/client_node_push_test.go b/internal/web/service/client_node_push_test.go index 11119848f..9d6b135cd 100644 --- a/internal/web/service/client_node_push_test.go +++ b/internal/web/service/client_node_push_test.go @@ -1,11 +1,14 @@ package service import ( + "os" + "path/filepath" "testing" "time" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) // TestResetTrafficAcrossNodesPushesConcurrently covers the panel's per-client @@ -73,12 +76,11 @@ func TestNodePushGivesUpBeforeTheRemoteTimeout(t *testing.T) { // TestBulkDeleteStopsPushingToAHungNode pins the batch circuit-break: once one // push times out, the rest of the batch defers to the reconcile as well. func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) { - setupBulkDB(t) - startSerializedWriter(t) + setupClientNodeOrderDB(t) useTestRuntimeManager(t) f := newFakeNodeHTTP(t) - realNodeInbound(t, f, 53200, []model.Client{ + ib := realNodeInbound(t, f, 53200, []model.Client{ {Email: "b1@x", ID: "66666666-1111-2222-3333-444444444441", SubID: "sub-b1", Enable: true}, {Email: "b2@x", ID: "66666666-1111-2222-3333-444444444442", SubID: "sub-b2", Enable: true}, {Email: "b3@x", ID: "66666666-1111-2222-3333-444444444443", SubID: "sub-b3", Enable: true}, @@ -96,4 +98,21 @@ func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) { if elapsed >= 2*nodeClientPushTimeout { t.Fatalf("deleting 3 clients took %v against a hung node, want a single %v deadline, not one per client", elapsed, nodeClientPushTimeout) } + if err := database.CloseDB(); err != nil { + t.Fatal(err) + } + if err := database.InitDB(filepath.Join(os.Getenv("XUI_DB_FOLDER"), "x-ui.db")); err != nil { + t.Fatal(err) + } + f.setHold(false) + var node model.Node + if err := database.GetDB().First(&node, *ib.NodeID).Error; err != nil { + t.Fatal(err) + } + if err := (&InboundService{}).ReconcileNode(t.Context(), runtime.NewRemote(&node, nil), &node); err != nil { + t.Fatal(err) + } + if got := f.hitCount("/clients/del/"); got != 4 { + t.Fatalf("delete requests including replay after reopening = %d, want 4 (one timed out, then all three retried)", got) + } } diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 5ca1f4bc8..2b4887144 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -137,14 +137,23 @@ func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, return nil } nodeID := n.Id + turn := reserveNodeConfigTurn(nodeID, 0, nodeFullReconcile) + defer turn.release() + if !turn.wait(ctx) { + return ctx.Err() + } + var errs []error + if err := deliverNodeClientDeletes(ctx, nodeID, rt); err != nil { + errs = append(errs, err) + } db := database.GetDB() var inbounds []*model.Inbound if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil { - return err + return errors.Join(append(errs, err)...) } remoteInbounds, err := rt.ListInboundOptions(ctx) if err != nil { - return err + return errors.Join(append(errs, err)...) } remoteTags := make([]string, 0, len(remoteInbounds)) remoteTagSet := make(map[string]struct{}, len(remoteTags)) @@ -154,7 +163,6 @@ func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, } prefix := nodeTagPrefix(&nodeID) desiredTags := make(map[string]struct{}, len(inbounds)*2) - var errs []error for _, ib := range inbounds { desiredTags[ib.Tag] = struct{}{} // existsOnNode: does the node already report this inbound under any of the diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index ce6f56f45..bc57a7114 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -34,6 +34,7 @@ func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraff func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart bool, clientsDisabled bool, err error) { var disabledNodeIDs []int var remotePlans []trafficInboundUpdatePlan + var remoteTurns []*nodeConfigTurn var renewed []string committed := false // The periodic poll takes the background lane: an operator's save or reset @@ -46,6 +47,9 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b committed = true var inner error needRestart, clientsDisabled, disabledNodeIDs, remotePlans, renewed, inner = s.maintainTrafficLocked() + if inner == nil { + remoteTurns = reserveTrafficRemoteTurns(remotePlans) + } return inner }) if err != nil { @@ -55,9 +59,16 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b } return } + defer func() { + for _, turn := range remoteTurns { + if turn != nil { + turn.release() + } + } + }() s.resetMtprotoClientQuotas(renewed) // Off the serial writer: a hanging node must not stall traffic accounting. - needRestart = s.applyTrafficRemotePlans(remotePlans) || needRestart + needRestart = s.applyTrafficRemotePlans(remotePlans, remoteTurns) || needRestart if len(disabledNodeIDs) > 0 { s.restartRemoteNodesOnDepletion(disabledNodeIDs) } diff --git a/internal/web/service/inbound_traffic_apply.go b/internal/web/service/inbound_traffic_apply.go index d2d65afd5..f0553c679 100644 --- a/internal/web/service/inbound_traffic_apply.go +++ b/internal/web/service/inbound_traffic_apply.go @@ -7,6 +7,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/logger" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" "github.com/mhsanaei/3x-ui/v3/internal/xray" "gorm.io/gorm" @@ -60,32 +61,54 @@ func (b *trafficMutationBatch) markNodesTx(tx *gorm.DB) error { return nil } -// applyTrafficRemotePlans is bounded like every per-client node push: the nodes are -// already dirty, so an offline or slow one defers to the reconcile. -func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePlan) bool { +// Reserve on the writer after maintenance commits so a newer client edit cannot pass it. +func reserveTrafficRemoteTurns(plans []trafficInboundUpdatePlan) []*nodeConfigTurn { + if len(plans) == 0 { + return nil + } + turns := make([]*nodeConfigTurn, len(plans)) + for i := range plans { + ib := &plans[i].newInbound + if ib.NodeID != nil { + turns[i] = reserveNodeConfigTurn(*ib.NodeID, ib.Id, nodeClientDelta) + } + } + return turns +} + +// The wait and pushes share one budget per node. Dirty state covers a skipped push. +func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePlan, turns []*nodeConfigTurn) bool { byNode := make(map[int][]int) var nodeIDs []int for i := range plans { - nodeID := 0 - if plans[i].newInbound.NodeID != nil { - nodeID = *plans[i].newInbound.NodeID + id := plans[i].newInbound.NodeID + if id == nil || turns[i] == nil { + continue } + nodeID := *id if _, seen := byNode[nodeID]; !seen { nodeIDs = append(nodeIDs, nodeID) } byNode[nodeID] = append(byNode[nodeID], i) } failed, panics := fanoutInboundResults(nodeIDs, nodeFanoutConcurrency, func(n int) bool { - // One budget per node, not per inbound: a node choosing how many inbounds it reports - // must not choose how long the sync job waits on it before serving other nodes. ctx, cancel := nodePushContext() defer cancel() indexes := byNode[nodeIDs[n]] nodeFailed, nodePanics := fanoutInboundResults(indexes, inboundFanoutConcurrency, func(k int) bool { - plan := &plans[indexes[k]] + index := indexes[k] + turn := turns[index] + defer turn.release() + if !turn.wait(ctx) { + return false + } + plan := &plans[index] rt, push, _, err := s.nodePushPlan(&plan.newInbound) if err == nil && push { err = rt.UpdateInbound(ctx, &plan.oldInbound, &plan.newInbound) + if remote, ok := rt.(*runtime.Remote); ok && err != nil { + remote.ForgetPushedInbound(plan.newInbound.Tag) + } } if err != nil { logger.Debug("traffic post-commit remote apply failed:", err) diff --git a/internal/web/service/node.go b/internal/web/service/node.go index 25ed1f493..735448b24 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -883,6 +883,9 @@ func (s *NodeService) Delete(id int) error { if err := tx.Where("node_id = ?", id).Delete(&model.NodePendingReset{}).Error; err != nil { return err } + if err := tx.Where("node_id = ?", id).Delete(&model.NodePendingClientDelete{}).Error; err != nil { + return err + } guids := []string{synthNodeGuid(id)} if guid != "" { guids = append(guids, guid) @@ -1076,11 +1079,12 @@ func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error { if tx == nil { return errors.New("nil db transaction") } + now := time.Now().UnixMilli() return tx.Model(model.Node{}). Where("id = ?", id). Updates(map[string]any{ "config_dirty": true, - "config_dirty_at": time.Now().UnixMilli(), + "config_dirty_at": gorm.Expr(database.GreatestExpr("COALESCE(config_dirty_at, 0) + 1", "?"), now), }).Error } diff --git a/internal/web/service/node_bulk_dispatch_test.go b/internal/web/service/node_bulk_dispatch_test.go index 2c572f8d3..6e33f9702 100644 --- a/internal/web/service/node_bulk_dispatch_test.go +++ b/internal/web/service/node_bulk_dispatch_test.go @@ -355,8 +355,8 @@ func TestNodeBulkDeleteCompletesAcrossPresentAndMissingSettings(t *testing.T) { if result.Deleted != 1 || len(result.Skipped) != 0 { t.Fatalf("BulkDelete result = %+v, want one deleted client", result) } - if got := fake.deleteClient.Load(); got != 2 { - t.Fatalf("remote DeleteClient calls = %d, want one per node inbound", got) + if got := fake.deleteClient.Load(); got != 1 { + t.Fatalf("remote DeleteClient calls = %d, want one full delete for the node", got) } } diff --git a/internal/web/service/node_client_delete_queue.go b/internal/web/service/node_client_delete_queue.go new file mode 100644 index 000000000..e494420ed --- /dev/null +++ b/internal/web/service/node_client_delete_queue.go @@ -0,0 +1,123 @@ +package service + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + "gorm.io/gorm/clause" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +func queueNodeClientDeletes(tx *gorm.DB, nodeID *int, emails []string) ([]model.NodePendingClientDelete, error) { + if nodeID == nil || len(emails) == 0 { + return nil, nil + } + ids := make(map[string]int, len(emails)) + for _, batch := range chunkStrings(emails, sqlInChunk) { + var records []model.ClientRecord + if err := tx.Select("id", "email").Where("email IN ?", batch).Find(&records).Error; err != nil { + return nil, err + } + for _, record := range records { + ids[record.Email] = record.Id + } + } + generation := uuid.NewString() + rows := make([]model.NodePendingClientDelete, 0, len(emails)) + for _, email := range emails { + rows = append(rows, model.NodePendingClientDelete{ + NodeId: *nodeID, Email: email, ClientId: ids[email], Generation: generation, + }) + } + err := tx.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}}, + DoUpdates: clause.AssignmentColumns([]string{"client_id", "generation", "last_attempt_at"}), + }).CreateInBatches(rows, 200).Error + return rows, err +} + +func sameNodeClientDelete(db *gorm.DB, row model.NodePendingClientDelete) *gorm.DB { + return db.Model(&model.NodePendingClientDelete{}). + Where("node_pending_client_deletes.node_id = ? AND node_pending_client_deletes.email = ? AND node_pending_client_deletes.generation = ?", + row.NodeId, row.Email, row.Generation) +} + +// applyNodeClientDelete runs under the node-wide turn. Later attached clients +// push after this turn or are restored by the dirty generation on reconcile. +func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.NodePendingClientDelete) error { + db := database.GetDB().WithContext(ctx) + var target struct { + Desired bool + } + result := sameNodeClientDelete(db, row). + Select("EXISTS (" + + "SELECT 1 FROM client_inbounds JOIN inbounds ON inbounds.id = client_inbounds.inbound_id " + + "WHERE client_inbounds.client_id = clients.id AND inbounds.node_id = node_pending_client_deletes.node_id) AS desired"). + Joins("LEFT JOIN clients ON clients.email = node_pending_client_deletes.email"). + Limit(1).Scan(&target) + if result.Error != nil || result.RowsAffected == 0 { + return result.Error + } + // Only a desired attachment on this node supersedes its pending delete. + // Recreating the email elsewhere must not leave the old node record behind. + if !target.Desired { + if err := rt.DeleteClient(ctx, row.Email); err != nil { + return err + } + } + return sameNodeClientDelete(db, row).Delete(&model.NodePendingClientDelete{}).Error +} + +const nodeClientDeletePage = 200 + +// Reconciliation holds the exclusive node turn while delivering one bounded +// page. A failed page keeps the node dirty so snapshots cannot readopt clients. +func deliverNodeClientDeletes(ctx context.Context, nodeID int, rt runtime.Runtime) error { + db := database.GetDB().WithContext(ctx) + var rows []model.NodePendingClientDelete + if err := db.Where("node_id = ?", nodeID).Order("last_attempt_at, email"). + Limit(nodeClientDeletePage).Find(&rows).Error; err != nil { + return err + } + if len(rows) == 0 { + return nil + } + sendCtx, cancel := context.WithTimeout(ctx, nodeClientPushTimeout) + defer cancel() + var firstErr error + for _, row := range rows { + if err := applyNodeClientDelete(sendCtx, rt, row); err != nil { + if firstErr == nil { + firstErr = err + } + // Rotate a failing row behind entries that have not had a turn. + if err := sameNodeClientDelete(db, row).Update("last_attempt_at", time.Now().UnixNano()).Error; err != nil { + return errors.Join(firstErr, err) + } + if sendCtx.Err() != nil { + break + } + } + } + if firstErr != nil { + return fmt.Errorf("deliver node client deletes: %w", firstErr) + } + if len(rows) == nodeClientDeletePage { + var remaining int64 + if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ?", nodeID). + Limit(1).Select("1").Scan(&remaining).Error; err != nil { + return err + } + if remaining != 0 { + return errors.New("more node client deletes awaiting delivery") + } + } + return nil +} diff --git a/internal/web/service/node_reset_undelivered_test.go b/internal/web/service/node_reset_undelivered_test.go index 278d1c2b0..00d300357 100644 --- a/internal/web/service/node_reset_undelivered_test.go +++ b/internal/web/service/node_reset_undelivered_test.go @@ -388,7 +388,7 @@ func TestTrafficRemotePlansWaitOneBudgetPerNode(t *testing.T) { plans[i] = trafficInboundUpdatePlan{oldInbound: ib, newInbound: ib} } start := time.Now() - (&InboundService{}).applyTrafficRemotePlans(plans) + (&InboundService{}).applyTrafficRemotePlans(plans, reserveTrafficRemoteTurns(plans)) if took := time.Since(start); took > nodeClientPushTimeout+2*time.Second { t.Fatalf("pushing %d inbounds to one hanging node took %v", len(plans), took) } diff --git a/internal/web/service/traffic_writer.go b/internal/web/service/traffic_writer.go index a40b17484..017fc8acf 100644 --- a/internal/web/service/traffic_writer.go +++ b/internal/web/service/traffic_writer.go @@ -167,6 +167,11 @@ func drainTrafficWriter(adminQueue, bgQueue chan *trafficWriteRequest) { // remote node call would stall all traffic accounting for up to the remote // timeout. Apply runtime changes after this returns. func runSerializedTx(fn func(tx *gorm.DB) error) error { + return runSerializedTxThen(fn, nil) +} + +// afterCommit runs on the writer in commit order and must not wait or perform I/O. +func runSerializedTxThen(fn func(tx *gorm.DB) error, afterCommit func()) error { return submitTrafficWrite(func() error { state := &serializedTx{} err := database.GetDB().Transaction(func(tx *gorm.DB) error { @@ -176,6 +181,9 @@ func runSerializedTx(fn func(tx *gorm.DB) error) error { if err == nil { // Still on the writer, so no node merge runs between the commit and the lift. withdrawClientTombstones(state.createdClientEmails...) + if afterCommit != nil { + afterCommit() + } } return err }) From 0db9503228d2c074e435b273b053847a91748811 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 16:47:26 +0330 Subject: [PATCH 05/14] 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 d13850474f1c5ed4f8161ce4dd99e6985d175c8f (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 --- .github/workflows/ci.yml | 6 +- docs/architecture.md | 13 + .../content/docs/en/reference/api/clients.mdx | 135 +++- docs/public/openapi.json | 583 ++++++++++++++++-- frontend/public/openapi.json | 583 ++++++++++++++++-- frontend/scripts/build-openapi.mjs | 4 +- frontend/src/generated/examples.ts | 124 ++++ frontend/src/generated/schemas.ts | 252 ++++++++ frontend/src/generated/types.ts | 65 ++ frontend/src/generated/zod.ts | 75 +++ frontend/src/pages/api-docs/endpoints.ts | 72 ++- frontend/src/test/clients-summary.test.tsx | 14 +- frontend/src/utils/index.ts | 2 +- internal/web/controller/client.go | 71 ++- .../web/controller/client_node_apply_test.go | 199 ++++++ internal/web/controller/util.go | 10 - internal/web/job/node_client_speed_test.go | 51 +- internal/web/job/node_reset_replay_test.go | 5 +- .../job/node_sync_operational_query_test.go | 9 +- .../web/job/node_traffic_isolation_test.go | 389 ++++++++++++ .../web/job/node_traffic_sync_ip_push_test.go | 5 +- internal/web/job/node_traffic_sync_job.go | 403 +++++++----- .../node_traffic_sync_online_prune_test.go | 5 +- internal/web/node_contract_test.go | 12 +- internal/web/runtime/local.go | 28 +- .../runtime/local_wireguard_devices_test.go | 2 +- internal/web/runtime/reconcile_skip_test.go | 26 +- internal/web/runtime/remote.go | 57 +- internal/web/runtime/runtime.go | 13 +- internal/web/service/client.go | 4 +- internal/web/service/client_bulk.go | 57 +- .../web/service/client_create_fanout_test.go | 2 +- internal/web/service/client_crud.go | 73 ++- .../service/client_edit_node_dirty_test.go | 3 +- internal/web/service/client_inbound_apply.go | 62 +- internal/web/service/client_lookup.go | 11 - internal/web/service/client_node_apply.go | 106 ++++ .../web/service/client_node_apply_test.go | 86 +++ internal/web/service/client_node_dispatch.go | 56 +- .../web/service/client_node_order_test.go | 20 +- internal/web/service/client_node_push_test.go | 159 +++++ .../web/service/client_update_fanout_test.go | 9 +- internal/web/service/inbound_node.go | 38 +- internal/web/service/node.go | 48 +- .../web/service/node_bulk_dispatch_test.go | 18 +- .../web/service/node_client_delete_queue.go | 15 +- internal/web/service/node_dirty_test.go | 24 + internal/web/service/node_http_fake_test.go | 19 +- internal/web/translation/ar-EG.json | 2 +- internal/web/translation/en-US.json | 2 +- internal/web/translation/es-ES.json | 2 +- internal/web/translation/fa-IR.json | 2 +- internal/web/translation/id-ID.json | 2 +- internal/web/translation/ja-JP.json | 2 +- internal/web/translation/pt-BR.json | 2 +- internal/web/translation/ru-RU.json | 2 +- internal/web/translation/sk-SK.json | 2 +- internal/web/translation/tr-TR.json | 2 +- internal/web/translation/uk-UA.json | 2 +- internal/web/translation/vi-VN.json | 2 +- internal/web/translation/zh-CN.json | 2 +- internal/web/translation/zh-TW.json | 2 +- internal/web/web.go | 10 +- tools/openapigen/main.go | 10 + 64 files changed, 3511 insertions(+), 560 deletions(-) create mode 100644 internal/web/controller/client_node_apply_test.go create mode 100644 internal/web/job/node_traffic_isolation_test.go create mode 100644 internal/web/service/client_node_apply.go create mode 100644 internal/web/service/client_node_apply_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cd6827ab2..9639a7fc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -147,10 +147,10 @@ jobs: - name: PostgreSQL node client push ordering run: | set -o pipefail - go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log + go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) - if [ "$passed" -ne 7 ]; then - echo "expected 7 passing PostgreSQL node client ordering tests, got $passed" >&2 + if [ "$passed" -ne 8 ]; then + echo "expected 8 passing PostgreSQL node client ordering tests, got $passed" >&2 exit 1 fi diff --git a/docs/architecture.md b/docs/architecture.md index 06e27193c..33d3f3781 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -390,6 +390,19 @@ merged with GUID-based baselines to avoid double counting after resets. `model.NodeClientTraffic`, `model.ClientGlobalTraffic` (cross-master totals). A client reset is queued per hosting node in `model.NodePendingReset` (`service/node_reset_queue.go`) and replayed by the node sync until the node accepts it. + +Client mutations reserve node dispatch turns when their local transactions commit. The writer and +inbound mutex are released before dispatch waits. Conflicting inbounds are ordered, independent +inbounds can use any of four live slots on a node, and full deletion and reconciliation use an +exclusive node turn. Each live push waits up to four seconds for its turn and then receives up to +four seconds for the whole RPC batch. A saturated delta is left dirty for reconciliation. Full +deletions are stored in the transactional node outbox and retried until the direct peer confirms +deletion or absence. HTTP requests can also include validation, writer waits and multiple waves of +inbound work. A direct acknowledgment can report downstream work pending alongside these results. + +Node traffic polls run independently within the shared worker limit. The publisher sums the latest +valid speed sample from every eligible node. Display samples expire after two five-second windows +and leave the cumulative counter baseline available for the next poll. Periodic resets: `job/periodic_traffic_reset_job.go` (keyed off `Inbound.TrafficReset`). Cross-panel totals are stored per master GUID and hosted email, separately from local diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 8c344b2ce..725bcacf2 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -812,6 +812,16 @@ _openapi: (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields - content: Uses the same calendar and catch-up calculation as auto-renew in the panel timezone. resetWeekday is 1 (Monday) to 7 (Sunday), 0 disables @@ -823,7 +833,8 @@ _openapi: preview is informational and does not reserve an allowance or guarantee node availability. heading: preview-client-auto-renewal-dates-without-saving-or-resetting-anything - - content: 'An omitted `flow` leaves every attached inbound on its own flow. Send + - content: >- + An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. @@ -834,9 +845,20 @@ _openapi: still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in - place.' + place. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + - content: >- + Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, @@ -849,9 +871,20 @@ _openapi: still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in - place.' + place. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1 - - content: 'The inbounds are applied concurrently and independently: one that + - content: >- + The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can @@ -859,9 +892,20 @@ _openapi: record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` - prefix and leaves the client already removed from every inbound.' + prefix and leaves the client already removed from every inbound. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed - - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + - content: >- + Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the @@ -871,23 +915,55 @@ _openapi: record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` - prefix and leaves the client already removed from every inbound.' + prefix and leaves the client already removed from every inbound. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1 - - content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound + - content: >- + A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still - attached and a `success:false` response can be partial.' + attached and a `success:false` response can be partial. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json - - content: 'The inbounds are applied concurrently and independently: one that + - content: >- + The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing - beyond the inbounds, so every error carries the prefix.' + beyond the inbounds, so every error carries the prefix. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: detach-a-client-from-one-or-more-inbounds-without-deleting-the-client - content: The original credentials remain the primary device. Additional devices share their parent client email, traffic quota, expiry and enable @@ -909,6 +985,41 @@ _openapi: previously downloaded configuration loses access after the configuration is applied. heading: delete-an-additional-wireguard-device-and-release-its-address + - content: For node-backed changes, the result can include obj.nodeResults and + obj.nodePending alongside the bulk counts and per-email results. A + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-the-optional-limithwid-sets-maximum-registered-devices-0--unlimited-the-optional-adtag-sets-mtproto-telegram-sponsor-channel-none-clears-alternatively-send-externallinks-to-append-external-share-links-and-https-subscriptions-to-each-selected-client-in-one-transaction-this-mode-cannot-be-combined-with-other-adjustments-existing-entries-metadata-and-ordering-are-preserved-duplicates-match-kind-value-per-client-including-repeated-input-rows-the-first-entry-wins-missing-clients-are-not-written-and-appear-in-skipped-externallinksadded-counts-inserted-rows-externallinksskipped-counts-duplicate-rows-across-found-clients-externallinkserrors-counts-missing-clients-and-adjusted-counts-clients-receiving-at-least-one-new-row-validation-or-database-failure-aborts-the-whole-append-without-writes-repeating-an-append-is-idempotent-and-does-not-restart-xray + - content: For node-backed changes, the result can include obj.nodeResults and + obj.nodePending alongside the bulk counts and per-email results. A + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons + - content: For node-backed changes, the result can include obj.nodeResults and + obj.nodePending alongside the bulk counts and per-email results. A + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons + - content: For node-backed changes, the result can include obj.nodeResults and + obj.nodePending alongside the bulk counts and per-email results. A + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion + - content: For node-backed changes, the result can include obj.nodeResults and + obj.nodePending alongside the bulk counts and per-email results. A + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running + - content: For node-backed changes, the result can include obj.nodeResults and + obj.nodePending alongside the bulk counts and per-email results. A + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running + - content: For node-backed changes, the result can include obj.nodeResults and + obj.nodePending alongside the bulk counts and per-email results. A + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 4877ccf2d..fee39fb9a 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -2114,6 +2114,16 @@ ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2127,6 +2137,170 @@ ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2149,6 +2323,48 @@ ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2419,6 +2635,42 @@ ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { @@ -10552,7 +10804,7 @@ ], "summary": "Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.", "operationId": "post_panel_api_clients_add", - "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", + "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "requestBody": { "required": true, "content": { @@ -10609,12 +10861,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client added" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10720,7 +10994,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update_email", - "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10764,12 +11038,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10784,7 +11080,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10828,12 +11124,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10848,7 +11166,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del_email", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10883,12 +11201,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10903,7 +11243,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10938,12 +11278,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10958,7 +11320,7 @@ ], "summary": "Attach an existing client to one or more additional inbounds. Body is JSON.", "operationId": "post_panel_api_clients_email_attach", - "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.", + "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11012,11 +11374,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11031,7 +11416,7 @@ ], "summary": "Detach a client from one or more inbounds without deleting the client.", "operationId": "post_panel_api_clients_email_detach", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11084,11 +11469,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11862,6 +12270,7 @@ ], "summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: \"none\" clears it, \"xtls-rprx-vision\"/\"xtls-rprx-vision-udp443\" set it where the inbound supports it (omit or \"\" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel (\"none\" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.", "operationId": "post_panel_api_clients_bulkAdjust", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -11953,6 +12362,14 @@ "obj": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] } } @@ -11969,6 +12386,7 @@ ], "summary": "Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkEnable", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -11999,17 +12417,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12027,6 +12455,7 @@ ], "summary": "Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkDisable", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12057,17 +12486,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12085,6 +12524,7 @@ ], "summary": "Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.", "operationId": "post_panel_api_clients_bulkDel", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12116,17 +12556,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDeleteResult" + } } }, "example": { "success": true, "obj": { - "deleted": 2, + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12144,6 +12594,7 @@ ], "summary": "Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.", "operationId": "post_panel_api_clients_bulkCreate", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12195,17 +12646,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkCreateResult" + } } }, "example": { "success": true, "obj": { - "created": 2, + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "alice@example.com", - "reason": "email already in use" + "email": "", + "reason": "" } ] } @@ -12328,6 +12789,7 @@ ], "summary": "Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkAttach", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12385,20 +12847,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkAttachResult" + } } }, "example": { "success": true, "obj": { "attached": [ - "alice", - "bob" + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } ], "skipped": [ - "bob" - ], - "errors": [] + "" + ] } } } @@ -12466,6 +12939,7 @@ ], "summary": "Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with the requested set and detaches from those only; (email, inbound) pairs where the client is not currently attached are silently no-ops. Emails not attached to any of the requested inbounds are reported under skipped. Client records are kept even if they become orphaned — use bulkDel for full removal. Returns per-email detached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkDetach", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12520,18 +12994,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDetachResult" + } } }, "example": { "success": true, "obj": { "detached": [ - "alice", - "bob" + "" ], - "skipped": [], - "errors": [] + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] } } } diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 4877ccf2d..fee39fb9a 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -2114,6 +2114,16 @@ ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2127,6 +2137,170 @@ ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2149,6 +2323,48 @@ ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2419,6 +2635,42 @@ ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { @@ -10552,7 +10804,7 @@ ], "summary": "Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.", "operationId": "post_panel_api_clients_add", - "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", + "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "requestBody": { "required": true, "content": { @@ -10609,12 +10861,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client added" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10720,7 +10994,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update_email", - "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10764,12 +11038,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10784,7 +11080,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10828,12 +11124,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10848,7 +11166,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del_email", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10883,12 +11201,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10903,7 +11243,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10938,12 +11278,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10958,7 +11320,7 @@ ], "summary": "Attach an existing client to one or more additional inbounds. Body is JSON.", "operationId": "post_panel_api_clients_email_attach", - "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.", + "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11012,11 +11374,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11031,7 +11416,7 @@ ], "summary": "Detach a client from one or more inbounds without deleting the client.", "operationId": "post_panel_api_clients_email_detach", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11084,11 +11469,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11862,6 +12270,7 @@ ], "summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: \"none\" clears it, \"xtls-rprx-vision\"/\"xtls-rprx-vision-udp443\" set it where the inbound supports it (omit or \"\" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel (\"none\" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.", "operationId": "post_panel_api_clients_bulkAdjust", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -11953,6 +12362,14 @@ "obj": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] } } @@ -11969,6 +12386,7 @@ ], "summary": "Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkEnable", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -11999,17 +12417,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12027,6 +12455,7 @@ ], "summary": "Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkDisable", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12057,17 +12486,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12085,6 +12524,7 @@ ], "summary": "Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.", "operationId": "post_panel_api_clients_bulkDel", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12116,17 +12556,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDeleteResult" + } } }, "example": { "success": true, "obj": { - "deleted": 2, + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12144,6 +12594,7 @@ ], "summary": "Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.", "operationId": "post_panel_api_clients_bulkCreate", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12195,17 +12646,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkCreateResult" + } } }, "example": { "success": true, "obj": { - "created": 2, + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "alice@example.com", - "reason": "email already in use" + "email": "", + "reason": "" } ] } @@ -12328,6 +12789,7 @@ ], "summary": "Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkAttach", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12385,20 +12847,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkAttachResult" + } } }, "example": { "success": true, "obj": { "attached": [ - "alice", - "bob" + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } ], "skipped": [ - "bob" - ], - "errors": [] + "" + ] } } } @@ -12466,6 +12939,7 @@ ], "summary": "Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with the requested set and detaches from those only; (email, inbound) pairs where the client is not currently attached are silently no-ops. Emails not attached to any of the requested inbounds are reported under skipped. Client records are kept even if they become orphaned — use bulkDel for full removal. Returns per-email detached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkDetach", + "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { "required": true, "content": { @@ -12520,18 +12994,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDetachResult" + } } }, "example": { "success": true, "obj": { "detached": [ - "alice", - "bob" + "" ], - "skipped": [], - "errors": [] + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] } } } diff --git a/frontend/scripts/build-openapi.mjs b/frontend/scripts/build-openapi.mjs index e2b4e5d2e..69e0688d5 100644 --- a/frontend/scripts/build-openapi.mjs +++ b/frontend/scripts/build-openapi.mjs @@ -266,7 +266,9 @@ function buildOperation(ep, tag) { ...(ep.responseSchemaArrayNullable ? { nullable: true } : {}), items: ref, } - : ref; + : ep.responseSchemaNullable + ? { oneOf: [ref, { type: 'object', nullable: true, enum: [null] }] } + : ref; if (successExample === undefined) { successExample = { success: true, obj: ep.responseSchemaArray ? [obj] : obj }; } diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 081067ac9..310051ae7 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -509,13 +509,122 @@ export const EXAMPLES: Record = { "BulkAdjustResult": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] }, + "BulkAttachResult": { + "attached": [ + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] + }, + "BulkCreateReport": { + "email": "", + "reason": "" + }, + "BulkCreateResult": { + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, + "BulkDeleteReport": { + "email": "", + "reason": "" + }, + "BulkDeleteResult": { + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, + "BulkDetachResult": { + "detached": [ + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] + }, "BulkExternalLinksResult": { "added": 4, "errors": 0, "skipped": 0 }, + "BulkSetEnableReport": { + "email": "", + "reason": "" + }, + "BulkSetEnableResult": { + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, "Client": { "adTag": "0123456789abcdef0123456789abcdef", "allowedIPs": [ @@ -585,6 +694,21 @@ export const EXAMPLES: Record = { "flowOverride": "", "inboundId": 0 }, + "ClientNodeApplyOutcome": { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + }, + "ClientNodeApplyResponse": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + }, "ClientNodeUsage": { "down": 2097152, "nodeId": 7, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index e5b7085f6..542b3178d 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -2088,6 +2088,16 @@ export const SCHEMAS: Record = { ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2101,6 +2111,170 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2123,6 +2297,48 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2393,6 +2609,42 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 5bf30b7ce..62b462e76 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -499,15 +499,69 @@ export interface BulkAdjustReport { export interface BulkAdjustResult { adjusted: number; externalLinks?: BulkExternalLinksResult | null; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; skipped?: BulkAdjustReport[]; } +export interface BulkAttachResult { + attached: string[]; + errors: string[]; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped: string[]; +} + +export interface BulkCreateReport { + email: string; + reason: string; +} + +export interface BulkCreateResult { + created: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkCreateReport[]; +} + +export interface BulkDeleteReport { + email: string; + reason: string; +} + +export interface BulkDeleteResult { + deleted: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkDeleteReport[]; +} + +export interface BulkDetachResult { + detached: string[]; + errors: string[]; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped: string[]; +} + export interface BulkExternalLinksResult { added: number; errors: number; skipped: number; } +export interface BulkSetEnableReport { + email: string; + reason: string; +} + +export interface BulkSetEnableResult { + changed: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkSetEnableReport[]; +} + export interface Client { adTag?: string; allowedIPs?: string[]; @@ -563,6 +617,17 @@ export interface ClientInbound { inboundId: number; } +export interface ClientNodeApplyOutcome { + nodeId: number; + reason?: string; + status: string; +} + +export interface ClientNodeApplyResponse { + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; +} + export interface ClientNodeUsage { down: number; nodeId: number; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 91489537e..f0a263118 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -522,10 +522,58 @@ export type BulkAdjustReport = z.infer; export const BulkAdjustResultSchema = z.object({ adjusted: z.number().int(), externalLinks: z.lazy(() => BulkExternalLinksResultSchema).nullable().optional(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), skipped: z.array(z.lazy(() => BulkAdjustReportSchema)).optional(), }); export type BulkAdjustResult = z.infer; +export const BulkAttachResultSchema = z.object({ + attached: z.array(z.string()), + errors: z.array(z.string()), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.string()), +}); +export type BulkAttachResult = z.infer; + +export const BulkCreateReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkCreateReport = z.infer; + +export const BulkCreateResultSchema = z.object({ + created: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkCreateReportSchema)).optional(), +}); +export type BulkCreateResult = z.infer; + +export const BulkDeleteReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkDeleteReport = z.infer; + +export const BulkDeleteResultSchema = z.object({ + deleted: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkDeleteReportSchema)).optional(), +}); +export type BulkDeleteResult = z.infer; + +export const BulkDetachResultSchema = z.object({ + detached: z.array(z.string()), + errors: z.array(z.string()), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.string()), +}); +export type BulkDetachResult = z.infer; + export const BulkExternalLinksResultSchema = z.object({ added: z.number().int(), errors: z.number().int(), @@ -533,6 +581,20 @@ export const BulkExternalLinksResultSchema = z.object({ }); export type BulkExternalLinksResult = z.infer; +export const BulkSetEnableReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkSetEnableReport = z.infer; + +export const BulkSetEnableResultSchema = z.object({ + changed: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkSetEnableReportSchema)).optional(), +}); +export type BulkSetEnableResult = z.infer; + export const ClientSchema = z.object({ adTag: z.string().optional(), allowedIPs: z.array(z.string()).optional(), @@ -591,6 +653,19 @@ export const ClientInboundSchema = z.object({ }); export type ClientInbound = z.infer; +export const ClientNodeApplyOutcomeSchema = z.object({ + nodeId: z.number().int(), + reason: z.string().optional(), + status: z.string(), +}); +export type ClientNodeApplyOutcome = z.infer; + +export const ClientNodeApplyResponseSchema = z.object({ + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), +}); +export type ClientNodeApplyResponse = z.infer; + export const ClientNodeUsageSchema = z.object({ down: z.number().int(), nodeId: z.number().int(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 8eb435b29..8e41e0bf9 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -45,6 +45,7 @@ export interface Endpoint { requestSchema?: Record; bodyRequiredOneOf?: string[]; responseSchema?: string; + responseSchemaNullable?: boolean; responseSchemaArray?: boolean; responseSchemaArrayNullable?: boolean; responseObjectSchema?: Record; @@ -65,6 +66,17 @@ export interface Section { endpoints: Endpoint[]; } +const clientNodeApplyResponse = { + responseSchema: 'ClientNodeApplyResponse', + responseSchemaNullable: true, +} satisfies Partial; + +const clientNodeApplyDescription = + '\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.'; + +const bulkClientNodeApplyDescription = + 'For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.'; + // /inbounds/update replaces the whole row, so it takes the same payload as /add. const inboundBody = '{\n "enable": true,\n "remark": "VLESS-443",\n "listen": "",\n "port": 443,\n "protocol": "vless",\n "expiryTime": 0,\n "total": 0,\n "settings": {\n "clients": [{ "id": "...", "email": "user1" }],\n "decryption": "none"\n },\n "streamSettings": {\n "network": "tcp",\n "security": "reality",\n "realitySettings": { "show": false, "dest": "..." }\n },\n "sniffing": {\n "enabled": true,\n "destOverride": ["http", "tls"]\n }\n}'; @@ -1309,7 +1321,8 @@ export const sections: readonly Section[] = [ summary: 'Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.', description: - 'Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.', + 'Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.' + + clientNodeApplyDescription, params: [ { name: 'client', @@ -1325,7 +1338,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "tgId": 0,\n "limitIp": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [3, 5]\n}', - response: '{\n "success": true,\n "msg": "Client added"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1379,7 +1392,8 @@ export const sections: readonly Section[] = [ summary: 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.', description: - 'An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + 'An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.' + + clientNodeApplyDescription, params: [ { name: 'email', @@ -1389,7 +1403,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "email": "alice@example.com",\n "totalGB": 107374182400,\n "expiryTime": 1767225600000,\n "limitHwid": 2,\n "tgId": 123456789,\n "enable": true\n}', - response: '{\n "success": true,\n "msg": "Client updated"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1397,7 +1411,8 @@ export const sections: readonly Section[] = [ summary: 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.', description: - 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.' + + clientNodeApplyDescription, params: [ { name: 'email', @@ -1407,7 +1422,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "email": "alice@example.com",\n "totalGB": 107374182400,\n "expiryTime": 1767225600000,\n "limitHwid": 2,\n "tgId": 123456789,\n "enable": true\n}', - response: '{\n "success": true,\n "msg": "Client updated"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1415,7 +1430,8 @@ export const sections: readonly Section[] = [ summary: 'Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.', description: - 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.', + 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1426,7 +1442,7 @@ export const sections: readonly Section[] = [ optional: true, }, ], - response: '{\n "success": true,\n "msg": "Client deleted"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1434,7 +1450,8 @@ export const sections: readonly Section[] = [ summary: 'Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.', description: - 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.', + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'query', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1445,14 +1462,15 @@ export const sections: readonly Section[] = [ optional: true, }, ], - response: '{\n "success": true,\n "msg": "Client deleted"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', path: '/panel/api/clients/:email/attach', summary: 'Attach an existing client to one or more additional inbounds. Body is JSON.', description: - 'A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.', + 'A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1463,14 +1481,15 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "inboundIds": [7, 9]\n}', - response: '{\n "success": true\n}', + ...clientNodeApplyResponse, }, { method: 'POST', path: '/panel/api/clients/:email/detach', summary: 'Detach a client from one or more inbounds without deleting the client.', description: - 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.', + 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1481,7 +1500,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "inboundIds": [5]\n}', - response: '{\n "success": true\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1631,6 +1650,7 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkAdjust', + description: bulkClientNodeApplyDescription, summary: 'Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: "none" clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the inbound supports it (omit or "" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel ("none" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.', requestSchema: { @@ -1678,38 +1698,38 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkEnable', + description: bulkClientNodeApplyDescription, summary: 'Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.', body: '{\n "emails": ["alice", "bob"]\n}', - response: - '{\n "success": true,\n "obj": {\n "changed": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkSetEnableResult', }, { method: 'POST', path: '/panel/api/clients/bulkDisable', + description: bulkClientNodeApplyDescription, summary: 'Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.', body: '{\n "emails": ["alice", "bob"]\n}', - response: - '{\n "success": true,\n "obj": {\n "changed": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkSetEnableResult', }, { method: 'POST', path: '/panel/api/clients/bulkDel', + description: bulkClientNodeApplyDescription, summary: 'Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.', body: '{\n "emails": ["alice", "bob"],\n "keepTraffic": false\n}', - response: - '{\n "success": true,\n "obj": {\n "deleted": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkDeleteResult', }, { method: 'POST', path: '/panel/api/clients/bulkCreate', + description: bulkClientNodeApplyDescription, summary: 'Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.', body: '[\n {\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 2,\n "enable": true\n },\n "inboundIds": [7]\n },\n {\n "client": {\n "email": "bob@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [7, 9]\n }\n]', - response: - '{\n "success": true,\n "obj": {\n "created": 2,\n "skipped": [\n { "email": "alice@example.com", "reason": "email already in use" }\n ]\n }\n}', + responseSchema: 'BulkCreateResult', }, { method: 'POST', @@ -1730,6 +1750,7 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkAttach', + description: bulkClientNodeApplyDescription, summary: 'Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.', params: [ @@ -1755,8 +1776,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "emails": ["alice", "bob"],\n "inboundIds": [7, 9]\n}', - response: - '{\n "success": true,\n "obj": {\n "attached": ["alice", "bob"],\n "skipped": ["bob"],\n "errors": []\n }\n}', + responseSchema: 'BulkAttachResult', }, { method: 'GET', @@ -1776,6 +1796,7 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkDetach', + description: bulkClientNodeApplyDescription, summary: "Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with the requested set and detaches from those only; (email, inbound) pairs where the client is not currently attached are silently no-ops. Emails not attached to any of the requested inbounds are reported under skipped. Client records are kept even if they become orphaned — use bulkDel for full removal. Returns per-email detached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.", params: [ @@ -1793,8 +1814,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "emails": ["alice", "bob"],\n "inboundIds": [7, 9]\n}', - response: - '{\n "success": true,\n "obj": {\n "detached": ["alice", "bob"],\n "skipped": [],\n "errors": []\n }\n}', + responseSchema: 'BulkDetachResult', }, { method: 'POST', diff --git a/frontend/src/test/clients-summary.test.tsx b/frontend/src/test/clients-summary.test.tsx index 22362e74e..a6407ace1 100644 --- a/frontend/src/test/clients-summary.test.tsx +++ b/frontend/src/test/clients-summary.test.tsx @@ -167,18 +167,28 @@ describe('client summary always reflects the server, never a client_stats recomp }); expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 100, down: 200 }); + // The next staggered publication contains both the fresh and retained node samples. + act(() => { + result.current.applyTrafficEvent({ + clientTrafficSource: 'node', + clientTrafficIntervalMs: 5_000, + clientTraffics: [{ email: 'shared@example.test', up: 750, down: 1_250 }], + }); + }); + expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 150, down: 250 }); + // A local Xray poll with no movement must not wipe the node sample. act(() => { result.current.applyTrafficEvent({ clientTraffics: [] }); }); - expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 100, down: 200 }); + expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 150, down: 250 }); act(() => { result.current.applyTrafficEvent({ clientTraffics: [{ email: 'shared@example.test', up: 50, down: 50 }], }); }); - expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 110, down: 210 }); + expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 160, down: 260 }); act(() => { result.current.applyTrafficEvent({ diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts index 89a670765..622514ccc 100644 --- a/frontend/src/utils/index.ts +++ b/frontend/src/utils/index.ts @@ -45,7 +45,7 @@ export class HttpUtil { typeof msg.obj === 'object' && (msg.obj as { nodePending?: unknown }).nodePending === true ) { - getMessage().warning(i18next.t('pages.inbounds.toasts.savedNodeOfflineWillSync')); + getMessage().warning(i18next.t('pages.inbounds.toasts.savedNodeApplyPending')); } return; } diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 9380e28df..1287fa777 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -268,7 +268,8 @@ func (a *ClientController) create(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - needRestart, err := a.clientService.Create(&a.inboundService, &payload) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.Create(&a.inboundService, &payload) // Flagged before the error check: a partly-applied create leaves clients // committed on the inbounds that succeeded, and those still need the restart. if needRestart { @@ -280,10 +281,10 @@ func (a *ClientController) create(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(payload.InboundIds)), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), clientSvc.NodeApplyResponse(), nil) } func (a *ClientController) update(c *gin.Context) { @@ -297,7 +298,8 @@ func (a *ClientController) update(c *gin.Context) { return } inboundFilter := parseInboundIdsQuery(c.Query("inboundIds")) - needRestart, err := a.clientService.UpdateByEmailJSON(&a.inboundService, email, body, inboundFilter...) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.UpdateByEmailJSON(&a.inboundService, email, body, inboundFilter...) // Flagged before the error check: a partly-applied edit leaves the change // committed on the inbounds that succeeded, and those still need the restart. if needRestart { @@ -309,10 +311,10 @@ func (a *ClientController) update(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), pendingNodeObj(a.clientService.HasPendingNode(&a.inboundService, email)), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), clientSvc.NodeApplyResponse(), nil) } func (a *ClientController) delete(c *gin.Context) { @@ -321,7 +323,8 @@ func (a *ClientController) delete(c *gin.Context) { return } keepTraffic := c.Query("keepTraffic") == "1" - needRestart, err := a.clientService.DeleteByEmail(&a.inboundService, email, keepTraffic) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.DeleteByEmail(&a.inboundService, email, keepTraffic) // Flagged before the error check: a partly-applied delete already removed // the client from the inbounds that succeeded, and those need the restart. if needRestart { @@ -333,10 +336,10 @@ func (a *ClientController) delete(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), clientSvc.NodeApplyResponse(), nil) } type attachDetachBody struct { @@ -354,7 +357,8 @@ func (a *ClientController) attach(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - needRestart, err := a.clientService.AttachByEmail(&a.inboundService, email, body.InboundIds) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.AttachByEmail(&a.inboundService, email, body.InboundIds) if needRestart { a.xrayService.SetToNeedRestart() } @@ -364,10 +368,10 @@ func (a *ClientController) attach(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(body.InboundIds)), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), clientSvc.NodeApplyResponse(), nil) } func (a *ClientController) setExternalLinks(c *gin.Context) { @@ -414,6 +418,7 @@ func (a *ClientController) bulkAdjust(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + clientSvc := a.clientService.TrackNodeApplies() var result service.BulkAdjustResult var needRestart bool var err error @@ -424,12 +429,15 @@ func (a *ClientController) bulkAdjust(c *gin.Context) { } result, err = a.clientService.BulkAppendExternalLinks(req.Emails, req.ExternalLinks) } else { - result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag) + result, needRestart, err = clientSvc.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag) } if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -462,11 +470,15 @@ func (a *ClientController) bulkAttach(c *gin.Context) { a.beginBulkAttach(c, req.InboundIds, *req.Selection) return } - result, needRestart, err := a.clientService.BulkAttach(&a.inboundService, req.Emails, req.InboundIds) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkAttach(&a.inboundService, req.Emails, req.InboundIds) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -485,11 +497,15 @@ func (a *ClientController) bulkDetach(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkDetach(&a.inboundService, req.Emails, req.InboundIds) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkDetach(&a.inboundService, req.Emails, req.InboundIds) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -503,11 +519,15 @@ func (a *ClientController) bulkDelete(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -533,11 +553,15 @@ func (a *ClientController) bulkSetEnable(c *gin.Context, enable bool) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkSetEnable(&a.inboundService, req.Emails, enable) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkSetEnable(&a.inboundService, req.Emails, enable) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -551,11 +575,15 @@ func (a *ClientController) bulkCreate(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkCreate(&a.inboundService, payloads) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkCreate(&a.inboundService, payloads) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -811,7 +839,8 @@ func (a *ClientController) detach(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - needRestart, err := a.clientService.DetachByEmailMany(&a.inboundService, email, body.InboundIds) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.DetachByEmailMany(&a.inboundService, email, body.InboundIds) // Flagged before the error check: a partly-applied detach already removed // the client from the inbounds that succeeded, and those need the restart. if needRestart { @@ -823,10 +852,10 @@ func (a *ClientController) detach(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(body.InboundIds)), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), clientSvc.NodeApplyResponse(), nil) } type bulkResetRequest struct { diff --git a/internal/web/controller/client_node_apply_test.go b/internal/web/controller/client_node_apply_test.go new file mode 100644 index 000000000..ad305a1e2 --- /dev/null +++ b/internal/web/controller/client_node_apply_test.go @@ -0,0 +1,199 @@ +package controller + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +func TestClientUpdateReportsTimedOutOnlineNodeAndKeepsLocalSave(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + const email = "partial-node@example.test" + db := database.GetDB() + var nodes []model.Node + var inbounds []model.Inbound + const ( + timeout = iota + downstream + recovered + ) + var slowMode atomic.Int32 + slowStarted := make(chan struct{}, 1) + healthyApplied := make(chan struct{}, 1) + for index, slow := range []bool{false, true} { + tag := fmt.Sprintf("in-%d", 15110+index) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/inbounds/list") { + fmt.Fprintf(w, "{\"success\":true,\"obj\":[{\"id\":1,\"tag\":%q}]}", tag) + } else if strings.Contains(r.URL.Path, "/clients/update/") { + if slow { + switch slowMode.Load() { + case timeout: + _, _ = io.Copy(io.Discard, r.Body) + slowStarted <- struct{}{} + <-r.Context().Done() + return + case downstream: + fmt.Fprint(w, "{\"success\":true,\"obj\":{\"nodePending\":true}}") + return + } + } else { + select { + case healthyApplied <- struct{}{}: + default: + } + } + fmt.Fprint(w, "{\"success\":true}") + } else { + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + parsed, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(parsed.Port()) + if err != nil { + t.Fatal(err) + } + node := model.Node{ + Name: fmt.Sprintf("slow=%t", slow), Address: parsed.Hostname(), Port: port, + Scheme: "http", BasePath: "/", ApiToken: "fixture", TlsVerifyMode: "verify", + AllowPrivateAddress: true, Enable: true, Status: "online", + } + if err := db.Create(&node).Error; err != nil { + t.Fatal(err) + } + inbound := model.Inbound{ + UserId: 1, Enable: true, Tag: tag, Port: 15110 + index, + Protocol: model.VLESS, Settings: "{\"clients\":[],\"decryption\":\"none\"}", StreamSettings: "{\"network\":\"tcp\",\"security\":\"none\"}", + } + if err := db.Create(&inbound).Error; err != nil { + t.Fatal(err) + } + nodes = append(nodes, node) + inbounds = append(inbounds, inbound) + } + clientSvc, inboundSvc := &service.ClientService{}, &service.InboundService{} + if _, err := clientSvc.Create(inboundSvc, &service.ClientCreatePayload{ + Client: model.Client{Email: email, ID: "11111111-2222-4333-8444-555555555555", Enable: true}, + InboundIds: []int{inbounds[0].Id, inbounds[1].Id}, + }); err != nil { + t.Fatal(err) + } + for i, inbound := range inbounds { + if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).Update("node_id", nodes[i].Id).Error; err != nil { + t.Fatal(err) + } + } + + gin.SetMode(gin.TestMode) + router := gin.New() + NewClientController(router.Group("/panel/api/clients")) + type applyEnvelope struct { + Success bool + Obj service.ClientNodeApplyResponse + } + request := func(comment string) *httptest.ResponseRecorder { + body := fmt.Sprintf("{\"comment\":%q}", comment) + req := httptest.NewRequest(http.MethodPost, "/panel/api/clients/update/"+email, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + router.ServeHTTP(response, req) + return response + } + decode := func(response *httptest.ResponseRecorder) applyEnvelope { + t.Helper() + var msg applyEnvelope + if err := json.Unmarshal(response.Body.Bytes(), &msg); err != nil { + t.Fatal(err) + } + if !msg.Success || len(msg.Obj.NodeResults) != 2 { + t.Fatalf("expected local success and both node results, got %s", response.Body.String()) + } + return msg + } + started := time.Now() + done := make(chan *httptest.ResponseRecorder, 1) + finished := make(chan struct{}) + go func() { + defer close(finished) + done <- request("saved locally") + }() + t.Cleanup(func() { <-finished }) + wait := func(ch <-chan struct{}) { + t.Helper() + select { + case <-ch: + case <-time.After(3 * time.Second): + t.Fatal("expected RPC did not start before the slow node's deadline") + } + } + wait(slowStarted) + wait(healthyApplied) + writerStarted := time.Now() + if _, _, err := inboundSvc.AddTraffic(nil, nil); err != nil { + t.Fatal(err) + } + t.Logf("fixture writer barrier while RPC in flight: %s", time.Since(writerStarted)) + select { + case <-done: + t.Fatal("unrelated writer work was held behind the slow RPC") + default: + } + msg := decode(<-done) + t.Logf("fixture timed-out request: %s", time.Since(started)) + if got := msg.Obj.NodeResults[0]; got.NodeID != nodes[0].Id || got.Status != "applied" { + t.Fatalf("healthy node outcome: %+v", got) + } + if got := msg.Obj.NodeResults[1]; !msg.Obj.NodePending || got.NodeID != nodes[1].Id || got.Status != "pending" || got.Reason != "timeout" { + t.Fatalf("slow node outcome: %+v", got) + } + if stored, err := clientSvc.GetRecordByEmail(nil, email); err != nil || stored.Comment != "saved locally" { + t.Fatalf("local edit not persisted: record=%+v error=%v", stored, err) + } + if err := db.First(&nodes[1], nodes[1].Id).Error; err != nil { + t.Fatal(err) + } + if !nodes[1].ConfigDirty || nodes[1].Status != "online" { + t.Fatalf("timed-out online node lost its durable reconcile flag: %+v", nodes[1]) + } + + slowMode.Store(downstream) + msg = decode(request("downstream pending")) + if got := msg.Obj.NodeResults[1]; !msg.Obj.NodePending || got.Status != "pending" || got.Reason != "downstream_pending" { + t.Fatalf("forwarded pending result was lost: %+v", msg.Obj) + } + + slowMode.Store(recovered) + started = time.Now() + msg = decode(request("both acknowledged")) + t.Logf("fixture healthy request: %s", time.Since(started)) + if got := msg.Obj.NodeResults[1]; msg.Obj.NodePending || got.Status != "applied" || got.Reason != "" { + t.Fatalf("recovered node outcome: %+v", msg.Obj) + } +} diff --git a/internal/web/controller/util.go b/internal/web/controller/util.go index 527b3845c..c054dabc4 100644 --- a/internal/web/controller/util.go +++ b/internal/web/controller/util.go @@ -102,16 +102,6 @@ func jsonMsgObj(c *gin.Context, msg string, obj any, err error) { c.JSON(http.StatusOK, m) } -// pendingNodeObj returns a response object flagging that the save committed -// locally but a backing node was offline/disabled, so the change will be -// mirrored to the node once it reconnects. Returns nil when nothing is pending. -func pendingNodeObj(pending bool) any { - if pending { - return gin.H{"nodePending": true} - } - return nil -} - // 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{ diff --git a/internal/web/job/node_client_speed_test.go b/internal/web/job/node_client_speed_test.go index 5b082c6f9..5aa2cfc1d 100644 --- a/internal/web/job/node_client_speed_test.go +++ b/internal/web/job/node_client_speed_test.go @@ -2,6 +2,7 @@ package job import ( "testing" + "time" "github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" @@ -76,13 +77,55 @@ func TestRecordNodeClientSpeed_PerNodeBaselinesAndPrune(t *testing.T) { {ClientStats: []xray.ClientTraffic{{Email: "a@x", Up: up, Down: down}}}, }} } - j.recordNodeClientSpeed(1, mk(0, 0)) - j.recordNodeClientSpeed(2, mk(1_000_000, 1_000_000)) - if len(j.tickClientSpeed) != 0 || len(j.prevClientTotals) != 2 { - t.Fatalf("baselines: tick=%v prev=%v", j.tickClientSpeed, j.prevClientTotals) + j.recordNodeClientSpeed(t.Context(), 1, mk(0, 0), time.Now()) + j.recordNodeClientSpeed(t.Context(), 2, mk(1_000_000, 1_000_000), time.Now()) + if len(j.clientSamples[1].speed) != 0 || len(j.clientSamples[2].speed) != 0 || len(j.prevClientTotals) != 2 { + t.Fatalf("baselines: tick=%v prev=%v", j.clientSamples, j.prevClientTotals) } j.pruneClientSpeedNodes([]*model.Node{{Id: 1}}) if _, ok := j.prevClientTotals[2]; ok || len(j.prevClientTotals) != 1 { t.Fatalf("deleted node not pruned: %v", j.prevClientTotals) } } + +func TestNodeClientSpeedRetainsStaggeredSamples(t *testing.T) { + j := NewNodeTrafficSyncJob() + now := time.Now() + snapshot := func(up int64) *runtime.TrafficSnapshot { + return &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + {ClientStats: []xray.ClientTraffic{{Email: "shared@example.test", Up: up}}}, + }} + } + j.recordNodeClientSpeed(t.Context(), 1, snapshot(0), now) + j.recordNodeClientSpeed(t.Context(), 2, snapshot(0), now.Add(time.Second)) + j.recordNodeClientSpeed(t.Context(), 1, snapshot(500), now.Add(5*time.Second)) + j.recordNodeClientSpeed(t.Context(), 2, snapshot(300), now.Add(6*time.Second)) + + for _, elapsed := range []time.Duration{7 * time.Second, 12 * time.Second} { + _, speed := j.clientSpeedSnapshot(now.Add(elapsed)) + if len(speed) != 1 || speed[0].Email != "shared@example.test" || speed[0].Up != 800 { + t.Fatalf("publication at %s lost one node's latest contribution: %+v", elapsed, speed) + } + } + j.recordNodeClientSpeed(t.Context(), 2, snapshot(300), now.Add(13*time.Second)) + _, speed := j.clientSpeedSnapshot(now.Add(14 * time.Second)) + if len(speed) != 1 || speed[0].Up != 500 { + t.Fatalf("an idle poll must replace that node's nonzero sample: %+v", speed) + } + _, speed = j.clientSpeedSnapshot(now.Add(24 * time.Second)) + if speed == nil || len(speed) != 0 { + t.Fatalf("expired samples must publish an explicit empty array: %+v", speed) + } + + j.recordNodeClientSpeed(t.Context(), 1, snapshot(2500), now.Add(25*time.Second)) + _, speed = j.clientSpeedSnapshot(now.Add(25 * time.Second)) + if len(speed) != 1 || speed[0].Up != 500 { + t.Fatalf("display expiry lost the cumulative baseline: %+v", speed) + } + + j.pruneClientSpeedNodes(nil) + _, speed = j.clientSpeedSnapshot(now.Add(25 * time.Second)) + if speed == nil || len(speed) != 0 { + t.Fatalf("removing the last node must clear its contribution: %+v", speed) + } +} diff --git a/internal/web/job/node_reset_replay_test.go b/internal/web/job/node_reset_replay_test.go index 961b67969..f356239ae 100644 --- a/internal/web/job/node_reset_replay_test.go +++ b/internal/web/job/node_reset_replay_test.go @@ -62,7 +62,10 @@ func TestNodeTrafficSyncReplaysOwedResetBeforeSnapshot(t *testing.T) { t.Fatalf("seed pending reset: %v", err) } - NewNodeTrafficSyncJob().Run() + job := NewNodeTrafficSyncJob() + job.Run() + job.workers.Wait() + job.Close() mu.Lock() got := slices.Clone(calls) diff --git a/internal/web/job/node_sync_operational_query_test.go b/internal/web/job/node_sync_operational_query_test.go index 615558dbc..a33944514 100644 --- a/internal/web/job/node_sync_operational_query_test.go +++ b/internal/web/job/node_sync_operational_query_test.go @@ -3,6 +3,7 @@ package job import ( "path/filepath" "strings" + "sync" "testing" "github.com/op/go-logging" @@ -45,10 +46,13 @@ func TestBackgroundNodeJobs_SkipNodeDashboardStatQueries(t *testing.T) { t.Fatalf("create client_traffic: %v", err) } + var mu sync.Mutex var queries []string recordSQL := func(tx *gorm.DB) { if sql := tx.Statement.SQL.String(); sql != "" { + mu.Lock() queries = append(queries, sql) + mu.Unlock() } } const cbName = "test:job-node-enum-sql" @@ -67,7 +71,10 @@ func TestBackgroundNodeJobs_SkipNodeDashboardStatQueries(t *testing.T) { _ = db.Callback().Raw().Remove(cbName) }) - NewNodeTrafficSyncJob().Run() + job := NewNodeTrafficSyncJob() + job.Run() + job.workers.Wait() + job.Close() NewNodeHeartbeatJob().Run() for _, q := range queries { diff --git a/internal/web/job/node_traffic_isolation_test.go b/internal/web/job/node_traffic_isolation_test.go new file mode 100644 index 000000000..68bed06a1 --- /dev/null +++ b/internal/web/job/node_traffic_isolation_test.go @@ -0,0 +1,389 @@ +package job + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +func TestNodeTrafficSyncAllowsHealthyNextTickDuringSlowReconcile(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + slowRequests := make(chan struct{}, 8) + fastRequests := make(chan struct{}, 8) + var slowReconciles atomic.Int32 + var slowID int + for _, slow := range []bool{true, false} { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + slowReconciles.Add(1) + slowRequests <- struct{}{} + <-release + } else if !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + fastRequests <- struct{}{} + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, "{\"success\":true,\"obj\":[]}") + })) + t.Cleanup(srv.Close) + parsed, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(parsed.Port()) + if err != nil { + t.Fatal(err) + } + node := model.Node{ + Name: fmt.Sprintf("slow=%t", slow), Address: parsed.Hostname(), Port: port, + Scheme: "http", BasePath: "/", ApiToken: "fixture", TlsVerifyMode: "verify", + AllowPrivateAddress: true, Enable: true, Status: "online", ConfigDirty: slow, + } + if err := database.GetDB().Create(&node).Error; err != nil { + t.Fatal(err) + } + if slow { + slowID = node.Id + } + } + j := NewNodeTrafficSyncJob() + first := make(chan struct{}) + go func() { defer close(first); j.Run() }() + t.Cleanup(func() { unblock(); <-first; j.Close() }) + wait := func(ch <-chan struct{}, which string) { + t.Helper() + select { + case <-ch: + case <-time.After(2 * time.Second): + t.Fatalf("%s did not start", which) + } + } + wait(slowRequests, "blocked reconcile") + wait(fastRequests, "first healthy snapshot") + + deadline := time.After(2 * time.Second) + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() +waiting: + for { + select { + case <-ticker.C: + j.Run() + case <-fastRequests: + if got := slowReconciles.Load(); got != 1 { + t.Fatalf("slow reconcile started %d times while blocked, want 1", got) + } + break waiting + case <-deadline: + t.Fatal("the next healthy snapshot was blocked behind a different node's reconciliation") + } + } + unblock() + wait(slowRequests, "recovered node snapshot") + if _, _, dirty, _, err := (&service.NodeService{}).NodeSyncState(slowID); err != nil || dirty { + t.Fatalf("reconcile did not clear the recovered node's dirty flag: dirty=%t err=%v", dirty, err) + } +} + +func TestNodeTrafficSyncDispatchesWhileTrafficWriterIsBusy(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + db := database.GetDB() + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + fetched := make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/panel/api/inbounds/list": + select { + case fetched <- struct{}{}: + default: + } + case "/panel/api/clients/onlinesByGuid", "/panel/api/clients/lastOnline", + "/panel/api/clients/activeInbounds", "/panel/api/clients/clientIpsByGuid": + fmt.Fprint(w, `{"success":true,"obj":{}}`) + return + } + fmt.Fprint(w, `{"success":true,"obj":[]}`) + })) + t.Cleanup(server.Close) + address, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(address.Port()) + if err != nil { + t.Fatal(err) + } + healthy := model.Node{ + Name: "healthy", Scheme: "http", Address: address.Hostname(), Port: port, + BasePath: "/", ApiToken: "fixture", AllowPrivateAddress: true, Enable: true, Status: "online", + } + writerNode := model.Node{Name: "writer peer", Address: "192.0.2.1", Port: 2053, Enable: true, Status: "offline"} + for _, node := range []*model.Node{&healthy, &writerNode} { + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + } + + parked, release := make(chan struct{}), make(chan struct{}) + var parkOnce atomic.Bool + const callback = "test:park-node-traffic-writer" + if err := db.Callback().Query().Before("gorm:query").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == "nodes" && parkOnce.CompareAndSwap(false, true) { + close(parked) + <-release + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + + j := NewNodeTrafficSyncJob() + writerDone := make(chan struct{}) + var writerErr error + go func() { + defer close(writerDone) + _, writerErr = (&service.InboundService{}).SetRemoteTraffic(writerNode.Id, &runtime.TrafficSnapshot{}, true, false) + }() + var runDone chan struct{} + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(func() { + unblock() + <-writerDone + if runDone != nil { + <-runDone + } + j.Close() + }) + + wait := func(c <-chan struct{}, message string) { + t.Helper() + select { + case <-c: + case <-time.After(3 * time.Second): + t.Fatal(message) + } + } + wait(parked, "the node merge did not occupy the traffic writer") + runDone = make(chan struct{}) + go func() { + defer close(runDone) + j.Run() + }() + wait(fetched, "cache pruning blocked the healthy node's snapshot request behind the writer") + wait(runDone, "the dispatcher did not return while the writer was blocked") + unblock() + wait(writerDone, "the node merge did not finish after the writer was released") + if writerErr != nil { + t.Fatal(writerErr) + } +} + +func TestNodeTrafficSyncAdmitsNextNodeAtCapacityAndCancelsOnClose(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + const count = nodeTrafficSyncConcurrency + 1 + var calls [count]atomic.Int32 + started := make(chan int, count*2) + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + prefix := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0] + index, err := strconv.Atoi(prefix) + if err != nil || index < 0 || index >= count { + http.NotFound(w, r) + return + } + if strings.HasSuffix(r.URL.Path, "/inbounds/list") { + calls[index].Add(1) + started <- index + if index == 0 { + select { + case <-release: + case <-r.Context().Done(): + return + } + } else { + <-r.Context().Done() + return + } + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{"success":true,"obj":[]}`) + })) + t.Cleanup(server.Close) + addr, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(addr.Port()) + if err != nil { + t.Fatal(err) + } + for i := range count { + node := model.Node{ + Name: fmt.Sprintf("poll-%d", i), Address: addr.Hostname(), Port: port, Scheme: "http", + BasePath: fmt.Sprintf("/%d/", i), ApiToken: "fixture", TlsVerifyMode: "verify", + Enable: true, Status: "online", AllowPrivateAddress: true, + } + if err := database.GetDB().Create(&node).Error; err != nil { + t.Fatal(err) + } + } + job := NewNodeTrafficSyncJob() + t.Cleanup(func() { unblock(); job.Close() }) + job.Run() + deadline := time.After(2 * time.Second) + for range nodeTrafficSyncConcurrency { + select { + case index := <-started: + if index == count-1 { + t.Fatal("node past the concurrency cap started on the first tick") + } + case <-deadline: + t.Fatal("initial poll did not fill its slots") + } + } + unblock() + tick := time.NewTicker(10 * time.Millisecond) + defer tick.Stop() +waiting: + for { + select { + case <-tick.C: + job.Run() + case index := <-started: + if index != count-1 { + t.Fatalf("round-robin skipped the waiting node and launched %d", index) + } + break waiting + case <-deadline: + t.Fatal("waiting node did not get the freed slot") + } + } + + closed := make(chan struct{}) + go func() { job.Close(); close(closed) }() + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("shutdown waited for the network deadline instead of canceling polls") + } + for i := range count { + if got := calls[i].Load(); got != 1 { + t.Fatalf("node %d received %d polls during admission and shutdown", i, got) + } + } +} + +func TestNodeTrafficSyncRejectsSnapshotWhenNodeBecomesIneligible(t *testing.T) { + for _, action := range []string{"disable", "delete"} { + t.Run(action, func(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + started, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload any = []any{} + switch r.URL.Path { + case "/panel/api/inbounds/list": + payload = []*model.Inbound{{ + Id: 1, Tag: "in-29443", Port: 29443, Protocol: model.VLESS, + Settings: `{"clients":[]}`, Enable: true, + }} + case "/panel/api/hosts/list": + close(started) + select { + case <-release: + case <-r.Context().Done(): + return + } + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": payload}) + })) + t.Cleanup(server.Close) + addr, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(addr.Port()) + if err != nil { + t.Fatal(err) + } + node := model.Node{ + Name: "snapshot-in-flight", Scheme: "http", Address: addr.Hostname(), Port: port, + BasePath: "/", ApiToken: "fixture", TlsVerifyMode: "verify", + Enable: true, Status: "online", AllowPrivateAddress: true, + } + if err := database.GetDB().Create(&node).Error; err != nil { + t.Fatal(err) + } + job := NewNodeTrafficSyncJob() + t.Cleanup(func() { unblock(); job.Close() }) + job.Run() + select { + case <-started: + case <-time.After(2 * time.Second): + t.Fatal("snapshot never passed the initial eligibility check") + } + + nodes := &service.NodeService{} + if action == "disable" { + err = nodes.SetEnable(node.Id, false) + } else { + err = nodes.Delete(node.Id) + } + if err != nil { + t.Fatal(err) + } + unblock() + job.workers.Wait() + + var adopted int64 + if err := database.GetDB().Model(&model.Inbound{}).Where("node_id = ?", node.Id).Count(&adopted).Error; err != nil { + t.Fatal(err) + } + if adopted != 0 || len(job.clientSamples) != 0 { + t.Fatalf("obsolete poll adopted %d inbounds or recorded a speed sample", adopted) + } + }) + } +} diff --git a/internal/web/job/node_traffic_sync_ip_push_test.go b/internal/web/job/node_traffic_sync_ip_push_test.go index 8db156d02..f847008a3 100644 --- a/internal/web/job/node_traffic_sync_ip_push_test.go +++ b/internal/web/job/node_traffic_sync_ip_push_test.go @@ -76,7 +76,10 @@ func TestNodeTrafficSyncPushesOnlyHostedClientIps(t *testing.T) { } } - NewNodeTrafficSyncJob().Run() + job := NewNodeTrafficSyncJob() + job.Run() + job.workers.Wait() + job.Close() for _, email := range []string{"a@node", "b@node"} { if got := pushed[email]; !slices.Equal(got, []string{email}) { diff --git a/internal/web/job/node_traffic_sync_job.go b/internal/web/job/node_traffic_sync_job.go index 50be79292..5dee54ab4 100644 --- a/internal/web/job/node_traffic_sync_job.go +++ b/internal/web/job/node_traffic_sync_job.go @@ -2,6 +2,7 @@ package job import ( "context" + "maps" "strings" "sync" "time" @@ -24,6 +25,8 @@ const ( nodeClientIpSyncInterval = 10 * time.Second nodeClientIpSyncTimeout = 6 * time.Second nodeGlobalPushInterval = 30 * time.Second + // Match the UI speed expiry: two normal five-second polling windows. + nodeClientSampleTTL = 10 * time.Second // nodeInboundSpeedWindowMs is the poll window node-inbound speed deltas are // normalized to; it MUST match the dashboard's TRAFFIC_POLL_INTERVAL_S (5s), // the fixed divisor the frontend applies to turn a delta into a rate. @@ -36,31 +39,41 @@ type inboundSample struct { up, down, at int64 } +type nodePollState struct { + busy bool + cancel context.CancelFunc + lastIP, lastGlobals time.Time +} + +type nodeClientSample struct { + at time.Time + emails []string + speed []*xray.ClientTraffic +} + type NodeTrafficSyncJob struct { nodeService service.NodeService inboundService service.InboundService settingService service.SettingService xrayService service.XrayService - running sync.Mutex - structural atomicBool - ipSyncMu sync.Mutex - lastIpSync int64 - globalPushMu sync.Mutex - lastGlobalPush int64 - // noGuidIpEndpoint tracks nodes (by id) whose client-IP attribution endpoint - // returned 404, so an old-build node is noted once instead of every cycle. + + ctx context.Context + cancel context.CancelFunc + dispatch sync.Mutex + closed bool + workers sync.WaitGroup + polls map[int]*nodePollState + inFlight, nextNode int + maintaining, publishing bool + hadNodes bool + + structural atomicBool noGuidIpEndpoint sync.Map - // prevInboundTotals holds the previous poll's cumulative up/down (and the time - // the counter last changed) per node inbound tag, so the next poll can derive - // a per-inbound speed delta — node inbounds have no local Xray poll. Touched - // only from Run (serialized). + // Only the publisher touches the inbound speed baseline. prevInboundTotals map[string]inboundSample - // Per-client counterpart keyed node id -> email, so a client on several nodes - // gets a baseline per node; guarded by clientSpeedMu as syncOne runs in parallel. - clientSpeedMu sync.Mutex - prevClientTotals map[int]map[string]inboundSample - // This tick's normalized per-client deltas from every synced node. - tickClientSpeed []*xray.ClientTraffic + clientSpeedMu sync.Mutex + prevClientTotals map[int]map[string]inboundSample + clientSamples map[int]nodeClientSample } type atomicBool struct { @@ -83,76 +96,145 @@ func (a *atomicBool) takeAndReset() bool { } func NewNodeTrafficSyncJob() *NodeTrafficSyncJob { - return &NodeTrafficSyncJob{} + ctx, cancel := context.WithCancel(context.Background()) + return &NodeTrafficSyncJob{ctx: ctx, cancel: cancel, polls: make(map[int]*nodePollState)} +} + +// Close drains polls and publication before the panel stops its traffic writer. +func (j *NodeTrafficSyncJob) Close() { + j.dispatch.Lock() + j.closed = true + j.cancel() + j.dispatch.Unlock() + j.workers.Wait() } func (j *NodeTrafficSyncJob) Run() { - if !j.running.TryLock() { + if !j.dispatch.TryLock() { return } - defer j.running.Unlock() - + defer j.dispatch.Unlock() mgr := runtime.GetManager() - if mgr == nil { + if j.closed || mgr == nil { return } - nodes, err := j.nodeService.ListOperational() if err != nil { logger.Warning("node traffic sync: load nodes failed:", err) return } j.inboundService.RetainSyncedNodeOnlineClients(nodes) - if err := j.inboundService.RetainNodeSnapshotCaches(nodes); err != nil { - logger.Warning("node traffic sync: prune snapshot caches failed:", err) - } - if len(nodes) == 0 { - return - } - // Decide once per tick whether this run also syncs client IPs, and stamp the - // clock before the loop so two back-to-back 5s ticks can't both qualify. - doIpSync := false - j.ipSyncMu.Lock() - if now := time.Now().Unix(); now-j.lastIpSync >= int64(nodeClientIpSyncInterval/time.Second) { - doIpSync = true - j.lastIpSync = now + present := make(map[int]*model.Node, len(nodes)) + for _, node := range nodes { + present[node.Id] = node + } + for id, poll := range j.polls { + node := present[id] + if poll.busy && (node == nil || !node.Enable || node.Status != "online") { + poll.cancel() + } + if !poll.busy && node == nil { + delete(j.polls, id) + j.noGuidIpEndpoint.Delete(id) + } } - j.ipSyncMu.Unlock() - j.clientSpeedMu.Lock() - j.tickClientSpeed = make([]*xray.ClientTraffic, 0) j.pruneClientSpeedNodes(nodes) j.clientSpeedMu.Unlock() + // Cache pruning waits on the traffic writer, so keep it off the dispatch path. + j.startPeriodicWorker("node-traffic-maintenance", &j.maintaining, func() { + j.maintainTraffic(nodes) + }) + if len(nodes) == 0 { + if j.hadNodes && !j.publishing { + j.startPeriodicWorker("node-traffic-publish", &j.publishing, j.publishTraffic) + j.hadNodes = false + } + return + } + j.hadNodes = true fetchTimeout, err := j.settingService.GetNodeTrafficFetchTimeout() if err != nil || fetchTimeout < time.Second || fetchTimeout > 30*time.Second { fetchTimeout = nodeTrafficSyncRequestTimeout } - sem := make(chan struct{}, nodeTrafficSyncConcurrency) - var wg sync.WaitGroup - var activeMu sync.Mutex - var activeEmails []string - for _, n := range nodes { - if !n.Enable || n.Status != "online" { + now := time.Now() + for remaining := len(nodes); remaining > 0 && j.inFlight < nodeTrafficSyncConcurrency; remaining-- { + j.nextNode %= len(nodes) + node := nodes[j.nextNode] + j.nextNode++ + if !node.Enable || node.Status != "online" { continue } - wg.Add(1) - sem <- struct{}{} - n := n - common.GoRecover("node-traffic-sync:"+n.Name, func() { - defer wg.Done() - defer func() { <-sem }() - if emails := j.syncOne(mgr, n, doIpSync, fetchTimeout); len(emails) > 0 { - activeMu.Lock() - activeEmails = append(activeEmails, emails...) - activeMu.Unlock() - } + state := j.polls[node.Id] + if state == nil { + state = &nodePollState{} + j.polls[node.Id] = state + } + if state.busy { + continue + } + doIPSync := now.Sub(state.lastIP) >= nodeClientIpSyncInterval + if doIPSync { + state.lastIP = now + } + pushGlobals := now.Sub(state.lastGlobals) >= nodeGlobalPushInterval + if pushGlobals { + state.lastGlobals = now + } + pollCtx, cancel := context.WithCancel(j.ctx) + state.busy = true + state.cancel = cancel + j.inFlight++ + j.startWorker("node-traffic-sync:"+node.Name, func() { + defer func() { + cancel() + j.dispatch.Lock() + state.busy = false + state.cancel = nil + j.inFlight-- + j.dispatch.Unlock() + }() + j.syncOne(pollCtx, mgr, node, doIPSync, pushGlobals, fetchTimeout) }) } - wg.Wait() + j.startPeriodicWorker("node-traffic-publish", &j.publishing, j.publishTraffic) +} + +// Worker admission is serialized with Close. The cron wrapper only sees dispatch. +func (j *NodeTrafficSyncJob) startWorker(name string, work func()) { + j.workers.Add(1) + common.GoRecover(name, func() { + defer j.workers.Done() + work() + }) +} + +func (j *NodeTrafficSyncJob) startPeriodicWorker(name string, busy *bool, work func()) { + if *busy { + return + } + *busy = true + j.startWorker(name, func() { + defer func() { + j.dispatch.Lock() + *busy = false + j.dispatch.Unlock() + }() + work() + }) +} + +func (j *NodeTrafficSyncJob) maintainTraffic(nodes []*model.Node) { + if err := j.inboundService.RetainNodeSnapshotCaches(nodes); err != nil { + logger.Warning("node traffic sync: prune snapshot caches failed:", err) + } + if len(nodes) == 0 { + return + } _, clientsDisabled, err := j.inboundService.AddTraffic(nil, nil) if err != nil { logger.Warning("node traffic sync: depletion check failed:", err) @@ -161,9 +243,9 @@ func (j *NodeTrafficSyncJob) Run() { j.xrayService.ApplyPendingDepletionRestart() j.structural.set() } +} - j.maybePushGlobals(mgr, nodes) - +func (j *NodeTrafficSyncJob) publishTraffic() { // Prune stale local-online entries (no local active emails or inbound tags // to add here — only the local xray poll feeds those) so a stopped local // xray's clients and inbounds still age out between traffic polls. @@ -177,6 +259,8 @@ func (j *NodeTrafficSyncJob) Run() { return } + activeEmails, clientSpeed := j.clientSpeedSnapshot(time.Now()) + // Same snapshot-vs-delta split as the local traffic job: above the // threshold a full snapshot would be dropped by the hub's payload cap, so // send only the rows for clients online on the synced nodes this tick. @@ -235,9 +319,6 @@ func (j *NodeTrafficSyncJob) Run() { // Own source so the clients page adds it to local Xray/TUIC speed instead of // overwriting it; sent even when empty so idle clients clear. - j.clientSpeedMu.Lock() - clientSpeed := j.tickClientSpeed - j.clientSpeedMu.Unlock() websocket.BroadcastTraffic(map[string]any{ "clientTraffics": clientSpeed, "clientTrafficSource": "node", @@ -356,113 +437,132 @@ func diffClientTotals(prev map[string]inboundSample, cur map[string][2]int64, no return next, deltas } -func (j *NodeTrafficSyncJob) recordNodeClientSpeed(nodeID int, snap *runtime.TrafficSnapshot) { +func (j *NodeTrafficSyncJob) recordNodeClientSpeed(ctx context.Context, nodeID int, snap *runtime.TrafficSnapshot, now time.Time) { cur := nodeClientTotals(snap) - now := time.Now().UnixMilli() + j.clientSpeedMu.Lock() + previous := j.prevClientTotals[nodeID] + j.clientSpeedMu.Unlock() + next, deltas := diffClientTotals(previous, cur, now.UnixMilli()) + var emails []string + if snap != nil { + emails = append(emails, snap.OnlineEmails...) + for _, online := range snap.OnlineTree { + emails = append(emails, online...) + } + } j.clientSpeedMu.Lock() defer j.clientSpeedMu.Unlock() + if ctx.Err() != nil { + return + } if j.prevClientTotals == nil { j.prevClientTotals = make(map[int]map[string]inboundSample) } - next, deltas := diffClientTotals(j.prevClientTotals[nodeID], cur, now) j.prevClientTotals[nodeID] = next - j.tickClientSpeed = append(j.tickClientSpeed, deltas...) + if j.clientSamples == nil { + j.clientSamples = make(map[int]nodeClientSample) + } + j.clientSamples[nodeID] = nodeClientSample{at: now, emails: emails, speed: deltas} } -// Offline nodes keep their baselines so the first poll after recovery averages -// over the gap. Caller holds clientSpeedMu. -func (j *NodeTrafficSyncJob) pruneClientSpeedNodes(nodes []*model.Node) { - if len(j.prevClientTotals) == 0 { - return +func (j *NodeTrafficSyncJob) clientSpeedSnapshot(now time.Time) ([]string, []*xray.ClientTraffic) { + j.clientSpeedMu.Lock() + for id, sample := range j.clientSamples { + if now.Sub(sample.at) >= nodeClientSampleTTL { + delete(j.clientSamples, id) + } } + samples := maps.Clone(j.clientSamples) + j.clientSpeedMu.Unlock() + + var activeEmails []string + byEmail := make(map[string]*xray.ClientTraffic) + for _, sample := range samples { + activeEmails = append(activeEmails, sample.emails...) + for _, delta := range sample.speed { + total := byEmail[delta.Email] + if total == nil { + total = &xray.ClientTraffic{Email: delta.Email} + byEmail[delta.Email] = total + } + total.Up += delta.Up + total.Down += delta.Down + } + } + speed := make([]*xray.ClientTraffic, 0, len(byEmail)) + for _, row := range byEmail { + speed = append(speed, row) + } + return activeEmails, speed +} + +// Keep the accounting baseline across temporary outages and presentation expiry. +// Caller holds clientSpeedMu. +func (j *NodeTrafficSyncJob) pruneClientSpeedNodes(nodes []*model.Node) { alive := make(map[int]struct{}, len(nodes)) for _, n := range nodes { if n != nil { alive[n.Id] = struct{}{} + if !n.Enable || n.Status != "online" { + delete(j.clientSamples, n.Id) + } } } for id := range j.prevClientTotals { if _, ok := alive[id]; !ok { delete(j.prevClientTotals, id) + delete(j.clientSamples, id) } } } -// maybePushGlobals broadcasts this panel's aggregated per-client usage to its -// online nodes so each node can display the client's cross-panel total and -// enforce its quota locally (see InboundService.AcceptGlobalTraffic). Scoped -// per node to the clients that node actually hosts, and throttled — the -// aggregates only need to reach nodes on a human timescale, not every poll. -func (j *NodeTrafficSyncJob) maybePushGlobals(mgr *runtime.Manager, nodes []*model.Node) { - j.globalPushMu.Lock() - now := time.Now().Unix() - if now-j.lastGlobalPush < int64(nodeGlobalPushInterval/time.Second) { - j.globalPushMu.Unlock() - return - } - j.lastGlobalPush = now - j.globalPushMu.Unlock() - +func (j *NodeTrafficSyncJob) pushGlobals(pollCtx context.Context, node *model.Node, remote *runtime.Remote) { masterGuid, err := j.settingService.GetPanelGuid() if err != nil || masterGuid == "" { return } - - sem := make(chan struct{}, nodeTrafficSyncConcurrency) - var wg sync.WaitGroup - for _, n := range nodes { - if !n.Enable || n.Status != "online" { - continue - } - remote, err := mgr.RemoteFor(n) - if err != nil { - continue - } - traffics, err := j.inboundService.GetNodeClientTraffics(n.Id) - if err != nil { - logger.Warningf("node traffic sync: load globals for %s failed: %v", n.Name, err) - continue - } - if len(traffics) == 0 { - continue - } - wg.Add(1) - sem <- struct{}{} - n, remote, traffics := n, remote, traffics - common.GoRecover("node-global-push:"+n.Name, func() { - defer wg.Done() - defer func() { <-sem }() - ctx, cancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout) - defer cancel() - if err := remote.PushGlobalClientTraffics(ctx, masterGuid, traffics); err != nil { - // An old-build node without the endpoint answers 404 — not worth a - // warning every cycle. - if strings.Contains(err.Error(), "HTTP 404") { - logger.Debugf("node traffic sync: node %s has no global-traffic endpoint (old build)", n.Name) - } else { - logger.Warningf("node traffic sync: push globals to %s failed: %v", n.Name, err) - } - } - }) + traffics, err := j.inboundService.GetNodeClientTraffics(node.Id) + if err != nil { + logger.Warningf("node traffic sync: load globals for %s failed: %v", node.Name, err) + return + } + if len(traffics) == 0 { + return + } + ctx, cancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout) + defer cancel() + if err := remote.PushGlobalClientTraffics(ctx, masterGuid, traffics); err != nil { + if strings.Contains(err.Error(), "HTTP 404") { + logger.Debugf("node traffic sync: node %s has no global-traffic endpoint (old build)", node.Name) + } else { + logger.Warningf("node traffic sync: push globals to %s failed: %v", node.Name, err) + } } - wg.Wait() } -// syncOne pulls one node's traffic snapshot and merges it. It returns the -// emails online on that node this tick, feeding the delta broadcast above the -// snapshot threshold; nil on any failure path. -func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSync bool, fetchTimeout time.Duration) []string { +func (j *NodeTrafficSyncJob) syncOne(pollCtx context.Context, mgr *runtime.Manager, n *model.Node, doIpSync, pushGlobals bool, fetchTimeout time.Duration) { rt, err := mgr.RemoteFor(n) if err != nil { logger.Warningf("node traffic sync: remote lookup failed for %s: %v", n.Name, err) - return nil + return + } + + if pushGlobals { + defer func() { + if pollCtx.Err() == nil { + j.pushGlobals(pollCtx, n, rt) + } + }() } justPushed := false if n.ConfigDirty { - reconcileCtx, reconcileCancel := context.WithTimeout(context.Background(), nodeReconcileTimeout) + reconcileCtx, reconcileCancel := context.WithTimeout(pollCtx, nodeReconcileTimeout) reconcileErr := j.inboundService.ReconcileNode(reconcileCtx, rt, n) reconcileCancel() + if pollCtx.Err() != nil { + return + } if reconcileErr != nil { // The dirty flag stays set so reconcile retries next tick, but traffic // accounting must keep flowing: one rejected inbound used to starve the @@ -480,13 +580,16 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy } // Before the snapshot, so counters a reset just zeroed are what gets merged. - resetCtx, resetCancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout) + resetCtx, resetCancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout) if resetErr := j.inboundService.DeliverNodeResets(resetCtx, n.Id, rt); resetErr != nil { logger.Warningf("node traffic sync: reset delivery to %s failed, retrying next tick: %v", n.Name, resetErr) } resetCancel() + if pollCtx.Err() != nil { + return + } - ctx, cancel := context.WithTimeout(context.Background(), fetchTimeout) + ctx, cancel := context.WithTimeout(pollCtx, fetchTimeout) defer cancel() fetchStarted := time.Now() @@ -495,17 +598,21 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy if err != nil { logger.Warningf("node traffic sync: fetch from %s failed after %dms: %v", n.Name, prepareStarted.Sub(fetchStarted).Milliseconds(), err) j.inboundService.ClearNodeOnlineClients(n.Id) - return nil + return } snap.ManagedAliases = rt.AdoptedInboundAliases() syncCanAdopt := syncCanAdoptInbounds(n, snap.ManagedAliases) service.FilterNodeSnapshot(n, snap) - _, _, dirty, _, _ := j.nodeService.NodeSyncState(n.Id) + enabled, status, dirty, _, err := j.nodeService.NodeSyncState(n.Id) + if err != nil || !enabled || status != "online" { + j.inboundService.ClearNodeOnlineClients(n.Id) + return + } if !dirty { if pending, checkErr := j.inboundService.SnapshotHasUnadoptedInbounds(n.Id, snap); checkErr != nil { logger.Warningf("node traffic sync: unadopted-inbound check for %s failed: %v", n.Name, checkErr) } else if pending { - hostCtx, hostCancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout) + hostCtx, hostCancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout) groups, hgErr := rt.FetchHostGroups(hostCtx) hostCancel() if hgErr != nil { @@ -516,35 +623,34 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy } } mergeStarted := time.Now() - changed, err := j.inboundService.SetRemoteTraffic(n.Id, snap, dirty, justPushed) + changed, err := j.inboundService.MergeOnlineNodeTraffic(pollCtx, n.Id, snap, dirty, justPushed) logger.Debugf("node traffic sync timing: node_id=%d compact=%t fetch_ms=%d prepare_ms=%d merge_ms=%d", n.Id, snap.StructuralRevision != "", prepareStarted.Sub(fetchStarted).Milliseconds(), mergeStarted.Sub(prepareStarted).Milliseconds(), time.Since(mergeStarted).Milliseconds()) if err != nil { logger.Warningf("node traffic sync: merge for %s failed: %v", n.Name, err) - return nil + return } if changed { j.structural.set() } - j.recordNodeClientSpeed(n.Id, snap) + enabled, status, _, _, err = j.nodeService.NodeSyncState(n.Id) + if err != nil || !enabled || status != "online" || pollCtx.Err() != nil { + j.inboundService.ClearNodeOnlineClients(n.Id) + return + } + j.recordNodeClientSpeed(pollCtx, n.Id, snap, time.Now()) if !dirty && n.InboundsAdoptedAt == 0 && syncCanAdopt { if markErr := j.nodeService.MarkNodeInboundsAdopted(n.Id); markErr != nil { logger.Warningf("node traffic sync: mark inbounds adopted for %s failed: %v", n.Name, markErr) } } - active := make([]string, 0, len(snap.OnlineEmails)) - active = append(active, snap.OnlineEmails...) - for _, emails := range snap.OnlineTree { - active = append(active, emails...) - } - if !doIpSync { - return active + return } - ipCtx, ipCancel := context.WithTimeout(context.Background(), nodeClientIpSyncTimeout) + ipCtx, ipCancel := context.WithTimeout(pollCtx, nodeClientIpSyncTimeout) defer ipCancel() nodeIps, err := rt.FetchAllClientIps(ipCtx) @@ -559,7 +665,7 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy masterIps, err := j.inboundService.GetNodeInboundClientIps(n.Id) if err != nil { logger.Warningf("node traffic sync: load client ips for push to %s failed: %v", n.Name, err) - return active + return } if len(masterIps) > 0 { if err := rt.PushAllClientIps(ipCtx, masterIps); err != nil { @@ -587,7 +693,6 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy } } } - return active } // Whether this sync can perform the "first clean adoption" that diff --git a/internal/web/job/node_traffic_sync_online_prune_test.go b/internal/web/job/node_traffic_sync_online_prune_test.go index 29e706627..5d1e111dd 100644 --- a/internal/web/job/node_traffic_sync_online_prune_test.go +++ b/internal/web/job/node_traffic_sync_online_prune_test.go @@ -35,7 +35,10 @@ func TestNodeTrafficSyncDropsOnlineClientsOfUnsyncedNodes(t *testing.T) { process.SetNodeOnlineTree(disabled.Id, map[string][]string{"g-disabled": {"a@x"}}) process.SetNodeOnlineTree(disabled.Id+100, map[string][]string{"g-deleted": {"b@x"}}) - NewNodeTrafficSyncJob().Run() + job := NewNodeTrafficSyncJob() + job.Run() + job.workers.Wait() + job.Close() if got := process.GetMergedNodeTrees(); len(got) != 0 { t.Fatalf("online sets after a sync tick = %v, want none for a disabled or deleted node", got) diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index 44c4e9870..a54cb27d5 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -226,18 +226,20 @@ func TestMasterNodeContract(t *testing.T) { } }}, {"AddClient attaches one client", []string{"AddClient"}, func() error { - return master.AddClient(ctx, masterInbound("updated", false), model.Client{ + _, err := master.AddClient(ctx, masterInbound("updated", false), model.Client{ Email: "c3", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000003", SubID: "s-c3", Enable: true, }) + return err }, func(t *testing.T) { if got := nodeEmails(t); !strings.Contains(strings.Join(got, ","), "c3") { t.Fatalf("node clients = %v, want c3 among them", got) } }}, {"UpdateUser changes the client's limits", []string{"UpdateUser"}, func() error { - return master.UpdateUser(ctx, masterInbound("updated", false), "c3", model.Client{ + _, err := master.UpdateUser(ctx, masterInbound("updated", false), "c3", model.Client{ Email: "c3", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000003", SubID: "s-c3", Enable: true, TotalGB: 5 << 30, }) + return err }, func(t *testing.T) { var ct xray.ClientTraffic database.GetDB().Where("email = ?", "c3").First(&ct) @@ -357,14 +359,16 @@ func TestMasterNodeContract(t *testing.T) { } }, nil}, {"DeleteUser detaches the client from the inbound", []string{"DeleteUser"}, func() error { - return master.DeleteUser(ctx, masterInbound("updated", false), "c3") + _, err := master.DeleteUser(ctx, masterInbound("updated", false), "c3") + return err }, func(t *testing.T) { if got := nodeEmails(t); strings.Contains(strings.Join(got, ","), "c3") { t.Fatalf("node clients = %v, want c3 gone", got) } }}, {"DeleteClient removes the client everywhere", []string{"DeleteClient"}, func() error { - return master.DeleteClient(ctx, "c2") + _, err := master.DeleteClient(ctx, "c2") + return err }, func(t *testing.T) { if got := nodeEmails(t); strings.Contains(strings.Join(got, ","), "c2") { t.Fatalf("node clients = %v, want c2 gone", got) diff --git a/internal/web/runtime/local.go b/internal/web/runtime/local.go index 1ef764945..72d498113 100644 --- a/internal/web/runtime/local.go +++ b/internal/web/runtime/local.go @@ -363,9 +363,9 @@ func (l *Local) RemoveUser(_ context.Context, ib *model.Inbound, email string) e }) } -func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error { +func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) (ClientApplyResult, error) { if !client.Enable { - return nil + return ClientApplyResult{}, nil } user := map[string]any{ "email": client.Email, @@ -380,34 +380,34 @@ func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.C "keepAlive": wgKeepAlive(client.KeepAliveSeconds()), "wireguardDevices": client.WireguardDevices, } - return l.AddUser(ctx, ib, user) + return ClientApplyResult{}, l.AddUser(ctx, ib, user) } -func (l *Local) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error { +func (l *Local) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) { if email == "" { - return nil + return ClientApplyResult{}, nil } if err := l.RemoveUser(ctx, ib, email); err != nil { if strings.Contains(err.Error(), "not found") { - return nil + return ClientApplyResult{}, nil } - return err + return ClientApplyResult{}, err } - return nil + return ClientApplyResult{}, nil } -func (l *Local) DeleteClient(context.Context, string) error { - return nil +func (l *Local) DeleteClient(context.Context, string) (ClientApplyResult, error) { + return ClientApplyResult{}, nil } -func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error { +func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) (ClientApplyResult, error) { if oldEmail != "" { if err := l.RemoveUser(ctx, ib, oldEmail); err != nil && !strings.Contains(err.Error(), "not found") { - return err + return ClientApplyResult{}, err } } if !payload.Enable { - return nil + return ClientApplyResult{}, nil } user := map[string]any{ "email": payload.Email, @@ -422,7 +422,7 @@ func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail stri "keepAlive": wgKeepAlive(payload.KeepAliveSeconds()), "wireguardDevices": payload.WireguardDevices, } - return l.AddUser(ctx, ib, user) + return ClientApplyResult{}, l.AddUser(ctx, ib, user) } func wgKeepAlive(seconds int) string { diff --git a/internal/web/runtime/local_wireguard_devices_test.go b/internal/web/runtime/local_wireguard_devices_test.go index 95258cbc3..74dfce190 100644 --- a/internal/web/runtime/local_wireguard_devices_test.go +++ b/internal/web/runtime/local_wireguard_devices_test.go @@ -92,7 +92,7 @@ func TestLocalWireguardAddsEveryEnabledDevice(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { local, core := newWireguardDeviceRuntime(t) - if err := local.AddClient(context.Background(), &model.Inbound{Tag: "wg", Protocol: model.WireGuard}, wireguardDeviceClient(test.keepAlive)); err != nil { + if _, err := local.AddClient(context.Background(), &model.Inbound{Tag: "wg", Protocol: model.WireGuard}, wireguardDeviceClient(test.keepAlive)); err != nil { t.Fatal(err) } assertWireguardDevicePeers(t, core, test.want) diff --git a/internal/web/runtime/reconcile_skip_test.go b/internal/web/runtime/reconcile_skip_test.go index 1d7ba96f0..8e225320c 100644 --- a/internal/web/runtime/reconcile_skip_test.go +++ b/internal/web/runtime/reconcile_skip_test.go @@ -81,7 +81,7 @@ func TestDeleteClientInvalidatesOnlyInboundsStampedWithThatClient(t *testing.T) unaffected := &model.Inbound{Tag: "in-2", Protocol: model.VLESS, Settings: `{"clients":[{"email":"keep@example.test"}]}`} r.AdoptInboundAlias(affected, RemoteInboundOption{Tag: "adopted-1", Id: 1}) r.AdoptInboundAlias(unaffected, RemoteInboundOption{Tag: "adopted-2", Id: 2}) - if err := r.DeleteClient(t.Context(), "delete@example.test"); (err != nil) != response.failed { + if _, err := r.DeleteClient(t.Context(), "delete@example.test"); (err != nil) != response.failed { t.Fatalf("unexpected delete result: %v", err) } if pushed, err := r.ReconcileInbound(t.Context(), unaffected, true); err != nil || pushed { @@ -126,19 +126,19 @@ func newCountingNodeServer(t *testing.T, clientsResp string) (*httptest.Server, func perClientMutationCases(client model.Client) []struct { name string - run func(*Remote, *model.Inbound) error + run func(*Remote, *model.Inbound) (ClientApplyResult, error) } { return []struct { name string - run func(*Remote, *model.Inbound) error + run func(*Remote, *model.Inbound) (ClientApplyResult, error) }{ - {"add", func(r *Remote, ib *model.Inbound) error { + {"add", func(r *Remote, ib *model.Inbound) (ClientApplyResult, error) { return r.AddClient(context.Background(), ib, client) }}, - {"delete", func(r *Remote, ib *model.Inbound) error { + {"delete", func(r *Remote, ib *model.Inbound) (ClientApplyResult, error) { return r.DeleteUser(context.Background(), ib, client.Email) }}, - {"update", func(r *Remote, ib *model.Inbound) error { + {"update", func(r *Remote, ib *model.Inbound) (ClientApplyResult, error) { return r.UpdateUser(context.Background(), ib, client.Email, client) }}, } @@ -159,8 +159,8 @@ func TestPerClientMutationsAloneDoNotSeedReconcileFingerprint(t *testing.T) { ib := &model.Inbound{Tag: "in-" + tt.name, Protocol: model.VLESS, Port: 443, Settings: `{"clients":[{"id":"11111111-1111-1111-1111-111111111111","email":"a@x","subId":"s","enable":true}]}`} r.cacheSet(ib.Tag, 7) - if err := tt.run(r, ib); err != nil { - t.Fatalf("%s client mutation: %v", tt.name, err) + if result, err := tt.run(r, ib); err != nil || result.DownstreamPending { + t.Fatalf("%s client mutation: result=%+v err=%v, want legacy ack with no pending flag", tt.name, result, err) } if got := counts.clientMutations.Load(); got != 1 { t.Fatalf("%s client mutation requests=%d, want 1", tt.name, got) @@ -201,7 +201,7 @@ func TestAdvancePushedInboundEnablesReconcileSkip(t *testing.T) { r.cacheSet(ib.Tag, 7) r.recordPushedInbound(prevIb) - if err := tt.run(r, ib); err != nil { + if _, err := tt.run(r, ib); err != nil { t.Fatalf("%s client mutation: %v", tt.name, err) } r.AdvancePushedInbound(prevIb, ib) @@ -229,7 +229,7 @@ func TestAdvancePushedInboundRequiresMatchingPreviousFingerprint(t *testing.T) { r.cacheSet(ib.Tag, 7) r.recordPushedInbound(staleIb) - if err := r.UpdateUser(context.Background(), ib, "a@x", model.Client{Email: "a@x"}); err != nil { + if _, err := r.UpdateUser(context.Background(), ib, "a@x", model.Client{Email: "a@x"}); err != nil { t.Fatalf("client mutation: %v", err) } r.AdvancePushedInbound(prevIb, ib) @@ -256,7 +256,7 @@ func TestAdoptedSerializationChainKeepsReconcileSkip(t *testing.T) { r.recordPushedInbound(pushForm) r.RecordAdoptedInbound(adoptedForm) - if err := r.UpdateUser(context.Background(), edited, "a@x", model.Client{Email: "a@x"}); err != nil { + if _, err := r.UpdateUser(context.Background(), edited, "a@x", model.Client{Email: "a@x"}); err != nil { t.Fatalf("client mutation: %v", err) } r.AdvancePushedInbound(adoptedForm, edited) @@ -275,7 +275,7 @@ func TestDeleteUserNotFoundHandling(t *testing.T) { ib := &model.Inbound{Tag: "in-delete-missing", Protocol: model.VLESS, Port: 443, Settings: `{"clients":[]}`} r.cacheSet(ib.Tag, 7) - if err := r.DeleteUser(context.Background(), ib, "missing@x"); err != nil { + if _, err := r.DeleteUser(context.Background(), ib, "missing@x"); err != nil { t.Fatalf("DeleteUser missing client: %v", err) } if pushed, err := r.ReconcileInbound(context.Background(), ib, true); err != nil || !pushed { @@ -300,7 +300,7 @@ func TestDeleteUserNotFoundHandling(t *testing.T) { ib := &model.Inbound{Tag: "in-delete-404", Protocol: model.VLESS, Port: 443, Settings: `{"clients":[]}`} r.cacheSet(ib.Tag, 7) - err := r.DeleteUser(context.Background(), ib, "missing@x") + _, err := r.DeleteUser(context.Background(), ib, "missing@x") if err == nil || !strings.Contains(err.Error(), "HTTP 404") { t.Fatalf("DeleteUser against old node = %v, want HTTP 404 error", err) } diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index 8a2288868..8448cabc1 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -797,80 +797,87 @@ func (r *Remote) RemoveUser(ctx context.Context, ib *model.Inbound, _ string) er return r.UpdateInbound(ctx, ib, ib) } -func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error { +func remoteClientApplyResult(env *envelope, err error) (ClientApplyResult, error) { + if err != nil || env == nil { + return ClientApplyResult{}, err + } + var result struct { + NodePending bool `json:"nodePending"` + } + pending := json.Unmarshal(env.Obj, &result) == nil && result.NodePending + return ClientApplyResult{DownstreamPending: pending}, nil +} + +func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) (ClientApplyResult, error) { id, err := r.resolveRemoteID(ctx, ib.Tag) if err != nil { - return fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err) + return ClientApplyResult{}, fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err) } payload := map[string]any{ "client": client, "inboundIds": []int{id}, } - if _, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload); err != nil { - return err - } - return nil + env, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload) + return remoteClientApplyResult(env, err) } -func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error { +func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) { if email == "" { - return nil + return ClientApplyResult{}, nil } id, err := r.resolveRemoteID(ctx, ib.Tag) if err != nil { // Can't confirm the delete reached the node — surface it so the caller // marks the node dirty and a reconcile converges, instead of silently // dropping the delete and letting the next snapshot resurrect the client. - return fmt.Errorf("remote DeleteUser: resolve tag %q: %w", ib.Tag, err) + return ClientApplyResult{}, fmt.Errorf("remote DeleteUser: resolve tag %q: %w", ib.Tag, err) } body := map[string]any{"inboundIds": []int{id}} - _, err = r.do(ctx, http.MethodPost, + env, err := r.do(ctx, http.MethodPost, "panel/api/clients/"+url.PathEscape(email)+"/detach", body) if err == nil { - return nil + return remoteClientApplyResult(env, nil) } var apiErr *remoteAPIError if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.msg), "not found") { - return nil + return ClientApplyResult{}, nil } - return err + return ClientApplyResult{}, err } -func (r *Remote) DeleteClient(ctx context.Context, email string) error { +func (r *Remote) DeleteClient(ctx context.Context, email string) (ClientApplyResult, error) { if email == "" { - return nil + return ClientApplyResult{}, nil } - _, err := r.do(ctx, http.MethodPost, + env, err := r.do(ctx, http.MethodPost, "panel/api/clients/del/"+url.PathEscape(email), nil) r.forgetPushedClient(email) if err == nil { - return nil + return remoteClientApplyResult(env, nil) } var apiErr *remoteAPIError if errors.As(err, &apiErr) { absent := fmt.Sprintf("client %q not found in any inbound or client record", email) message := strings.TrimSpace(apiErr.msg) if message == absent || strings.HasSuffix(message, " ("+absent+")") { - return nil + return ClientApplyResult{}, nil } } - return err + return ClientApplyResult{}, err } -func (r *Remote) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error { +func (r *Remote) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) (ClientApplyResult, error) { if oldEmail == "" { oldEmail = payload.Email } id, err := r.resolveRemoteID(ctx, ib.Tag) if err != nil { - return err + return ClientApplyResult{}, err } path := "panel/api/clients/update/" + url.PathEscape(oldEmail) + "?inboundIds=" + strconv.Itoa(id) - if _, err := r.do(ctx, http.MethodPost, path, payload); err != nil { - return err - } - return nil + env, err := r.do(ctx, http.MethodPost, path, payload) + return remoteClientApplyResult(env, err) } func (r *Remote) RestartXray(ctx context.Context) error { diff --git a/internal/web/runtime/runtime.go b/internal/web/runtime/runtime.go index d0540055c..4d871c414 100644 --- a/internal/web/runtime/runtime.go +++ b/internal/web/runtime/runtime.go @@ -6,6 +6,11 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database/model" ) +// ClientApplyResult describes an acknowledged mutation. The direct peer retries its own downstream nodes. +type ClientApplyResult struct { + DownstreamPending bool +} + type Runtime interface { Name() string @@ -19,16 +24,16 @@ type Runtime interface { // Per-client operations that route through the node's clients API on // Remote (instead of pushing the whole inbound) so the node applies // per-user xray API calls without a DelInbound+AddInbound cycle. - UpdateUser(ctx context.Context, ib *model.Inbound, email string, payload model.Client) error - DeleteUser(ctx context.Context, ib *model.Inbound, email string) error - AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error + UpdateUser(ctx context.Context, ib *model.Inbound, email string, payload model.Client) (ClientApplyResult, error) + DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) + AddClient(ctx context.Context, ib *model.Inbound, client model.Client) (ClientApplyResult, error) // DeleteClient removes the client identified by email entirely from the // runtime's own store: on Remote it hits the node's full-delete endpoint // (record, attachments, traffic), unlike DeleteUser which only detaches // from one inbound and leaves the node's client record behind. Local has // no client store of its own, so it is a no-op there. - DeleteClient(ctx context.Context, email string) error + DeleteClient(ctx context.Context, email string) (ClientApplyResult, error) RestartXray(ctx context.Context) error diff --git a/internal/web/service/client.go b/internal/web/service/client.go index 7429f4bee..4fd2625e1 100644 --- a/internal/web/service/client.go +++ b/internal/web/service/client.go @@ -57,7 +57,9 @@ func (c ClientWithAttachments) MarshalJSON() ([]byte, error) { return out, nil } -type ClientService struct{} +type ClientService struct { + nodeApplies *clientNodeApplyReport +} // ErrClientNotInInbound is returned (wrapped) when a client cannot be located // in an inbound's settings during deletion. Deletion treats it as non-fatal so diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index 5bb9050eb..371a1cd88 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -21,6 +21,7 @@ import ( // BulkAttachResult reports the outcome of a bulk attach across target inbounds. type BulkAttachResult struct { + ClientNodeApplyResponse Attached []string `json:"attached"` Skipped []string `json:"skipped"` Errors []string `json:"errors"` @@ -145,7 +146,7 @@ func (s *ClientService) bulkAttachRecords(inboundSvc *InboundService, records [] attachClients = append(attachClients, clientsToAdd) } - attachResults, attachPanics := fanoutInboundResults(attachIds, addFanoutLimit(attachAnyTunnel), func(i int) inboundApplyOutcome { + attachResults, attachPanics := fanoutClientInboundResults(attachIds, addFanoutLimit(attachAnyTunnel), func(i int) inboundApplyOutcome { nr, err := s.AddInboundClient(inboundSvc, &model.Inbound{Id: attachIds[i], Settings: attachPayloads[i]}) return inboundApplyOutcome{needRestart: nr, err: err} }) @@ -174,6 +175,7 @@ func (s *ClientService) bulkAttachRecords(inboundSvc *InboundService, records [] // BulkDetachResult reports the outcome of a bulk detach across target inbounds. type BulkDetachResult struct { + ClientNodeApplyResponse Detached []string `json:"detached"` Skipped []string `json:"skipped"` Errors []string `json:"errors"` @@ -255,7 +257,7 @@ func (s *ClientService) BulkDetach(inboundSvc *InboundService, emails []string, detachIds = append(detachIds, ibId) detachRecs = append(detachRecs, recs) } - detachResults, detachPanics := fanoutInboundResults(detachIds, inboundFanoutConcurrency, func(i int) inboundApplyOutcome { + detachResults, detachPanics := fanoutClientInboundResults(detachIds, inboundFanoutConcurrency, func(i int) inboundApplyOutcome { nr, err := s.delInboundClients(inboundSvc, detachIds[i], detachRecs[i], true) return inboundApplyOutcome{needRestart: nr, err: err} }) @@ -297,6 +299,7 @@ type inboundApplyOutcome struct { // BulkAdjustResult reports changed clients and per-client skip reasons. // ExternalLinks contains row counts only for append requests. type BulkAdjustResult struct { + ClientNodeApplyResponse Adjusted int `json:"adjusted" example:"2"` Skipped []BulkAdjustReport `json:"skipped,omitempty" example:"[]"` ExternalLinks *BulkExternalLinksResult `json:"externalLinks,omitempty"` @@ -480,7 +483,7 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, adTagIneligible := map[string]bool{} execFailed := map[string]bool{} adjustIds := sortedInboundIds(emailsByInbound) - adjustResults, adjustPanics := fanoutInboundResults(adjustIds, inboundFanoutConcurrency, func(i int) bulkInboundAdjustResult { + adjustResults, adjustPanics := fanoutClientInboundResults(adjustIds, inboundFanoutConcurrency, func(i int) bulkInboundAdjustResult { return s.bulkAdjustInboundClients(inboundSvc, adjustIds[i], emailsByInbound[adjustIds[i]], plan, flow, adTag) }) for i, ibRes := range adjustResults { @@ -696,6 +699,7 @@ func (s *ClientService) bulkAdjustInboundClients( var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &err) for _, e := range emails { res.perEmailSkipped[e] = err.Error() } @@ -832,6 +836,7 @@ func (s *ClientService) bulkAdjustInboundClients( return nil }) if txErr != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &txErr) for email := range foundEmails { if _, skip := res.perEmailSkipped[email]; !skip { res.perEmailSkipped[email] = txErr.Error() @@ -846,7 +851,7 @@ func (s *ClientService) bulkAdjustInboundClients( if perr != nil { logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr) } else if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for email := range foundEmails { entry := plan[email] updated := *entry.record.ToClient() @@ -860,15 +865,18 @@ func (s *ClientService) bulkAdjustInboundClients( updated.AdTag = wantAdTag } updated.UpdatedAt = nowMs - err := rt.UpdateUser(ctx, oldInbound, email, updated) - if err != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err) + if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, email, updated)) { return false } } return true }) } + if perr != nil || !push { + s.recordClientNodeDeferred(oldInbound.NodeID) + } + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } } @@ -878,6 +886,7 @@ func (s *ClientService) bulkAdjustInboundClients( // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email // skip reasons when an email could not be processed. type BulkDeleteResult struct { + ClientNodeApplyResponse Deleted int `json:"deleted"` Skipped []BulkDeleteReport `json:"skipped,omitempty"` } @@ -951,7 +960,7 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, needRestart := false delIds := sortedInboundIds(emailsByInbound) - delResults, delPanics := fanoutInboundResults(delIds, inboundFanoutConcurrency, func(i int) bulkInboundDeleteResult { + delResults, delPanics := fanoutClientInboundResults(delIds, inboundFanoutConcurrency, func(i int) bulkInboundDeleteResult { return s.bulkDelInboundClients(inboundSvc, delIds[i], emailsByInbound[delIds[i]], recordsByEmail, keepTraffic) }) for i, ibResult := range delResults { @@ -1070,6 +1079,7 @@ func (s *ClientService) bulkDelInboundClients( var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &err) for _, e := range emails { res.perEmailSkipped[e] = err.Error() } @@ -1215,6 +1225,7 @@ func (s *ClientService) bulkDelInboundClients( return err }) if txErr != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &txErr) for email := range wantedEmails { if _, skip := res.perEmailSkipped[email]; !skip { res.perEmailSkipped[email] = txErr.Error() @@ -1245,22 +1256,28 @@ func (s *ClientService) bulkDelInboundClients( } } else { if len(pending) == 0 || len(pending) > nodeBulkPushThreshold { + s.recordClientNodeDeferred(oldInbound.NodeID) return res } rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { logger.Warning("BulkDelete: node runtime lookup after commit failed:", perr) } else if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + complete := true for _, row := range pending { - if err := applyNodeClientDelete(ctx, rt, row); err != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err) + result, attempted, err := applyNodeClientDelete(ctx, rt, row) + if !batch.acknowledge(result, err) { return false } + complete = complete && attempted } - return true + return complete }) } + if perr != nil || !push { + s.recordClientNodeDeferred(oldInbound.NodeID) + } } return res @@ -1268,6 +1285,7 @@ func (s *ClientService) bulkDelInboundClients( // BulkCreateResult mirrors BulkAdjustResult for the create flow. type BulkCreateResult struct { + ClientNodeApplyResponse Created int `json:"created"` Skipped []BulkCreateReport `json:"skipped,omitempty"` } @@ -1480,7 +1498,7 @@ func (s *ClientService) bulkCreate(inboundSvc *InboundService, payloads []Client } needRestart := false - createResults, createPanics := fanoutInboundResults(inboundOrder, addFanoutLimit(createAnyTunnel), func(i int) inboundApplyOutcome { + createResults, createPanics := fanoutClientInboundResults(inboundOrder, addFanoutLimit(createAnyTunnel), func(i int) inboundApplyOutcome { ibId := inboundOrder[i] payload, e := json.Marshal(map[string][]model.Client{"clients": byInbound[ibId]}) if e != nil { @@ -1566,6 +1584,7 @@ func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, erro } type BulkSetEnableResult struct { + ClientNodeApplyResponse Changed int `json:"changed"` Skipped []BulkSetEnableReport `json:"skipped,omitempty"` } @@ -1626,7 +1645,7 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin needRestart := false enableIds := sortedInboundIds(emailsByInbound) - enableResults, enablePanics := fanoutInboundResults(enableIds, inboundFanoutConcurrency, func(i int) bulkSetEnableInboundResult { + enableResults, enablePanics := fanoutClientInboundResults(enableIds, inboundFanoutConcurrency, func(i int) bulkSetEnableInboundResult { return s.bulkSetEnableInboundClients(inboundSvc, enableIds[i], emailsByInbound[enableIds[i]], enable) }) for i, ibRes := range enableResults { @@ -1725,6 +1744,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &err) for _, e := range emails { res.perEmailSkipped[e] = err.Error() } @@ -1826,6 +1846,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, return nil }) if txErr != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &txErr) for _, ch := range changed { res.perEmailSkipped[ch.email] = txErr.Error() } @@ -1858,19 +1879,19 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, } } } else if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for _, ch := range changed { updated := ch.client updated.UpdatedAt = nowMs - err := rt.UpdateUser(ctx, oldInbound, ch.email, updated) - if err != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err) + if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, ch.email, updated)) { return false } } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) return true }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } return res diff --git a/internal/web/service/client_create_fanout_test.go b/internal/web/service/client_create_fanout_test.go index 1d7dc57bc..4b8ada29c 100644 --- a/internal/web/service/client_create_fanout_test.go +++ b/internal/web/service/client_create_fanout_test.go @@ -110,7 +110,7 @@ func (b *barrierNodeRuntime) free() { } } -func (b *barrierNodeRuntime) AddClient(ctx context.Context, ib *model.Inbound, c model.Client) error { +func (b *barrierNodeRuntime) AddClient(ctx context.Context, ib *model.Inbound, c model.Client) (runtime.ClientApplyResult, error) { n := b.inFlight.Add(1) for { peak := b.maxPar.Load() diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 3646889e0..687f45f01 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -315,7 +315,7 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate if mErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, mErr) } - adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)}) + adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID}) } needRestart, fanoutErr := s.fanoutInboundClientAdds(inboundSvc, adds) if fanoutErr != nil { @@ -340,8 +340,9 @@ const inboundFanoutConcurrency = 4 // inboundApply is one inbound's share of a client op, ready to run. type inboundApply struct { - id int - run func() (bool, error) + id int + nodeID *int + run func() (bool, error) } // fanoutInboundApplies runs the applies with the node pushes overlapping, so a @@ -350,8 +351,9 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) { var needRestart atomic.Bool errs := make([]error, len(applies)) sem := make(chan struct{}, inboundFanoutConcurrency) + indices := nodeFairOrder(len(applies), func(i int) *int { return applies[i].nodeID }) var wg sync.WaitGroup - for i := range applies { + for _, i := range indices { wg.Add(1) sem <- struct{}{} go func() { @@ -386,18 +388,57 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) { func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) { applies := make([]inboundApply, 0, len(adds)) for _, add := range adds { - applies = append(applies, inboundApply{id: add.Id, run: func() (bool, error) { + applies = append(applies, inboundApply{id: add.Id, nodeID: add.NodeID, run: func() (bool, error) { return s.AddInboundClient(inboundSvc, add) }}) } return fanoutInboundApplies(applies) } +// Give each node a turn before admitting a second inbound from any node. +func nodeFairOrder(count int, nodeAt func(int) *int) []int { + indices := make([]int, count) + order := make([]int, count) + seen := make(map[int]int) + for i := range indices { + indices[i] = i + nodeID := 0 + if id := nodeAt(i); id != nil { + nodeID = *id + } + order[i] = seen[nodeID] + seen[nodeID]++ + } + slices.SortStableFunc(indices, func(i, k int) int { return order[i] - order[k] }) + return indices +} + +func fanoutClientInboundResults[T any](inboundIDs []int, limit int, run func(int) T) ([]T, []error) { + if limit < 2 || len(inboundIDs) <= limit { + return fanoutInboundResults(inboundIDs, limit, run) + } + db := database.GetDB() + nodes := make(map[int]*int, len(inboundIDs)) + for _, batch := range chunkInts(inboundIDs, sqlInChunk) { + var rows []model.Inbound + if err := db.Select("id", "node_id").Where("id IN ?", batch).Find(&rows).Error; err != nil { + logger.Warning("Cannot order bulk client applies across nodes:", err) + return fanoutInboundResults(inboundIDs, limit, run) + } + for _, row := range rows { + nodes[row.Id] = row.NodeID + } + } + return fanoutInboundResults(inboundIDs, limit, run, nodeFairOrder(len(inboundIDs), func(i int) *int { + return nodes[inboundIDs[i]] + })...) +} + // fanoutInboundResults runs one job per inbound with the node pushes // overlapping, so a bulk op costs one RPC round-trip instead of one per node. // limit is the caller's own cap: an op that allocates tunnel addresses passes 1, // because allocation reads a cross-inbound used-set before it writes. -func fanoutInboundResults[T any](inboundIds []int, limit int, run func(i int) T) ([]T, []error) { +func fanoutInboundResults[T any](inboundIds []int, limit int, run func(i int) T, order ...int) ([]T, []error) { if limit < 1 { limit = 1 } @@ -405,7 +446,11 @@ func fanoutInboundResults[T any](inboundIds []int, limit int, run func(i int) T) errs := make([]error, len(inboundIds)) sem := make(chan struct{}, limit) var wg sync.WaitGroup - for i := range inboundIds { + for pos := range inboundIds { + i := pos + if len(order) != 0 { + i = order[pos] + } wg.Add(1) sem <- struct{}{} go func() { @@ -895,7 +940,7 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model return false, mErr } data := &model.Inbound{Id: ibId, Settings: string(settingsPayload)} - applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) { + applies = append(applies, inboundApply{id: ibId, nodeID: inbound.NodeID, run: func() (bool, error) { return s.UpdateInboundClient(inboundSvc, data, existing.Email) }}) } @@ -1059,7 +1104,8 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b applies := make([]inboundApply, 0, len(inboundIds)) var delErrs []error for _, ibId := range inboundIds { - if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil { + inbound, getErr := inboundSvc.GetInbound(ibId) + if getErr != nil { if errors.Is(getErr, gorm.ErrRecordNotFound) { continue } @@ -1074,7 +1120,7 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b if existing.Email == "" { continue } - applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) { + applies = append(applies, inboundApply{id: ibId, nodeID: inbound.NodeID, run: func() (bool, error) { nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, keepTraffic, true) // The client is already absent from this inbound (data drift or a // retried delete). Skip it — deletion stays idempotent. @@ -1271,7 +1317,7 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds [] if mErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, mErr) } - adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)}) + adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID}) } return s.fanoutInboundClientAdds(inboundSvc, adds) } @@ -1396,14 +1442,15 @@ func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds [] if _, attached := have[ibId]; !attached { continue } - if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil { + inbound, getErr := inboundSvc.GetInbound(ibId) + if getErr != nil { return false, getErr } // Detach by email — the client's stable identity (see Delete). if existing.Email == "" { continue } - applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) { + applies = append(applies, inboundApply{id: ibId, nodeID: inbound.NodeID, run: func() (bool, error) { nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false) if errors.Is(delErr, ErrClientNotInInbound) { return nr, nil diff --git a/internal/web/service/client_edit_node_dirty_test.go b/internal/web/service/client_edit_node_dirty_test.go index c42a95f8f..26133182d 100644 --- a/internal/web/service/client_edit_node_dirty_test.go +++ b/internal/web/service/client_edit_node_dirty_test.go @@ -7,6 +7,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) // dirtyProbeRuntime reads a node's config_dirty flag at the moment an inbound @@ -18,7 +19,7 @@ type dirtyProbeRuntime struct { probed atomic.Bool } -func (d *dirtyProbeRuntime) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, c model.Client) error { +func (d *dirtyProbeRuntime) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, c model.Client) (runtime.ClientApplyResult, error) { var node model.Node if err := database.GetDB().Where("id = ?", d.watch).First(&node).Error; err == nil { d.sawSet.Store(node.ConfigDirty) diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 2ee15e988..f805aa233 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -135,7 +135,7 @@ func advancePushedInbound(rt runtime.Runtime, prevSettings, pushedSettings strin // whole batch, instead of repeating the full per-client cycle. It mirrors the // semantics of DelInboundClientByEmail for each removed client. needRestart is // the OR across all removals. -func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (bool, error) { +func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (restartNeeded bool, saveErr error) { defer InvalidateSubData() if len(recs) == 0 { return false, nil @@ -148,6 +148,7 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId logger.Error("Load Old Data Error") return false, err } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { @@ -285,23 +286,25 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if oldInbound.NodeID != nil { rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { - return needRestart, perr + logger.Warning("Node client detach deferred:", perr) + s.recordClientNodeDeferred(oldInbound.NodeID) + return needRestart, nil } if push && len(targets) <= nodeBulkPushThreshold { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for _, target := range targets { if target.email == "" { continue } - err := rt.DeleteUser(ctx, oldInbound, target.email) - if err != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err) + if !batch.acknowledge(rt.DeleteUser(ctx, oldInbound, target.email)) { return false } } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) return true }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } return needRestart, nil } @@ -392,7 +395,7 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c return "", nil } -func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) { +func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(data.Id) defer mutation.close() @@ -449,6 +452,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model if err != nil { return false, err } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err } @@ -707,15 +711,13 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } } else if push && len(clients) <= nodeBulkPushThreshold { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for _, client := range clients { // Older nodes coerce enable=true. Reconcile the rest of this batch. if !client.Enable { return false } - err1 := rt.AddClient(ctx, oldInbound, client) - if err1 != nil { - logger.Warning("Error in adding client on", rt.Name(), ":", err1) + if !batch.acknowledge(rt.AddClient(ctx, oldInbound, client)) { return false } } @@ -725,12 +727,14 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } return !prunedOrphans }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } return needRestart, nil } -func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) { +func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(data.Id) defer mutation.close() @@ -758,6 +762,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if err != nil { return false, err } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err } @@ -1190,16 +1195,18 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo } } } else if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { - if err := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]); err != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err) + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0])) { return false } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) return true }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } } else { + s.recordClientNodeDeferred(oldInbound.NodeID) logger.Debug("Client old email not found") needRestart = true } @@ -1207,7 +1214,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo return needRestart, nil } -func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) { +func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(inboundId) defer mutation.close() @@ -1217,6 +1224,7 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo logger.Error("Load Old Data Error") return false, err } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { @@ -1367,24 +1375,26 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // must remove the node's client record too, not just detach it from // this inbound (#5797). if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { - var err error + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { if fullDelete { + complete := len(pending) > 0 for _, row := range pending { - err = applyNodeClientDelete(ctx, rt, row) + result, attempted, err := applyNodeClientDelete(ctx, rt, row) + if !batch.acknowledge(result, err) { + return false + } + complete = complete && attempted } - } else { - err = rt.DeleteUser(ctx, oldInbound, email) + return complete } - if err != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err) + if !batch.acknowledge(rt.DeleteUser(ctx, oldInbound, email)) { return false } - if !fullDelete { - advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) return true }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } } } diff --git a/internal/web/service/client_lookup.go b/internal/web/service/client_lookup.go index 391d19563..d80cd99f6 100644 --- a/internal/web/service/client_lookup.go +++ b/internal/web/service/client_lookup.go @@ -237,17 +237,6 @@ func (s *ClientService) List() ([]ClientWithAttachments, error) { return out, nil } -func (s *ClientService) HasPendingNode(inboundSvc *InboundService, email string) bool { - if strings.TrimSpace(email) == "" { - return false - } - ids, err := s.GetInboundIdsForEmail(nil, email) - if err != nil { - return false - } - return inboundSvc.AnyNodePending(ids) -} - const settingsProbeBytes = 64 // findInboundIdsByClientEmail returns every inbound whose settings.clients[] diff --git a/internal/web/service/client_node_apply.go b/internal/web/service/client_node_apply.go new file mode 100644 index 000000000..4c7be4f19 --- /dev/null +++ b/internal/web/service/client_node_apply.go @@ -0,0 +1,106 @@ +package service + +import ( + "context" + "errors" + "sort" + "sync" + + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +type ClientNodeApplyOutcome struct { + NodeID int `json:"nodeId" example:"7"` + Status string `json:"status" enum:"applied,pending,failed" example:"pending"` + Reason string `json:"reason,omitempty" example:"timeout"` +} + +type ClientNodeApplyResponse struct { + NodePending bool `json:"nodePending,omitempty" example:"true"` + NodeResults []ClientNodeApplyOutcome `json:"nodeResults,omitempty"` +} + +type clientNodeApplyReport struct { + mu sync.Mutex + byNode map[int]ClientNodeApplyOutcome + pending bool +} + +var errClientNodePushBusy = errors.New("node client apply capacity reached") + +// TrackNodeApplies gives one request its own outcome collection. +func (s ClientService) TrackNodeApplies() ClientService { + s.nodeApplies = &clientNodeApplyReport{ + byNode: make(map[int]ClientNodeApplyOutcome), + } + return s +} + +func (s *ClientService) NodeApplyResponse() *ClientNodeApplyResponse { + report := s.nodeApplies + if report == nil { + return nil + } + report.mu.Lock() + defer report.mu.Unlock() + if len(report.byNode) == 0 { + return nil + } + result := &ClientNodeApplyResponse{NodePending: report.pending, NodeResults: make([]ClientNodeApplyOutcome, 0, len(report.byNode))} + for _, outcome := range report.byNode { + result.NodeResults = append(result.NodeResults, outcome) + } + sort.Slice(result.NodeResults, func(i, j int) bool { + return result.NodeResults[i].NodeID < result.NodeResults[j].NodeID + }) + return result +} + +func (s *ClientService) recordClientNodeFailure(id *int, err *error) { + if id != nil && *err != nil && !errors.Is(*err, ErrClientNotInInbound) { + s.recordClientNodeApply(*id, "failed", "local_save_failed") + } +} + +func (s *ClientService) recordClientNodePush(id int, attempted bool, result runtime.ClientApplyResult, err error) { + status, reason := "pending", "deferred" + switch { + case !attempted: + case err == nil && result.DownstreamPending: + reason = "downstream_pending" + case err == nil: + status, reason = "applied", "" + case errors.Is(err, context.DeadlineExceeded): + reason = "timeout" + case errors.Is(err, errClientNodePushBusy): + reason = "busy" + default: + reason = "push_failed" + } + s.recordClientNodeApply(id, status, reason) +} + +func (s *ClientService) recordClientNodeApply(id int, status, reason string) { + report := s.nodeApplies + if report == nil { + return + } + report.mu.Lock() + defer report.mu.Unlock() + report.pending = report.pending || status == "pending" + prev := report.byNode[id] + // Keep the most severe result when several inbounds share the same node. + if prev.Status == "failed" || prev.Status == "pending" && status == "applied" { + return + } + if prev.Status == status && prev.Reason != "deferred" && (reason == "deferred" || prev.Reason <= reason) { + return + } + report.byNode[id] = ClientNodeApplyOutcome{NodeID: id, Status: status, Reason: reason} +} + +func (s *ClientService) recordClientNodeDeferred(id *int) { + if id != nil { + s.recordClientNodePush(*id, false, runtime.ClientApplyResult{}, nil) + } +} diff --git a/internal/web/service/client_node_apply_test.go b/internal/web/service/client_node_apply_test.go new file mode 100644 index 000000000..9d69ccbae --- /dev/null +++ b/internal/web/service/client_node_apply_test.go @@ -0,0 +1,86 @@ +package service + +import ( + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestClientFanoutAdmitsHealthyNodeBeforeSlowNodeFillsSlots(t *testing.T) { + slow, healthy := 1, 2 + release := make(chan struct{}) + healthyStarted := make(chan struct{}) + applies := make([]inboundApply, 0, inboundFanoutConcurrency+1) + for i := range inboundFanoutConcurrency { + applies = append(applies, inboundApply{id: i + 1, nodeID: &slow, run: func() (bool, error) { + <-release + return false, nil + }}) + } + applies = append(applies, inboundApply{id: len(applies) + 1, nodeID: &healthy, run: func() (bool, error) { + close(healthyStarted) + return false, nil + }}) + done := make(chan error, 1) + go func() { + _, err := fanoutInboundApplies(applies) + done <- err + }() + defer func() { + close(release) + if err := <-done; err != nil { + t.Error(err) + } + }() + select { + case <-healthyStarted: + case <-time.After(2 * time.Second): + t.Fatal("healthy node waited for a slow node to free a slot") + } +} + +func TestBulkClientFanoutAdmitsHealthyNodeBeforeSlowNodeFillsSlots(t *testing.T) { + setupBulkDB(t) + slow := model.Node{Name: "slow", Address: "127.0.0.1", Port: 8443} + healthy := model.Node{Name: "healthy", Address: "127.0.0.1", Port: 8444} + if err := database.GetDB().Create(&slow).Error; err != nil { + t.Fatal(err) + } + if err := database.GetDB().Create(&healthy).Error; err != nil { + t.Fatal(err) + } + var ids []int + for i := range inboundFanoutConcurrency { + ids = append(ids, nodeInbound(t, slow.Id, 54500+i, nil).Id) + } + ids = append(ids, nodeInbound(t, healthy.Id, 54510, nil).Id) + release, started := make(chan struct{}), make(chan struct{}) + done := make(chan []int, 1) + go func() { + out, _ := fanoutClientInboundResults(ids, inboundFanoutConcurrency, func(i int) int { + if i == len(ids)-1 { + close(started) + } else { + <-release + } + return ids[i] + }) + done <- out + }() + defer func() { + close(release) + out := <-done + for i := range ids { + if out[i] != ids[i] { + t.Errorf("result %d belongs to inbound %d, want %d", i, out[i], ids[i]) + } + } + }() + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("bulk fanout left the healthy inbound behind the slow node") + } +} diff --git a/internal/web/service/client_node_dispatch.go b/internal/web/service/client_node_dispatch.go index b00a47ec2..fc3aae0aa 100644 --- a/internal/web/service/client_node_dispatch.go +++ b/internal/web/service/client_node_dispatch.go @@ -4,10 +4,12 @@ import ( "container/list" "context" "sync" + "time" "gorm.io/gorm" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/logger" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) @@ -19,6 +21,7 @@ var ( type nodeConfigQueue struct { groups list.List reconciles int + live int } // Inbounds in the same group can push concurrently. A node-wide operation @@ -161,7 +164,10 @@ func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWo return runSerializedTx(write) } nodeID := *inbound.NodeID - return runSerializedTxThen(func(tx *gorm.DB) error { + queuedAt := time.Now() + var startedAt time.Time + err := runSerializedTxThen(func(tx *gorm.DB) error { + startedAt = time.Now() if err := write(tx); err != nil { return err } @@ -169,19 +175,55 @@ func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWo }, func() { m.turn = reserveNodeConfigTurn(nodeID, inbound.Id, work) }) + if !startedAt.IsZero() { + logger.Debugf("client node save: node_id=%d writer_wait_ms=%d tx_ms=%d success=%t", nodeID, + startedAt.Sub(queuedAt).Milliseconds(), time.Since(startedAt).Milliseconds(), err == nil) + } + return err } -func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, apply func(context.Context) bool) { +type nodeClientBatch struct { + result runtime.ClientApplyResult + err error +} + +func (b *nodeClientBatch) acknowledge(result runtime.ClientApplyResult, err error) bool { + b.result.DownstreamPending = b.result.DownstreamPending || result.DownstreamPending + b.err = err + return err == nil +} + +func (m *inboundClientMutation) push(s *ClientService, rt runtime.Runtime, inbound *model.Inbound, apply func(context.Context, *nodeClientBatch) bool) { m.unlock() if m.turn == nil { + s.recordClientNodeDeferred(inbound.NodeID) return } + nodeID := m.turn.nodeID + queued := time.Now() waitCtx, stopWaiting := nodePushContext() ready := m.turn.wait(waitCtx) + waitErr := waitCtx.Err() stopWaiting() if !ready { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, waitErr) + logger.Debugf("client node apply: node_id=%d queue_wait_ms=%d deferred=timeout", nodeID, time.Since(queued).Milliseconds()) return } + // Conflicting turns wait without consuming a live slot. + nodeConfigDispatchMu.Lock() + if m.turn.queue.live >= inboundFanoutConcurrency { + nodeConfigDispatchMu.Unlock() + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) + return + } + m.turn.queue.live++ + nodeConfigDispatchMu.Unlock() + defer func() { + nodeConfigDispatchMu.Lock() + m.turn.queue.live-- + nodeConfigDispatchMu.Unlock() + }() ctx, cancel := nodePushContext() defer cancel() complete := false @@ -190,5 +232,13 @@ func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, remote.ForgetPushedInbound(inbound.Tag) } }() - complete = apply(ctx) + started := time.Now() + var batch nodeClientBatch + complete = apply(ctx, &batch) + s.recordClientNodePush(nodeID, complete || batch.err != nil || batch.result.DownstreamPending, batch.result, batch.err) + if batch.err != nil { + logger.Warning("Error applying clients on", rt.Name(), ":", batch.err) + } + logger.Debugf("client node apply: node_id=%d queue_wait_ms=%d rpc_ms=%d complete=%t downstream_pending=%t", + nodeID, started.Sub(queued).Milliseconds(), time.Since(started).Milliseconds(), complete, batch.result.DownstreamPending) } diff --git a/internal/web/service/client_node_order_test.go b/internal/web/service/client_node_order_test.go index f3f1d1a5b..771867366 100644 --- a/internal/web/service/client_node_order_test.go +++ b/internal/web/service/client_node_order_test.go @@ -32,14 +32,14 @@ type blockedClientPushRuntime struct { expired atomic.Bool } -func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbound, client model.Client) error { +func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbound, client model.Client) (runtime.ClientApplyResult, error) { r.calls <- "add " + client.Email if client.Email != r.blockedEmail { - return nil + return runtime.ClientApplyResult{}, nil } if r.waitForTimeout { if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > nodeClientPushTimeout { - return errors.New("push timeout was not enforced") + return runtime.ClientApplyResult{}, errors.New("push timeout was not enforced") } // Give the node a shorter deadline so this case exercises RPC ordering // and the queue-expiry regression can test the separate wait budget. @@ -47,24 +47,24 @@ func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbou defer cancel() <-call.Done() r.expired.Store(errors.Is(call.Err(), context.DeadlineExceeded)) - return call.Err() + return runtime.ClientApplyResult{}, call.Err() } select { case <-r.release: - return nil + return runtime.ClientApplyResult{}, nil case <-ctx.Done(): - return ctx.Err() + return runtime.ClientApplyResult{}, ctx.Err() } } -func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) error { +func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) (runtime.ClientApplyResult, error) { r.calls <- "update " + email + " " + client.Comment - return nil + return runtime.ClientApplyResult{}, nil } -func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) error { +func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) (runtime.ClientApplyResult, error) { r.calls <- "detach " + email - return nil + return runtime.ClientApplyResult{}, nil } func (r *blockedClientPushRuntime) UpdateInbound(_ context.Context, _ *model.Inbound, inbound *model.Inbound) error { diff --git a/internal/web/service/client_node_push_test.go b/internal/web/service/client_node_push_test.go index 9d6b135cd..ed2c52513 100644 --- a/internal/web/service/client_node_push_test.go +++ b/internal/web/service/client_node_push_test.go @@ -1,8 +1,10 @@ package service import ( + "fmt" "os" "path/filepath" + "sync" "testing" "time" @@ -116,3 +118,160 @@ func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) { t.Fatalf("delete requests including replay after reopening = %d, want 4 (one timed out, then all three retried)", got) } } + +func TestClientBatchesContinueAfterDownstreamPendingAck(t *testing.T) { + tests := []struct { + name string + path string + run func(*testing.T, *ClientService, *InboundService, *model.Inbound, []string) error + }{ + {"full delete", "/clients/del/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error { + _, _, err := svc.BulkDelete(inbounds, emails, false) + return err + }}, + {"disable", "/clients/update/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error { + _, _, err := svc.BulkSetEnable(inbounds, emails, false) + return err + }}, + {"adjust", "/clients/update/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error { + _, _, err := svc.BulkAdjust(inbounds, emails, 1, 0, "", nil, "") + return err + }}, + {"detach", "/detach", func(t *testing.T, svc *ClientService, inbounds *InboundService, ib *model.Inbound, emails []string) error { + records := make([]*model.ClientRecord, 0, len(emails)) + for _, email := range emails { + record := lookupClientRecord(t, email) + records = append(records, &record) + } + _, err := svc.delInboundClients(inbounds, ib.Id, records, true) + return err + }}, + {"add", "/clients/add", func(t *testing.T, svc *ClientService, inbounds *InboundService, original *model.Inbound, _ []string) error { + target := *original + target.Settings = clientsSettings(t, makeNodeClients(3)) + _, err := svc.AddInboundClient(inbounds, &target) + return err + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + setupBulkDB(t) + startSerializedWriter(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + fake.mu.Lock() + fake.pendingClientAcks = 1 + fake.mu.Unlock() + + const batchSize = 3 + clients := makeNodeClients(batchSize) + emails := make([]string, 0, batchSize) + for i := range clients { + clients[i].Email = "seed-" + clients[i].Email + clients[i].SubID = clients[i].Email + clients[i].ExpiryTime = time.Now().Add(24 * time.Hour).UnixMilli() + emails = append(emails, clients[i].Email) + } + inbound := realNodeInbound(t, fake, 53300, clients) + for _, client := range clients { + mkTraffic(t, inbound.Id, client.Email, 0, 0, 0, client.ExpiryTime, true) + } + + svc := (ClientService{}).TrackNodeApplies() + if err := tt.run(t, &svc, &InboundService{}, inbound, emails); err != nil { + t.Fatal(err) + } + if got := fake.hitCount(tt.path); got != batchSize { + t.Errorf("node received %d requests, want %d after acknowledging downstream pending", got, batchSize) + } + result := svc.NodeApplyResponse() + want := ClientNodeApplyOutcome{NodeID: *inbound.NodeID, Status: "pending", Reason: "downstream_pending"} + if result == nil || !result.NodePending || len(result.NodeResults) != 1 || result.NodeResults[0] != want { + t.Errorf("%s report = %+v, want one downstream pending outcome", tt.name, result) + } + }) + } +} + +func TestNodeClientCapacityPreservesPermanentDelete(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + node := newFakeNodeHTTP(t) + const email = "durable-under-load@example.test" + target := realNodeInbound(t, node, 53400, []model.Client{{Email: email, ID: "a820e1e7-7bc8-4cc3-a5e4-cd8805271ea7", Enable: true}}) + nodeID := *target.NodeID + inboundSvc := &InboundService{} + adds := make([]*model.Inbound, 0, inboundFanoutConcurrency+1) + for i := range inboundFanoutConcurrency + 1 { + ib := nodeInbound(t, nodeID, 53401+i, nil) + node.mu.Lock() + node.tags[ib.Tag] = 200 + i + node.mu.Unlock() + adds = append(adds, &model.Inbound{ + Id: ib.Id, Protocol: ib.Protocol, + Settings: clientsSettings(t, []model.Client{{ + Email: fmt.Sprintf("load-%d@example.test", i), + ID: fmt.Sprintf("66666666-1111-2222-3333-%012d", i+1), Enable: true, + }}), + }) + } + node.setHold(true) + errs := make(chan error, inboundFanoutConcurrency) + var wg sync.WaitGroup + t.Cleanup(wg.Wait) + for _, add := range adds[:inboundFanoutConcurrency] { + wg.Go(func() { + _, err := (&ClientService{}).AddInboundClient(inboundSvc, add) + errs <- err + }) + } + deadline := time.Now().Add(2 * time.Second) + for node.hitCount("/clients/add") < inboundFanoutConcurrency { + if time.Now().After(deadline) { + t.Fatal("parallel RPCs did not occupy all live slots") + } + time.Sleep(5 * time.Millisecond) + } + clientSvc := (ClientService{}).TrackNodeApplies() + if _, err := clientSvc.AddInboundClient(inboundSvc, adds[inboundFanoutConcurrency]); err != nil { + t.Fatal(err) + } + report := clientSvc.NodeApplyResponse() + if report == nil || len(report.NodeResults) != 1 || report.NodeResults[0].Reason != "busy" || + node.hitCount("/clients/add") != inboundFanoutConcurrency { + t.Fatalf("saturated delta must save without taking a live slot: %+v", report) + } + + earlier := reserveNodeConfigTurn(nodeID, target.Id, nodeClientDelta) + defer earlier.release() + record := lookupClientRecord(t, email) + deleteSvc := (ClientService{}).TrackNodeApplies() + if _, err := deleteSvc.Delete(inboundSvc, record.Id, false); err != nil { + t.Fatal(err) + } + report = deleteSvc.NodeApplyResponse() + if report == nil || len(report.NodeResults) != 1 || report.NodeResults[0].Reason != "timeout" || + node.hitCount("/clients/del/") != 0 { + t.Fatalf("exclusive delete must defer when its queue wait expires: %+v", report) + } + earlier.release() + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatal(err) + } + } + + node.setHold(false) + var row model.Node + if err := database.GetDB().First(&row, nodeID).Error; err != nil { + t.Fatal(err) + } + if err := inboundSvc.ReconcileNode(t.Context(), runtime.NewRemote(&row, nil), &row); err != nil { + t.Fatal(err) + } + if got := node.hitCount("/clients/del/"); got != 1 { + t.Fatalf("reconcile sent %d permanent deletes after saturation, want one", got) + } +} diff --git a/internal/web/service/client_update_fanout_test.go b/internal/web/service/client_update_fanout_test.go index 5efea58b7..455ec5212 100644 --- a/internal/web/service/client_update_fanout_test.go +++ b/internal/web/service/client_update_fanout_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) // applyBarrierRuntime holds every armed node push until fanout of them are @@ -60,12 +61,12 @@ func (b *applyBarrierRuntime) wait() { b.inFlight.Add(-1) } -func (b *applyBarrierRuntime) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, c model.Client) error { +func (b *applyBarrierRuntime) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, c model.Client) (runtime.ClientApplyResult, error) { b.wait() return b.fakeNodeRuntime.UpdateUser(ctx, ib, oldEmail, c) } -func (b *applyBarrierRuntime) AddClient(ctx context.Context, ib *model.Inbound, c model.Client) error { +func (b *applyBarrierRuntime) AddClient(ctx context.Context, ib *model.Inbound, c model.Client) (runtime.ClientApplyResult, error) { b.wait() return b.fakeNodeRuntime.AddClient(ctx, ib, c) } @@ -75,12 +76,12 @@ func (b *applyBarrierRuntime) ResetClientTraffic(ctx context.Context, ib *model. return b.fakeNodeRuntime.ResetClientTraffic(ctx, ib, email) } -func (b *applyBarrierRuntime) DeleteClient(ctx context.Context, email string) error { +func (b *applyBarrierRuntime) DeleteClient(ctx context.Context, email string) (runtime.ClientApplyResult, error) { b.wait() return b.fakeNodeRuntime.DeleteClient(ctx, email) } -func (b *applyBarrierRuntime) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error { +func (b *applyBarrierRuntime) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (runtime.ClientApplyResult, error) { b.wait() return b.fakeNodeRuntime.DeleteUser(ctx, ib, email) } diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 2b4887144..b80d7ea7b 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -111,23 +111,6 @@ func (s *InboundService) NodeIsPending(nodeID *int) bool { return (&NodeService{}).IsNodePending(*nodeID) } -func (s *InboundService) AnyNodePending(inboundIds []int) bool { - if len(inboundIds) == 0 { - return false - } - nodeSvc := NodeService{} - for _, id := range uniqueInts(inboundIds) { - ib, err := s.GetInbound(id) - if err != nil || ib.NodeID == nil { - continue - } - if nodeSvc.IsNodePending(*ib.NodeID) { - return true - } - } - return false -} - // ReconcileNode pushes every inbound and sweeps undesired remote tags even when // individual operations fail, returning the failures joined: one inbound the // node rejects (e.g. a legacy protocol failing validation, #5685) must not @@ -469,11 +452,32 @@ func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime. // SetRemoteTraffic merges a node snapshot. justPushed marks the tick whose // config push just landed, whose snapshot may still predate it (#6228). func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { + return s.mergeNodeTraffic(context.Background(), nodeID, snap, dirty, justPushed, false) +} + +// MergeOnlineNodeTraffic rechecks eligibility inside the serialized writer. +func (s *InboundService) MergeOnlineNodeTraffic(ctx context.Context, nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { + return s.mergeNodeTraffic(ctx, nodeID, snap, dirty, justPushed, true) +} + +func (s *InboundService) mergeNodeTraffic(ctx context.Context, nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed, requireOnline bool) (bool, error) { var structuralChange bool queuedAt := time.Now() // Node merges take the background lane: a per-client mutation the operator // is waiting on must not queue behind the next batch of 5s snapshots. err := submitTrafficWriteBackground(func() error { + if err := ctx.Err(); err != nil { + return err + } + if requireOnline { + enabled, status, _, _, err := (&NodeService{}).NodeSyncState(nodeID) + if err != nil { + return err + } + if !enabled || status != "online" { + return context.Canceled + } + } started := time.Now() var inner error structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty, justPushed) diff --git a/internal/web/service/node.go b/internal/web/service/node.go index 735448b24..bac491ed1 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -851,32 +851,19 @@ func FilterNodeSnapshot(n *model.Node, snap *runtime.TrafficSnapshot) { } func (s *NodeService) Delete(id int) error { - db := database.GetDB() - // Refuse to delete a node that still owns inbounds: dropping the node row - // while inbounds keep its node_id leaves orphaned, dangling references that - // confuse node sync, subscriptions and cleanup. The operator must detach or - // remove those inbounds first. (DB-002) - var attached int64 - if err := db.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil { - return err - } - if attached > 0 { - return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached)) - } - // Capture the node's guid before deleting the row so we can drop its per-node - // IP attribution. NodeClientIp is keyed by the node's attribution key, which - // is its guid normally but its node-unique key for a cloned/ambiguous-guid - // node (see effectiveNodeKey) — so we purge both below. - var guid string - var n model.Node - if err := db.Select("guid").Where("id = ?", id).First(&n).Error; err == nil { - guid = n.Guid - } - // Delete the node row and its per-node child rows atomically. Remove the - // children (traffic baselines, IP attribution) before the parent node row so - // the ordering already matches a future ON DELETE constraint. Delete stays - // tolerant of a missing node row so it can still clean up orphaned baselines. - if err := db.Transaction(func(tx *gorm.DB) error { + // Order the attachment check with snapshot adoption on the shared writer. + if err := runSerializedTx(func(tx *gorm.DB) error { + var attached int64 + if err := tx.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil { + return err + } + if attached > 0 { + return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached)) + } + var n model.Node + if err := tx.Select("guid").Where("id = ?", id).First(&n).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } if err := tx.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil { return err } @@ -887,8 +874,8 @@ func (s *NodeService) Delete(id int) error { return err } guids := []string{synthNodeGuid(id)} - if guid != "" { - guids = append(guids, guid) + if n.Guid != "" { + guids = append(guids, n.Guid) } if err := tx.Where("node_guid IN ?", guids).Delete(&model.NodeClientIp{}).Error; err != nil { return err @@ -907,8 +894,9 @@ func (s *NodeService) Delete(id int) error { } func (s *NodeService) SetEnable(id int, enable bool) error { - db := database.GetDB() - if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil { + if err := runSerializedTx(func(tx *gorm.DB) error { + return tx.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error + }); err != nil { return err } if mgr := runtime.GetManager(); mgr != nil { diff --git a/internal/web/service/node_bulk_dispatch_test.go b/internal/web/service/node_bulk_dispatch_test.go index 6e33f9702..2f6d89dd2 100644 --- a/internal/web/service/node_bulk_dispatch_test.go +++ b/internal/web/service/node_bulk_dispatch_test.go @@ -54,24 +54,24 @@ func (f *fakeNodeRuntime) AddUser(context.Context, *model.Inbound, map[string]an func (f *fakeNodeRuntime) RemoveUser(context.Context, *model.Inbound, string) error { return nil } -func (f *fakeNodeRuntime) UpdateUser(context.Context, *model.Inbound, string, model.Client) error { +func (f *fakeNodeRuntime) UpdateUser(context.Context, *model.Inbound, string, model.Client) (runtime.ClientApplyResult, error) { f.updateUser.Add(1) - return nil + return runtime.ClientApplyResult{}, nil } -func (f *fakeNodeRuntime) DeleteUser(context.Context, *model.Inbound, string) error { +func (f *fakeNodeRuntime) DeleteUser(context.Context, *model.Inbound, string) (runtime.ClientApplyResult, error) { f.deleteUser.Add(1) - return nil + return runtime.ClientApplyResult{}, nil } -func (f *fakeNodeRuntime) DeleteClient(context.Context, string) error { +func (f *fakeNodeRuntime) DeleteClient(context.Context, string) (runtime.ClientApplyResult, error) { f.deleteClient.Add(1) - return nil + return runtime.ClientApplyResult{}, nil } -func (f *fakeNodeRuntime) AddClient(context.Context, *model.Inbound, model.Client) error { +func (f *fakeNodeRuntime) AddClient(context.Context, *model.Inbound, model.Client) (runtime.ClientApplyResult, error) { f.addClient.Add(1) - return nil + return runtime.ClientApplyResult{}, nil } func (f *fakeNodeRuntime) RestartXray(context.Context) error { return nil } func (f *fakeNodeRuntime) ResetClientTraffic(context.Context, *model.Inbound, string) error { @@ -103,7 +103,7 @@ func useTestRuntimeManager(t *testing.T) *runtime.Manager { // apply path that would otherwise unwind straight out of a fanout goroutine. type panicNodeRuntime struct{ fakeNodeRuntime } -func (p *panicNodeRuntime) AddClient(context.Context, *model.Inbound, model.Client) error { +func (p *panicNodeRuntime) AddClient(context.Context, *model.Inbound, model.Client) (runtime.ClientApplyResult, error) { panic("boom from node runtime") } diff --git a/internal/web/service/node_client_delete_queue.go b/internal/web/service/node_client_delete_queue.go index e494420ed..af466dfe2 100644 --- a/internal/web/service/node_client_delete_queue.go +++ b/internal/web/service/node_client_delete_queue.go @@ -51,7 +51,7 @@ func sameNodeClientDelete(db *gorm.DB, row model.NodePendingClientDelete) *gorm. // applyNodeClientDelete runs under the node-wide turn. Later attached clients // push after this turn or are restored by the dirty generation on reconcile. -func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.NodePendingClientDelete) error { +func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.NodePendingClientDelete) (runtime.ClientApplyResult, bool, error) { db := database.GetDB().WithContext(ctx) var target struct { Desired bool @@ -63,16 +63,19 @@ func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.No Joins("LEFT JOIN clients ON clients.email = node_pending_client_deletes.email"). Limit(1).Scan(&target) if result.Error != nil || result.RowsAffected == 0 { - return result.Error + return runtime.ClientApplyResult{}, false, result.Error } // Only a desired attachment on this node supersedes its pending delete. // Recreating the email elsewhere must not leave the old node record behind. + var applied runtime.ClientApplyResult if !target.Desired { - if err := rt.DeleteClient(ctx, row.Email); err != nil { - return err + var err error + applied, err = rt.DeleteClient(ctx, row.Email) + if err != nil { + return applied, false, err } } - return sameNodeClientDelete(db, row).Delete(&model.NodePendingClientDelete{}).Error + return applied, !target.Desired, sameNodeClientDelete(db, row).Delete(&model.NodePendingClientDelete{}).Error } const nodeClientDeletePage = 200 @@ -93,7 +96,7 @@ func deliverNodeClientDeletes(ctx context.Context, nodeID int, rt runtime.Runtim defer cancel() var firstErr error for _, row := range rows { - if err := applyNodeClientDelete(sendCtx, rt, row); err != nil { + if _, _, err := applyNodeClientDelete(sendCtx, rt, row); err != nil { if firstErr == nil { firstErr = err } diff --git a/internal/web/service/node_dirty_test.go b/internal/web/service/node_dirty_test.go index 111cba574..35a186754 100644 --- a/internal/web/service/node_dirty_test.go +++ b/internal/web/service/node_dirty_test.go @@ -3,6 +3,7 @@ package service import ( "errors" "testing" + "time" "gorm.io/gorm" @@ -11,6 +12,29 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) +func TestMarkNodeDirtyAdvancesRevisionPastCurrentClock(t *testing.T) { + setupConflictDB(t) + node := model.Node{ + Name: "revision", Enable: true, ConfigDirty: true, + ConfigDirtyAt: time.Now().Add(time.Minute).UnixMilli(), + } + db := database.GetDB() + if err := db.Create(&node).Error; err != nil { + t.Fatal(err) + } + svc := &NodeService{} + if err := svc.MarkNodeDirty(node.Id); err != nil { + t.Fatal(err) + } + if err := svc.ClearNodeDirty(node.Id, node.ConfigDirtyAt); err != nil { + t.Fatal(err) + } + _, _, dirty, revision, err := svc.NodeSyncState(node.Id) + if err != nil || !dirty || revision <= node.ConfigDirtyAt { + t.Fatalf("dirty=%t revision=%d, want dirty revision newer than %d: %v", dirty, revision, node.ConfigDirtyAt, err) + } +} + // While a node is config-dirty (a local edit committed before it could be // mirrored to the node), the traffic pull must not overwrite the central // inbound's config columns from the node's stale snapshot — only traffic diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go index 609123e9d..b5ce92530 100644 --- a/internal/web/service/node_http_fake_test.go +++ b/internal/web/service/node_http_fake_test.go @@ -19,11 +19,12 @@ import ( // fakeNodeHTTP emulates a node panel over real HTTP, so the master's Remote // (tag cache, list fetch, per-op RPC, timeouts) runs for real, not a stub. type fakeNodeHTTP struct { - srv *httptest.Server - mu sync.Mutex - tags map[string]int - hits map[string]int - caps string + srv *httptest.Server + mu sync.Mutex + tags map[string]int + hits map[string]int + caps string + pendingClientAcks int // hold makes every non-list request block until the master gives up. hold bool release chan struct{} @@ -56,6 +57,10 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { f.mu.Lock() f.hits[r.URL.Path]++ hold := f.hold + pending := f.pendingClientAcks > 0 && strings.Contains(r.URL.Path, "/clients/") + if pending { + f.pendingClientAcks-- + } f.mu.Unlock() if hold { // Drain first: the server only notices a client disconnect once the @@ -67,6 +72,10 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { } return } + if pending { + _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":true}}`)) + return + } _, _ = w.Write([]byte(`{"success":true,"msg":""}`)) })) t.Cleanup(f.srv.Close) diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index f8766bf36..dd6b04f5f 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "تمت إضافة عميل(عملاء) وارد", "inboundClientDeleteSuccess": "تم حذف عميل وارد", "inboundClientUpdateSuccess": "تم تحديث عميل وارد", - "savedNodeOfflineWillSync": "تم الحفظ محليًا. إحدى العُقد الداعمة غير متصلة أو معطّلة — ستتم مزامنة التغيير بمجرد إعادة الاتصال.", + "savedNodeApplyPending": "تم الحفظ محليًا. لم يُطبَّق التغيير على عقدة واحدة أو أكثر بعد.", "resetAllClientTrafficSuccess": "تم إعادة تعيين كل حركة المرور من العميل", "resetAllTrafficSuccess": "تم إعادة تعيين كل حركة المرور", "resetInboundClientTrafficSuccess": "تم إعادة تعيين حركة المرور", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 24af28443..5457d21d5 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -476,7 +476,7 @@ "inboundClientAddSuccess": "Inbound client(s) have been added.", "inboundClientDeleteSuccess": "Inbound client has been deleted.", "inboundClientUpdateSuccess": "Inbound client has been updated.", - "savedNodeOfflineWillSync": "Saved locally. A backing node is offline or disabled — the change will sync once it reconnects.", + "savedNodeApplyPending": "Saved locally. Applying the change on one or more nodes is pending.", "resetAllClientTrafficSuccess": "Traffic for all clients has been reset.", "resetAllTrafficSuccess": "All traffic has been reset.", "resetInboundClientTrafficSuccess": "Traffic has been reset.", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 42429f419..f9591939d 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Cliente(s) de entrada añadido(s)", "inboundClientDeleteSuccess": "Cliente de entrada eliminado", "inboundClientUpdateSuccess": "Cliente de entrada actualizado", - "savedNodeOfflineWillSync": "Guardado localmente. Un nodo de respaldo está desconectado o deshabilitado: el cambio se sincronizará cuando vuelva a conectarse.", + "savedNodeApplyPending": "Guardado localmente. El cambio está pendiente de aplicarse en uno o más nodos.", "resetAllClientTrafficSuccess": "Todo el tráfico del cliente ha sido reiniciado", "resetAllTrafficSuccess": "Todo el tráfico ha sido reiniciado", "resetInboundClientTrafficSuccess": "El tráfico ha sido reiniciado", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 5f8bf7016..32b06d5fe 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "کلاینت(های) ورودی اضافه شدند", "inboundClientDeleteSuccess": "کلاینت ورودی حذف شد", "inboundClientUpdateSuccess": "کلاینت ورودی به‌روزرسانی شد", - "savedNodeOfflineWillSync": "به‌صورت محلی ذخیره شد. یک نود پشتیبان آفلاین یا غیرفعال است — تغییر پس از اتصال مجدد همگام‌سازی می‌شود.", + "savedNodeApplyPending": "به‌صورت محلی ذخیره شد. اعمال تغییر روی یک یا چند نود در انتظار همگام‌سازی است.", "resetAllClientTrafficSuccess": "تمام ترافیک کلاینت بازنشانی شد", "resetAllTrafficSuccess": "تمام ترافیک‌ها بازنشانی شدند", "resetInboundClientTrafficSuccess": "ترافیک بازنشانی شد", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 209bdc64e..e5f93b779 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Klien inbound telah ditambahkan", "inboundClientDeleteSuccess": "Klien inbound telah dihapus", "inboundClientUpdateSuccess": "Klien inbound telah diperbarui", - "savedNodeOfflineWillSync": "Disimpan secara lokal. Node pendukung sedang offline atau dinonaktifkan — perubahan akan disinkronkan setelah terhubung kembali.", + "savedNodeApplyPending": "Disimpan secara lokal. Penerapan perubahan pada satu atau beberapa node masih tertunda.", "resetAllClientTrafficSuccess": "Semua lalu lintas klien telah direset", "resetAllTrafficSuccess": "Semua lalu lintas telah direset", "resetInboundClientTrafficSuccess": "Lalu lintas telah direset", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 58837eb0a..b7980610e 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "インバウンドクライアントが追加されました", "inboundClientDeleteSuccess": "インバウンドクライアントが削除されました", "inboundClientUpdateSuccess": "インバウンドクライアントが更新されました", - "savedNodeOfflineWillSync": "ローカルに保存しました。バックエンドのノードがオフラインまたは無効になっています — 再接続後に変更が同期されます。", + "savedNodeApplyPending": "ローカルに保存しました。1 つ以上のノードへの変更の適用が保留中です。", "resetAllClientTrafficSuccess": "クライアントのすべてのトラフィックがリセットされました", "resetAllTrafficSuccess": "すべてのトラフィックがリセットされました", "resetInboundClientTrafficSuccess": "トラフィックがリセットされました", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index f5454593c..94527b479 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Cliente(s) de entrada adicionado(s)", "inboundClientDeleteSuccess": "Cliente de entrada excluído", "inboundClientUpdateSuccess": "Cliente de entrada atualizado", - "savedNodeOfflineWillSync": "Salvo localmente. Um nó de apoio está offline ou desativado — a alteração será sincronizada assim que reconectar.", + "savedNodeApplyPending": "Salvo localmente. A aplicação da alteração em um ou mais nós está pendente.", "resetAllClientTrafficSuccess": "Todo o tráfego do cliente foi reiniciado", "resetAllTrafficSuccess": "Todo o tráfego foi reiniciado", "resetInboundClientTrafficSuccess": "O tráfego foi reiniciado", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 3e336f3fe..41e5e7bdd 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -476,7 +476,7 @@ "inboundClientAddSuccess": "Клиент(ы) подключения добавлен(ы)", "inboundClientDeleteSuccess": "Клиент подключения удалён", "inboundClientUpdateSuccess": "Клиент подключения обновлён", - "savedNodeOfflineWillSync": "Сохранено локально. Опорный узел отключён или недоступен — изменение синхронизируется после повторного подключения.", + "savedNodeApplyPending": "Сохранено локально. Изменение ещё не применено на одном или нескольких узлах.", "resetAllClientTrafficSuccess": "Весь трафик клиента сброшен", "resetAllTrafficSuccess": "Весь трафик сброшен", "resetInboundClientTrafficSuccess": "Трафик сброшен", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index d564f6aad..15c69af56 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -476,7 +476,7 @@ "inboundClientAddSuccess": "Klienti boli pridaní k vstupu.", "inboundClientDeleteSuccess": "Klient bol odstránený zo vstupu.", "inboundClientUpdateSuccess": "Klient na vstupe bol aktualizovaný.", - "savedNodeOfflineWillSync": "Uložené miestne. Príslušný server je offline alebo vypnutý. Zmena sa zosynchronizuje po jeho opätovnom pripojení.", + "savedNodeApplyPending": "Uložené lokálne. Zmena ešte čaká na uplatnenie na jednom alebo viacerých uzloch.", "resetAllClientTrafficSuccess": "Spotreba všetkých klientov bola vynulovaná.", "resetAllTrafficSuccess": "Všetka spotreba bola vynulovaná.", "resetInboundClientTrafficSuccess": "Spotreba bola vynulovaná.", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 6baa7a495..b52fa0f09 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Gelen bağlantı kullanıcı(lar)ı eklendi.", "inboundClientDeleteSuccess": "Gelen bağlantı kullanıcısı silindi.", "inboundClientUpdateSuccess": "Gelen bağlantı kullanıcısı güncellendi.", - "savedNodeOfflineWillSync": "Yerel olarak kaydedildi. Destekleyen bir düğüm çevrimdışı veya devre dışı — değişiklik yeniden bağlandığında senkronize edilecek.", + "savedNodeApplyPending": "Yerel olarak kaydedildi. Değişikliğin bir veya daha fazla düğüme uygulanması bekleniyor.", "resetAllClientTrafficSuccess": "Tüm kullanıcıların trafiği sıfırlandı.", "resetAllTrafficSuccess": "Tüm trafik sıfırlandı.", "resetInboundClientTrafficSuccess": "Trafik sıfırlandı.", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index defd6b693..48082a511 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Клієнт(и) вхідного підключення додано", "inboundClientDeleteSuccess": "Клієнта вхідного підключення видалено", "inboundClientUpdateSuccess": "Клієнта вхідного підключення оновлено", - "savedNodeOfflineWillSync": "Збережено локально. Опорний вузол вимкнено або недоступний — зміни синхронізуються після повторного підключення.", + "savedNodeApplyPending": "Збережено локально. Зміна ще очікує застосування на одному чи кількох вузлах.", "resetAllClientTrafficSuccess": "Весь трафік клієнта скинуто", "resetAllTrafficSuccess": "Весь трафік скинуто", "resetInboundClientTrafficSuccess": "Трафік скинуто", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 9ac29d089..a2a7060d0 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Đã thêm client inbound", "inboundClientDeleteSuccess": "Đã xóa client inbound", "inboundClientUpdateSuccess": "Đã cập nhật client inbound", - "savedNodeOfflineWillSync": "Đã lưu cục bộ. Một nút hỗ trợ đang ngoại tuyến hoặc bị tắt — thay đổi sẽ được đồng bộ khi kết nối lại.", + "savedNodeApplyPending": "Đã lưu cục bộ. Thay đổi đang chờ áp dụng trên một hoặc nhiều nút.", "resetAllClientTrafficSuccess": "Đã đặt lại toàn bộ lưu lượng client", "resetAllTrafficSuccess": "Đã đặt lại toàn bộ lưu lượng", "resetInboundClientTrafficSuccess": "Đã đặt lại lưu lượng", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index fbfd10cd6..fcb7b7535 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "已添加入站客户端", "inboundClientDeleteSuccess": "入站客户端已删除", "inboundClientUpdateSuccess": "入站客户端已更新", - "savedNodeOfflineWillSync": "已在本地保存。某个支撑节点离线或已禁用——重新连接后将同步此更改。", + "savedNodeApplyPending": "已在本地保存。更改尚未应用到一个或多个节点。", "resetAllClientTrafficSuccess": "客户端所有流量已重置", "resetAllTrafficSuccess": "所有流量已重置", "resetInboundClientTrafficSuccess": "流量已重置", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index a1d96b556..04922e8ef 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "已新增入站客戶端", "inboundClientDeleteSuccess": "入站客戶端已刪除", "inboundClientUpdateSuccess": "入站客戶端已更新", - "savedNodeOfflineWillSync": "已在本機儲存。某個支撐節點離線或已停用——重新連線後將同步此變更。", + "savedNodeApplyPending": "已在本機儲存。變更尚未套用到一個或多個節點。", "resetAllClientTrafficSuccess": "客戶端所有流量已重置", "resetAllTrafficSuccess": "所有流量已重置", "resetInboundClientTrafficSuccess": "流量已重置", diff --git a/internal/web/web.go b/internal/web/web.go index f00823791..f6c6f388f 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -137,6 +137,7 @@ type Server struct { bus *eventbus.Bus cron *cron.Cron + nodeTrafficJob *job.NodeTrafficSyncJob discordNotifyEntryID cron.EntryID wechatNotifyEntryID cron.EntryID cpuAlarmEntryID cron.EntryID @@ -364,7 +365,8 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) { _, _ = s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob()) - _, _ = s.cron.AddJob(cadenceNodeTraffic, job.NewNodeTrafficSyncJob()) + s.nodeTrafficJob = job.NewNodeTrafficSyncJob() + _, _ = s.cron.AddJob(cadenceNodeTraffic, s.nodeTrafficJob) // Outbound subscription auto-refresh (respects per-sub updateInterval) _, _ = s.cron.AddJob(cadenceOutboundSub, job.NewOutboundSubscriptionJob()) @@ -816,6 +818,12 @@ func (s *Server) stop(ctx context.Context, stopXray bool, stopTgBot bool) error return nil }) } + if s.nodeTrafficJob != nil { + _ = runPanelStopPhase("node traffic drain", func() error { + s.nodeTrafficJob.Close() + return nil + }) + } if stopXray { tuic.GetManager().StopAll() if err := job.NewTuicJob().FlushStoppedTraffic(); err != nil { diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index f40382268..2633d92c0 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -109,6 +109,8 @@ func run(root, outDir string) error { "Status", "HappLinkResult", "ClientSlim", + "ClientNodeApplyResponse", + "ClientNodeApplyOutcome", "ClientRenewalPreviewRequest", "ClientRenewalPreview", "ClientPageResponse", @@ -117,6 +119,14 @@ func run(root, outDir string) error { "AttachSelectionResult", "BulkAdjustResult", "BulkAdjustReport", + "BulkAttachResult", + "BulkDetachResult", + "BulkCreateResult", + "BulkCreateReport", + "BulkDeleteResult", + "BulkDeleteReport", + "BulkSetEnableResult", + "BulkSetEnableReport", "BulkExternalLinksResult", "ExternalLinkInput", "ClientsSummary", From 7a5a25fae225e83431656a705ef57055f9997bad Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 17:44:17 +0330 Subject: [PATCH 06/14] perf(nodes): reuse client link changes during full reconciliation (#7344) Reuse client records and successful link diffs during full node snapshot reconciliation. Preserve master-owned comments on existing records while importing new comments; omit comment writes so concurrent operator updates survive. Deduplicate detached IDs across successful inbound savepoints and mark only globally unattached clients in bounded 400-ID batches inside the existing transaction; roll back on orphan-mark write failure. Integrate against current main while preserving #7314 target-node pending-delete cancellation and cross-node recreation guarantees, #7315 staged traffic and batched baseline writes, and #7308 serialized eligibility checks. Preserve orphan recovery, degraded-inbound safeguards and idempotent snapshot replay. Validation: all 12 CI jobs passed on 51e627739ef632e86f4f180d91cae4cd8f8c714d (run 46895213148). PostgreSQL logs confirm four new reconciliation tests, both contention/baseline regressions and eight ordering/durable-delete regressions. Author reports focused SQLite/PostgreSQL 18 race tests, make verify and all four mixed-version node E2E pairings. Author-reported controlled 4096-client PostgreSQL 18 fixture: idle SQL statements 350 -> 270, changing-counter statements 552 -> 472, rows read 151832 -> 102680. Idle writer p50/p95 490/597 -> 430/466 ms; counter writer 489/521 -> 449/519 ms. Idle cycle p50/p95 1118/1277 -> 1015/1050 ms; counter cycle 1121/1172 -> 1046/1135 ms. Worst counter cycle effectively unchanged. These fixture results are not independent production measurements. Production tail latency, shared-client compact-cache reuse and migration coordination remain separate follow-ups. Refs #7305 --- .github/workflows/ci.yml | 16 + internal/web/service/client_link.go | 46 ++- internal/web/service/client_sync_orphan.go | 18 +- internal/web/service/inbound_node.go | 99 +----- .../service/node_full_reconciliation_test.go | 336 ++++++++++++++++++ 5 files changed, 406 insertions(+), 109 deletions(-) create mode 100644 internal/web/service/node_full_reconciliation_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9639a7fc8..767a5f045 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,6 +214,22 @@ jobs: exit 1 fi + - name: PostgreSQL node client reconciliation + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(NodeFullReconciliation|NodeMerge(BatchesBaselinesForActiveClients|LetsSubscriptionTouchDuringClientReconciliationPostgres)$)' -count=1 -v | tee /tmp/postgres-node-client-reconciliation.log + passed=$(grep -c -- '^--- PASS: TestNodeFullReconciliation' /tmp/postgres-node-client-reconciliation.log || true) + if [ "$passed" -ne 4 ]; then + echo "expected 4 passing node client reconciliation tests, got $passed" >&2 + exit 1 + fi + for test in TestNodeMergeBatchesBaselinesForActiveClients TestNodeMergeLetsSubscriptionTouchDuringClientReconciliationPostgres; do + if ! grep -q -- "^--- PASS: $test " /tmp/postgres-node-client-reconciliation.log; then + echo "expected PostgreSQL regression to pass: $test" >&2 + exit 1 + fi + done + - name: PostgreSQL node counter reset regressions run: | set -o pipefail diff --git a/internal/web/service/client_link.go b/internal/web/service/client_link.go index 1eda01a15..ddf69e9ac 100644 --- a/internal/web/service/client_link.go +++ b/internal/web/service/client_link.go @@ -106,7 +106,7 @@ func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecor // SyncInbound makes the inbound's client records and links match clients // exactly: links for clients no longer in the set are removed. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error { - return s.syncInboundClients(tx, inboundId, clients, nil, true) + return s.syncInboundClients(tx, inboundId, clients, nil, true, nil) } // withClientSyncSavepoint lets a caller continue only after a failed sync is undone. @@ -132,10 +132,14 @@ func withClientSyncSavepoint(tx *gorm.DB, sync func() error) (rejected, fatal er // the whole point being that a one-client edit must not rewrite the inbound's // entire membership set (#6252). func (s *ClientService) ApplyInboundClientDelta(tx *gorm.DB, inboundId int, changed []model.Client, detachEmails []string) error { - return s.syncInboundClients(tx, inboundId, changed, detachEmails, false) + return s.syncInboundClients(tx, inboundId, changed, detachEmails, false, nil) } -func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool) error { +type nodeInboundSyncResult struct { + detached []int +} + +func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool, node *nodeInboundSyncResult) error { if err := validateClientsRenewal(clients); err != nil { return err } @@ -239,6 +243,9 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ } before := *row + if node != nil { + incoming.Comment = before.Comment + } applyClientRecordMerge(row, incoming) _, outranked := onLowerTunnel[row.Id] _, wireguardOutranked := onLowerWireguard[row.Id] @@ -255,6 +262,10 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ } // Keep GORM's save hooks and serializers while writing the agreed timestamp once. save := tx.Session(&gorm.Session{NowFunc: func() time.Time { return time.UnixMilli(preservedUpdatedAt) }}) + if node != nil { + // An operator can change the note while this node merge is open. + save = save.Omit("Comment") + } if err := save.Save(row).Error; err != nil { return err } @@ -303,7 +314,7 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ wantedIds = append(wantedIds, id) } - relinked, err := s.reconcileInboundLinks(tx, inboundId, inbound.NodeID, wantedFlow, wantedIds, detachEmails, prune) + relinked, detached, err := s.reconcileInboundLinks(tx, inboundId, inbound.NodeID, wantedFlow, wantedIds, detachEmails, prune) if err != nil { return err } @@ -354,22 +365,25 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ // A failed validation can roll back the row while the outer transaction commits. liftTombstonesOnCommit(tx, toCreate) + if node != nil { + node.detached = detached + } return nil } // reconcileInboundLinks writes only the client_inbounds rows that differ and returns -// their clients. prune also removes links absent from wantedFlow, as only a full sync may. -func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID *int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) { +// affected and detached client IDs. Only full sync prunes links absent from wantedFlow. +func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID *int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) (relinked, detached []int, err error) { var current []model.ClientInbound if prune { if err := tx.Where("inbound_id = ?", inboundId).Find(¤t).Error; err != nil { - return nil, err + return nil, nil, err } } else { for _, batch := range chunkInts(wantedIds, sqlInChunk) { var rows []model.ClientInbound if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).Find(&rows).Error; err != nil { - return nil, err + return nil, nil, err } current = append(current, rows...) } @@ -397,7 +411,7 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID for _, batch := range chunkStrings(detachEmails, sqlInChunk) { var ids []int if err := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).Pluck("id", &ids).Error; err != nil { - return nil, err + return nil, nil, err } for _, id := range ids { if _, keep := wantedFlow[id]; !keep { @@ -421,12 +435,12 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID // A restored, still-attached client must lose its legacy mark before it loses its link. if err := clearSyncOrphanMarks(tx, toDelete); err != nil { - return nil, err + return nil, nil, err } for _, batch := range chunkInts(toDelete, sqlInChunk) { if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch). Delete(&model.ClientInbound{}).Error; err != nil { - return nil, err + return nil, nil, err } } for flow, ids := range toUpdate { @@ -434,7 +448,7 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID if err := tx.Model(&model.ClientInbound{}). Where("inbound_id = ? AND client_id IN ?", inboundId, batch). Update("flow_override", flow).Error; err != nil { - return nil, err + return nil, nil, err } } } @@ -445,7 +459,7 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID Columns: []clause.Column{{Name: "client_id"}, {Name: "inbound_id"}}, DoUpdates: clause.AssignmentColumns([]string{"flow_override"}), }).CreateInBatches(toInsert, 200).Error; err != nil { - return nil, err + return nil, nil, err } if nodeID != nil { reattached := make([]int, 0, len(toInsert)) @@ -456,20 +470,20 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID emails := tx.Model(&model.ClientRecord{}).Select("email").Where("id IN ?", batch) if err := tx.Where("node_id = ? AND email IN (?)", *nodeID, emails). Delete(&model.NodePendingClientDelete{}).Error; err != nil { - return nil, err + return nil, nil, err } } } } - relinked := append([]int(nil), toDelete...) + relinked = append([]int(nil), toDelete...) for _, ids := range toUpdate { relinked = append(relinked, ids...) } for _, link := range toInsert { relinked = append(relinked, link.ClientId) } - return relinked, nil + return relinked, toDelete, nil } // keepLinkOwnedFields undoes the merge of the record fields one inbound cannot decide diff --git a/internal/web/service/client_sync_orphan.go b/internal/web/service/client_sync_orphan.go index 5e73d8b42..809e25ad8 100644 --- a/internal/web/service/client_sync_orphan.go +++ b/internal/web/service/client_sync_orphan.go @@ -25,13 +25,19 @@ func clientRecordExists(tx *gorm.DB, email string) bool { return n > 0 } -func markSyncOrphan(tx *gorm.DB, email string, nodeID int, nowMs int64) error { - if email == "" { - return nil +func markDetachedSyncOrphans(tx *gorm.DB, ids []int, nodeID int, nowMs int64) (bool, error) { + marked := false + for _, batch := range chunkInts(ids, sqlInChunk) { + result := tx.Model(&model.ClientRecord{}). + Where("id IN ? AND email <> '' AND sync_orphaned_at = 0", batch). + Where("NOT EXISTS (SELECT 1 FROM client_inbounds WHERE client_inbounds.client_id = clients.id)"). + Updates(map[string]any{"sync_orphaned_at": nowMs, "sync_orphaned_by": nodeID}) + if result.Error != nil { + return false, result.Error + } + marked = marked || result.RowsAffected > 0 } - return tx.Model(&model.ClientRecord{}). - Where("email = ? AND sync_orphaned_at = 0", email). - Updates(map[string]any{"sync_orphaned_at": nowMs, "sync_orphaned_by": nodeID}).Error + return marked, nil } // A client that is attached again is not orphaned, whatever an earlier merge diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index b80d7ea7b..269a2450e 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -1455,11 +1455,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi syncFailedInbounds := map[int]struct{}{} if !skipStructure || structuralChange { - type oldSet struct { - inboundID int - emails map[string]struct{} - } - var perInboundOld []oldSet + detached := make(map[int]struct{}) for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -1471,20 +1467,6 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if dirty { continue } - var oldEmailsRows []string - if err := tx.Table("clients"). - Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). - Where("client_inbounds.inbound_id = ?", c.Id). - Pluck("email", &oldEmailsRows).Error; err == nil { - oldEmails := make(map[string]struct{}, len(oldEmailsRows)) - for _, e := range oldEmailsRows { - if e != "" { - oldEmails[e] = struct{}{} - } - } - perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails}) - } - clients, gcErr := s.GetClients(snapIb) if gcErr != nil { logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr) @@ -1512,37 +1494,10 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi // A degraded node (reset/restart/removal) reports zero clients for an inbound the // hub populates; adopting it empties links and ReapSyncOrphans deletes shared clients (#6734). if _, degraded := degradedInbounds[c.Id]; degraded { - logger.Warningf("setRemoteTraffic: node %d reported zero clients for tag %q while the hub has %d attached — keeping them and re-pushing", nodeID, snapIb.Tag, len(oldEmailsRows)) + logger.Warningf("setRemoteTraffic: node %d reported zero clients for tag %q while the hub still has attached clients — keeping them and re-pushing", nodeID, snapIb.Tag) syncFailedInbounds[c.Id] = struct{}{} continue } - localEmails := make([]string, 0, len(filtered)) - for i := range filtered { - if filtered[i].Email != "" { - localEmails = append(localEmails, filtered[i].Email) - } - } - commentByEmail := make(map[string]string, len(localEmails)) - for _, batch := range chunkStrings(localEmails, sqlInChunk) { - var localMeta []struct { - Email string - Comment string `gorm:"column:comment"` - } - if err := tx.Table("clients"). - Select("email, comment"). - Where("email IN ?", batch). - Find(&localMeta).Error; err != nil { - continue - } - for _, m := range localMeta { - commentByEmail[m.Email] = m.Comment - } - } - for i := range filtered { - if cmt, ok := commentByEmail[filtered[i].Email]; ok { - filtered[i].Comment = cmt - } - } p, adopt := pendingAdopts[c.Id] _, isNew := newInboundIDs[c.Id] adoptedSettings := p.wireSettings @@ -1561,13 +1516,14 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } updates["settings"] = adoptedSettings } + var linkResult nodeInboundSyncResult rejected, err := withClientSyncSavepoint(tx, func() error { if len(updates) > 0 { if err := tx.Model(model.Inbound{}).Where("id = ?", c.Id).Updates(updates).Error; err != nil { return err } } - return s.clientService.SyncInbound(tx, c.Id, filtered) + return s.clientService.syncInboundClients(tx, c.Id, filtered, nil, true, &linkResult) }) if err != nil { return false, err @@ -1584,6 +1540,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if len(updates) > 0 { structuralChange = true } + for _, id := range linkResult.detached { + detached[id] = struct{}{} + } adoptedSettingsChanged = adoptedSettingsChanged || settingsChanged lifecycleLifted = lifecycleLifted || liftChanged // Stamp the un-lifted wire blob so reconciliation can push lifecycle lifts. @@ -1592,46 +1551,12 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } - for _, old := range perInboundOld { - // The sweep's premise is that links were just rebuilt from the snapshot, - // which is exactly what a failed SyncInbound violates. - if _, failed := syncFailedInbounds[old.inboundID]; failed { - continue - } - var stillAttached []string - if err := tx.Table("clients"). - Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). - Where("client_inbounds.inbound_id = ?", old.inboundID). - Pluck("email", &stillAttached).Error; err != nil { - continue - } - stillSet := make(map[string]struct{}, len(stillAttached)) - for _, e := range stillAttached { - stillSet[e] = struct{}{} - } - for email := range old.emails { - if _, kept := stillSet[email]; kept { - continue - } - var attachmentCount int64 - if err := tx.Table("client_inbounds"). - Joins("JOIN clients ON clients.id = client_inbounds.client_id"). - Where("clients.email = ?", email). - Count(&attachmentCount).Error; err != nil { - continue - } - if attachmentCount > 0 { - continue - } - // "Ended the merge unattached" is true for a real remote deletion and - // equally true for a bad merge, so record a strike instead of deleting. - if err := markSyncOrphan(tx, email, nodeID, now); err != nil { - logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err) - continue - } - structuralChange = true - } + // A client detached here may have been attached to another inbound by the same snapshot. + marked, err := markDetachedSyncOrphans(tx, slices.Sorted(maps.Keys(detached)), nodeID, now) + if err != nil { + return false, fmt.Errorf("mark node %d sync orphans: %w", nodeID, err) } + structuralChange = structuralChange || marked } if err := upsertNodeBaselines(tx, baselineChanges); err != nil { diff --git a/internal/web/service/node_full_reconciliation_test.go b/internal/web/service/node_full_reconciliation_test.go new file mode 100644 index 000000000..7ae3cce0d --- /dev/null +++ b/internal/web/service/node_full_reconciliation_test.go @@ -0,0 +1,336 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/config" + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestNodeFullReconciliationReusesLinkDiff(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + const nodeID = 1 + seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "remote", Address: "192.0.2.1", Port: 2053, Enable: true}) + createNodeInbound(t, db, nodeID, "remote-first", 41001) + createNodeInbound(t, db, nodeID, "remote-second", 41002) + var inbounds []model.Inbound + if err := db.Where("node_id = ?", nodeID).Order("id").Find(&inbounds).Error; err != nil { + t.Fatal(err) + } + keep := model.Client{Email: "keep@example.test", Enable: true, Comment: "remote comment"} + move := model.Client{Email: "move@example.test", Enable: true} + local := model.Client{Email: "still-local@example.test", Enable: true} + other := model.Client{Email: "still-on-other-node@example.test", Enable: true} + before := []model.Client{keep, move, local, other} + const dropped = sqlInChunk + 3 + for i := range dropped { + before = append(before, model.Client{Email: fmt.Sprintf("drop-%04d@example.test", i), Enable: true}) + } + clientSvc := &ClientService{} + localInbound := model.Inbound{UserId: 1, Tag: "local-inbound", Port: 41003, Protocol: model.VLESS, Enable: true} + if err := db.Create(&localInbound).Error; err != nil { + t.Fatal(err) + } + if err := clientSvc.SyncInbound(db, localInbound.Id, []model.Client{local}); err != nil { + t.Fatal(err) + } + const otherNodeID = 2 + seedNodeRow(t, db, &model.Node{Id: otherNodeID, Name: "other", Address: "192.0.2.2", Port: 2053, Enable: true}) + createNodeInboundWithClient(t, db, otherNodeID, "other-node-inbound", 41004, other.Email) + if err := clientSvc.SyncInbound(db, inbounds[0].Id, before); err != nil { + t.Fatal(err) + } + if err := clientSvc.SyncInbound(db, inbounds[1].Id, []model.Client{keep}); err != nil { + t.Fatal(err) + } + if err := db.Model(&model.ClientRecord{}).Where("email = ?", keep.Email). + UpdateColumn("comment", "operator note").Error; err != nil { + t.Fatal(err) + } + keep.LimitIP = 3 + last := model.Client{Email: "new@example.test", Enable: true, Comment: "imported note"} + wire := func(tag string, clients ...model.Client) *model.Inbound { + t.Helper() + raw, err := json.Marshal(map[string]any{"clients": clients}) + if err != nil { + t.Fatal(err) + } + return &model.Inbound{Tag: tag, Protocol: model.VLESS, Settings: string(raw)} + } + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + wire(inbounds[0].Tag, keep), wire(inbounds[1].Tag, keep, move, last), + }} + snap.Inbounds[0].ClientStats = []xray.ClientTraffic{{Email: keep.Email, Enable: true}} + queries := recordExecutedSQL(t, db) + const updateCallback = "test:record-node-reconciliation-updates" + if err := db.Callback().Update().After("gorm:update").Register(updateCallback, func(tx *gorm.DB) { + *queries = append(*queries, tx.Statement.SQL.String()) + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(updateCallback) }) + svc := &InboundService{} + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil { + t.Fatal(err) + } + markWrites := 0 + for _, sql := range *queries { + stmt := strings.ToLower(sql) + if strings.HasPrefix(stmt, "select email, comment ") || + (strings.Contains(stmt, "count(*)") && strings.Contains(stmt, "clients.email =")) { + t.Fatalf("reconciliation repeated a per-inbound comment or per-client attachment read: %s", sql) + } + if strings.HasPrefix(stmt, "update ") && strings.Contains(stmt, "sync_orphaned_by") && + strings.Contains(stmt, "not exists") { + markWrites++ + } + if strings.HasPrefix(stmt, "update ") && strings.Contains(stmt, "comment") { + t.Fatalf("remote reconciliation unnecessarily wrote the operator's comment: %s", sql) + } + } + if markWrites != 2 { + t.Fatalf("marked a %d-client drop in %d writes, want 2", dropped, markWrites) + } + var marked []model.ClientRecord + if err := db.Where("sync_orphaned_at > 0").Find(&marked).Error; err != nil { + t.Fatal(err) + } + if len(marked) != dropped { + t.Fatalf("marked %d removed clients, want %d", len(marked), dropped) + } + for _, row := range marked { + if row.SyncOrphanedBy != nodeID || !strings.HasPrefix(row.Email, "drop-") { + t.Fatalf("unexpected orphan: %q, node %d", row.Email, row.SyncOrphanedBy) + } + } + for email, want := range map[string]string{keep.Email: "operator note", last.Email: "imported note"} { + var row model.ClientRecord + if err := db.Where("email = ?", email).Take(&row).Error; err != nil || row.Comment != want { + t.Fatalf("comment for %q = %q, want %q (%v)", email, row.Comment, want, err) + } + } + var movedLinks []int + if err := db.Table("client_inbounds").Joins("JOIN clients ON clients.id = client_inbounds.client_id"). + Where("clients.email = ?", move.Email).Pluck("inbound_id", &movedLinks).Error; err != nil { + t.Fatal(err) + } + if len(movedLinks) != 1 || movedLinks[0] != inbounds[1].Id { + t.Fatalf("move lost its destination: %v", movedLinks) + } + snap.Inbounds[0].ClientStats = []xray.ClientTraffic{{Email: keep.Email, Up: 100, Down: 50, Enable: true}} + for range 2 { + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil { + t.Fatal(err) + } + } + baseline := model.NodeClientTraffic{} + if err := db.Where("node_id = ? AND email = ?", nodeID, keep.Email).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + traffic := readTraffic(t, db, keep.Email) + if baseline.Up != 100 || baseline.Down != 50 || traffic.Up != 100 || traffic.Down != 50 { + t.Fatalf("reapplied snapshot duplicated traffic or lost the baseline: traffic=%+v baseline=%+v", traffic, baseline) + } + if got := readOrphanMark(t, db, marked[0].Email); got != marked[0].SyncOrphanedAt { + t.Fatalf("replayed snapshot changed the orphan grace timestamp to %d", got) + } +} + +func TestNodeFullReconciliationRollsBackOrphanWriteFailure(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + const nodeID = 1 + const tag = "remote-inbound" + seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "remote", Address: "192.0.2.1", Port: 2053, Enable: true}) + svc := &InboundService{} + const keepEmail = "keep@example.test" + const oldSettings = `{"clients":[{"email":"keep@example.test","enable":true},{"email":"detached@example.test","enable":true}]}` + syncNodeWithSettings(t, svc, nodeID, tag, oldSettings, xray.ClientTraffic{Email: keepEmail, Enable: true, Up: 100}) + var oldInbound model.Inbound + if err := db.Where("tag = ?", tag).Take(&oldInbound).Error; err != nil { + t.Fatal(err) + } + + writeErr := errors.New("injected orphan write failure") + const callbackName = "test:fail-node-orphan-write" + if err := db.Callback().Update().Before("gorm:update").Register(callbackName, func(tx *gorm.DB) { + updates, ok := tx.Statement.Dest.(map[string]any) + if ok && tx.Statement.Table == "clients" && updates["sync_orphaned_by"] == nodeID { + _ = tx.AddError(writeErr) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callbackName) }) + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{ + Tag: tag, Settings: `{"clients":[{"email":"keep@example.test","enable":true}]}`, + ClientStats: []xray.ClientTraffic{{Email: keepEmail, Enable: true, Up: 160}}, + }}} + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); !errors.Is(err, writeErr) { + t.Fatalf("merge error = %v, want %v", err, writeErr) + } + var links int64 + if err := db.Model(&model.ClientInbound{}).Count(&links).Error; err != nil || links != 2 { + t.Fatalf("rollback left %d links, want 2 (%v)", links, err) + } + if mark := readOrphanMark(t, db, "detached@example.test"); mark != 0 { + t.Fatalf("rollback left orphan mark %d", mark) + } + var inbound model.Inbound + if err := db.First(&inbound, oldInbound.Id).Error; err != nil { + t.Fatal(err) + } + var baseline model.NodeClientTraffic + if err := db.Where("node_id = ? AND email = ?", nodeID, keepEmail).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + if inbound.Settings != oldInbound.Settings || baseline.Up != 100 || readTraffic(t, db, keepEmail).Up != 100 { + t.Fatalf("rollback leaked snapshot settings, counters or baseline: settings=%s baseline=%+v", inbound.Settings, baseline) + } +} + +func isolateNodeReconciliationDB(t *testing.T) { + t.Helper() + cleanup, err := testpg.IsolatePackage("node_reconciliation") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) +} + +func TestNodeFullReconciliationKeepsConcurrentCommentPostgres(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires concurrent PostgreSQL writes") + } + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + node := &model.Node{Enable: true, Name: "comment-test", Address: "192.0.2.1", Port: 2053} + seedNodeRow(t, db, node) + const email = "comment@example.test" + const tag = "remote-comment" + svc := &InboundService{} + syncNodeWithSettings(t, svc, node.Id, tag, clientsSettings(t, []model.Client{{Email: email, Enable: true, Comment: "old note"}})) + + read, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + var gate sync.Once + var wg sync.WaitGroup + const hook = "test:comment-after-reconcile-read" + if err := db.Callback().Update().Before("gorm:update").Register(hook, func(tx *gorm.DB) { + row, ok := tx.Statement.Dest.(*model.ClientRecord) + if ok && row.Email == email && row.LimitIP == 3 { + gate.Do(func() { close(read); <-release }) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + unblock() + wg.Wait() + _ = db.Callback().Update().Remove(hook) + }) + + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{ + Tag: tag, Protocol: model.VLESS, + Settings: clientsSettings(t, []model.Client{{Email: email, Enable: true, LimitIP: 3, Comment: "remote note"}}), + }}} + done := make(chan error, 1) + wg.Go(func() { + _, err := svc.SetRemoteTraffic(node.Id, snap, false, false) + done <- err + }) + select { + case <-read: + case err := <-done: + t.Fatalf("reconciliation never reached the client write barrier: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("blocked before reaching the client write barrier") + } + + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + if err := db.WithContext(ctx).Model(&model.ClientRecord{}).Where("email = ?", email). + UpdateColumn("comment", "concurrent master note").Error; err != nil { + t.Fatal(err) + } + unblock() + if err := <-done; err != nil { + t.Fatal(err) + } + var row model.ClientRecord + if err := db.Where("email = ?", email).Take(&row).Error; err != nil { + t.Fatal(err) + } + if row.Comment != "concurrent master note" || row.LimitIP != 3 { + t.Fatalf("reconciliation lost the note or did not apply the remote edit: comment=%q limitIP=%d", row.Comment, row.LimitIP) + } +} + +func TestNodeFullReconciliationExcludesRolledBackDetaches(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + node := &model.Node{Enable: true, Name: "savepoint-test", Address: "192.0.2.1", Port: 2053} + seedNodeRow(t, db, node) + svc := &InboundService{} + const rejectedTag = "rejected-inbound" + const acceptedTag = "accepted-inbound" + const rejectedEmail = "rejected@example.test" + const removedEmail = "removed@example.test" + keep := model.Client{Email: "keep@example.test", Enable: true} + initial := func(tag, email string, port int) *model.Inbound { + return &model.Inbound{ + Tag: tag, Port: port, Protocol: model.VLESS, Enable: true, + Settings: clientsSettings(t, []model.Client{keep, {Email: email, Enable: true}}), + } + } + original := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + initial(rejectedTag, rejectedEmail, 41010), initial(acceptedTag, removedEmail, 41011), + }} + if _, err := svc.SetRemoteTraffic(node.Id, original, false, false); err != nil { + t.Fatal(err) + } + var rejected model.Inbound + if err := db.Where("tag = ?", rejectedTag).Take(&rejected).Error; err != nil { + t.Fatal(err) + } + const hook = "test:reject-detach-after-delete" + rejectedDelete := false + if err := db.Callback().Delete().After("gorm:delete").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "client_inbounds" && len(tx.Statement.Vars) > 0 && + tx.Statement.Vars[0] == rejected.Id && tx.RowsAffected == 1 { + rejectedDelete = true + _ = tx.AddError(errors.New("injected failure after link deletion")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Delete().Remove(hook) }) + snapshot := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + {Tag: rejectedTag, Port: 41010, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{keep})}, + {Tag: acceptedTag, Port: 41011, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{keep})}, + }} + if _, err := svc.SetRemoteTraffic(node.Id, snapshot, false, false); err != nil { + t.Fatal(err) + } + if !rejectedDelete || readOrphanMark(t, db, rejectedEmail) != 0 || readOrphanMark(t, db, removedEmail) == 0 { + t.Fatalf("savepoint did not isolate orphan candidates: injected=%v", rejectedDelete) + } + var links int64 + if err := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", rejected.Id).Count(&links).Error; err != nil || links != 2 { + t.Fatalf("failed reconciliation did not restore its two memberships: %d (%v)", links, err) + } +} From 32e4b8bcfebc7b05e67bca6d3ddbf6375298c221 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 19:46:44 +0330 Subject: [PATCH 07/14] perf(ip-sync): batch node client IP attribution writes (#7347) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Batch changed node_client_ips rows in bounded deterministic 190-row statements with snapshot CAS, affected-row/replacement-ID checks, whole-GUID rollback and retry, insert-only RETURNING id and guarded pruning. Preserve exact timestamps, canonical no-op skipping, GUID scoping and flat IP-limit behavior. Integrate independent node polling with transactional reporter eligibility and identity fences. Avoid the reproduced PostgreSQL flat-IP/node ABBA cycle by ordering flat IP DML before reporter validation at commit; retain node-before-attribution ordering for GUID writes and node deletion. Prelock rename and bulk cleanup targets in byte order and reject stale email CAS attempts. Preserve SQLite immediate write transactions, ordered dispatch, durable deletion and existing traffic reconciliation. No network I/O under the new DB locks or global IP-sync serialization. Validation: all 12 CI jobs passed on c2831ca52f5099030758c46ed38d179022461653 (run 46915194728). PostgreSQL logs confirm delete/rename/bulk lock order, independent reporter progress, lifecycle rollback on disable/delete/endpoint/GUID changes, guarded prune, scanner enforcement and existing durable-delete/reconciliation regressions. Author reports RED SQLSTATE 40P01 on af77a55d, focused SQLite/PostgreSQL race tests, make verify and all four node E2E version pairings. Author-reported PostgreSQL 16 fixture: 552 -> 4 UPSERTs/round, unchanged 70,656 affected rows, merge p95 387.8–391.1 -> 72.3–81.4 ms, handler p95 16.9–19.5 -> 8.9–11.7 ms. Contention: 2 -> 0 observed deadlocks; corrected 192/192 reports succeeded. Loaded-host tails increased; idle-host repeats did not show a consistent material regression. WAL reduction and production latency improvement are not established. Monitor lock waits and CRUD tail latency separately. Fixes #7298 --- .github/workflows/ci.yml | 17 +- .../web/job/node_traffic_sync_ip_push_test.go | 257 +++++++++ internal/web/job/node_traffic_sync_job.go | 9 +- internal/web/service/client_bulk.go | 6 +- internal/web/service/client_inbound_apply.go | 9 +- .../service/client_ip_sync_postgres_test.go | 6 + internal/web/service/client_portable.go | 6 +- internal/web/service/client_sync_orphan.go | 2 +- internal/web/service/inbound.go | 11 +- internal/web/service/inbound_client_ips.go | 88 ++- internal/web/service/inbound_node_ips.go | 229 ++++++-- internal/web/service/node.go | 8 +- .../web/service/node_client_ips_batch_test.go | 410 ++++++++++++++ .../node_ip_lock_order_postgres_test.go | 534 ++++++++++++++++++ 14 files changed, 1512 insertions(+), 80 deletions(-) create mode 100644 internal/web/service/node_client_ips_batch_test.go create mode 100644 internal/web/service/node_ip_lock_order_postgres_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 767a5f045..3e9311d42 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -127,13 +127,24 @@ jobs: - name: PostgreSQL client IP sync regressions run: | set -o pipefail - go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner)?$' -count=1 -v | tee /tmp/postgres-client-ip-sync.log + go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner|Scheduler)?$' -count=1 -v | tee /tmp/postgres-client-ip-sync.log passed=$(grep -c -- '^--- PASS' /tmp/postgres-client-ip-sync.log || true) - if [ "$passed" -ne 2 ]; then - echo "expected 2 passing PostgreSQL client IP sync tests, got $passed" >&2 + if [ "$passed" -ne 3 ]; then + echo "expected 3 passing PostgreSQL client IP sync tests, got $passed" >&2 exit 1 fi + - name: PostgreSQL IP reporter lock order and lifecycle + run: | + set -o pipefail + go test ./internal/web/service -run '^TestPostgres(NodeIPReporterClientLockOrder|FlatIPReporterLifecycleCommit|PolledAttributionSurvivesConcurrentPrune)$' -count=1 -v | tee /tmp/postgres-ip-reporter-locks.log + for test in NodeIPReporterClientLockOrder FlatIPReporterLifecycleCommit PolledAttributionSurvivesConcurrentPrune; do + if ! grep -q -- "^--- PASS: TestPostgres${test} " /tmp/postgres-ip-reporter-locks.log; then + echo "expected PostgreSQL reporter test TestPostgres${test} to pass" >&2 + exit 1 + fi + done + - name: PostgreSQL Xray traffic retry run: | set -o pipefail diff --git a/internal/web/job/node_traffic_sync_ip_push_test.go b/internal/web/job/node_traffic_sync_ip_push_test.go index f847008a3..6f62c81a6 100644 --- a/internal/web/job/node_traffic_sync_ip_push_test.go +++ b/internal/web/job/node_traffic_sync_ip_push_test.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "os" "path/filepath" "slices" "strconv" @@ -14,11 +15,13 @@ import ( "time" "github.com/op/go-logging" + "gorm.io/gorm" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" "github.com/mhsanaei/3x-ui/v3/internal/database/model" xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" "github.com/mhsanaei/3x-ui/v3/internal/web/service" ) @@ -87,3 +90,257 @@ func TestNodeTrafficSyncPushesOnlyHostedClientIps(t *testing.T) { } } } + +func TestNodeTrafficSyncMergesFourOverlappingIPReports(t *testing.T) { + loggerInitOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) }) + isolateIPPollDatabase(t) + dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + db := database.GetDB() + + const email = "shared-ip@example.test" + const common = "198.51.100.1" + const size = 4 + const clientID = "00000001-0000-4000-8000-000000000000" + const subscriptionID = "shared-fixture" + settings := fmt.Sprintf(`{"clients":[{"email":%q,"id":%q,"subId":%q,"enable":true}],"decryption":"none"}`, email, clientID, subscriptionID) + now := time.Now().Unix() + arrived := make(chan int, size) + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + for i := range size { + guid := fmt.Sprintf("edge-%d", i) + port := 29500 + i + tag := fmt.Sprintf("in-%d", port) + entries := []model.ClientIpEntry{ + {IP: fmt.Sprintf("192.0.2.%d", i+1), Timestamp: now - int64(i)}, + {IP: common, Timestamp: now - int64(i)}, + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any = []any{} + switch { + case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + obj = []*model.Inbound{{Id: i + 1, Tag: tag, Port: port, Protocol: model.VLESS, Enable: true, Settings: settings}} + case strings.HasSuffix(r.URL.Path, "/server/clientIps") && r.Method == http.MethodGet: + encoded, _ := json.Marshal(entries) + obj = []model.InboundClientIps{{ClientEmail: email, Ips: string(encoded)}} + case strings.HasSuffix(r.URL.Path, "/clients/clientIpsByGuid"): + arrived <- i + select { + case <-release: + case <-r.Context().Done(): + return + } + obj = map[string]map[string][]model.ClientIpEntry{guid: {email: entries}, "unowned": {email: entries}} + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + host, rawPort, _ := strings.Cut(strings.TrimPrefix(server.URL, "http://"), ":") + httpPort, err := strconv.Atoi(rawPort) + if err != nil { + t.Fatal(err) + } + node := &model.Node{ + Name: guid, Guid: guid, Scheme: "http", Address: host, Port: httpPort, + BasePath: "/", ApiToken: "tok", Enable: true, Status: "online", AllowPrivateAddress: true, + } + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + // A node is not allowed to claim a client attached only to another node. + // Establish the shared membership on the hub before any node reports it. + inbound := &model.Inbound{ + NodeID: &node.Id, UserId: 1, Port: port, Tag: tag, Protocol: model.VLESS, Enable: true, Settings: settings, + } + if err := db.Create(inbound).Error; err != nil { + t.Fatal(err) + } + if err := (&service.ClientService{}).SyncInbound(db, inbound.Id, []model.Client{ + {Email: email, ID: clientID, SubID: subscriptionID, Enable: true}, + }); err != nil { + t.Fatal(err) + } + } + + job := NewNodeTrafficSyncJob() + t.Cleanup(func() { unblock(); job.Close() }) + job.Run() + deadline := time.After(5 * time.Second) + for range size { + select { + case <-arrived: + case <-deadline: + t.Fatal("four independent polls did not reach the attribution endpoint together") + } + } + unblock() + job.workers.Wait() + + var flat model.InboundClientIps + if err := db.Where("client_email = ?", email).First(&flat).Error; err != nil { + t.Fatal(err) + } + var flatEntries []model.ClientIpEntry + if err := json.Unmarshal([]byte(flat.Ips), &flatEntries); err != nil { + t.Fatal(err) + } + wantFlat := map[string]int64{common: now} + for i := range size { + wantFlat[fmt.Sprintf("192.0.2.%d", i+1)] = now - int64(i) + } + for _, entry := range flatEntries { + if want, ok := wantFlat[entry.IP]; !ok || want != entry.Timestamp { + t.Fatalf("unexpected flat IP entry %+v (all entries %v, remaining expected %v)", entry, flatEntries, wantFlat) + } + delete(wantFlat, entry.IP) + } + if len(wantFlat) != 0 { + t.Fatalf("flat IP union missing %v", wantFlat) + } + tree, err := (&service.InboundService{}).GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if len(tree) != size { + t.Fatalf("expected %d scoped GUIDs, got %+v", size, tree) + } + for i := range size { + entries := tree[fmt.Sprintf("edge-%d", i)][email] + want := fmt.Sprintf("192.0.2.%d", i+1) + if len(entries) != 2 || !slices.Contains(entries, model.ClientIpEntry{IP: want, Timestamp: now - int64(i)}) { + t.Fatalf("wrong attribution for edge %d: %+v", i, entries) + } + } +} + +func TestClientIpSyncPostgresScheduler(t *testing.T) { + if os.Getenv("XUI_DB_TYPE") != "postgres" || os.Getenv("XUI_DB_DSN") == "" { + t.Skip("requires PostgreSQL") + } + t.Run("overlapping reports", TestNodeTrafficSyncMergesFourOverlappingIPReports) + t.Run("obsolete reports", TestNodeTrafficSyncDropsObsoleteIPReport) +} + +func TestNodeTrafficSyncDropsObsoleteIPReport(t *testing.T) { + loggerInitOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) }) + for _, stage := range []string{"disable during flat fetch", "disable during attribution fetch", "delete after attribution read"} { + t.Run(stage, func(t *testing.T) { + isolateIPPollDatabase(t) + dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + db := database.GetDB() + + const email = "late-ip@example.test" + const tag = "in-29444" + const guid = "ip-reporter" + seen, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + now := time.Now().Unix() + entry := model.ClientIpEntry{IP: "192.0.2.40", Timestamp: now} + settings := fmt.Sprintf(`{"clients":[{"email":%q,"id":"00000001-0000-4000-8000-000000000000","enable":true}],"decryption":"none"}`, email) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any = []any{} + switch { + case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + obj = []*model.Inbound{{Id: 1, Tag: tag, Port: 29444, Protocol: model.VLESS, Enable: true, Settings: settings}} + case strings.HasSuffix(r.URL.Path, "/server/clientIps") && r.Method == http.MethodGet && stage == "disable during flat fetch": + close(seen) + select { + case <-release: + case <-r.Context().Done(): + return + } + obj = []model.InboundClientIps{{ClientEmail: email, Ips: fmt.Sprintf(`[{"ip":%q,"timestamp":%d}]`, entry.IP, now)}} + case strings.HasSuffix(r.URL.Path, "/clients/clientIpsByGuid"): + if stage == "disable during attribution fetch" { + close(seen) + select { + case <-release: + case <-r.Context().Done(): + return + } + } + obj = map[string]map[string][]model.ClientIpEntry{guid: {email: {entry}}} + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + host, port, _ := strings.Cut(strings.TrimPrefix(server.URL, "http://"), ":") + portNum, err := strconv.Atoi(port) + if err != nil { + t.Fatal(err) + } + node := &model.Node{ + Name: guid, Guid: guid, Scheme: "http", Address: host, Port: portNum, + BasePath: "/", ApiToken: "tok", Enable: true, Status: "online", AllowPrivateAddress: true, + } + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + + const hook = "test:park-obsolete-attribution" + if stage == "delete after attribution read" { + park := sync.OnceFunc(func() { close(seen); <-release }) + if err := db.Callback().Query().After("gorm:query").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "node_client_ips" { + park() + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(hook) }) + } + job := NewNodeTrafficSyncJob() + t.Cleanup(func() { unblock(); job.Close() }) + job.Run() + select { + case <-seen: + case <-time.After(3 * time.Second): + t.Fatal("IP sync did not reach the requested barrier") + } + + svc := &service.NodeService{} + if stage == "delete after attribution read" { + if err := db.Model(&model.Inbound{}).Where("node_id = ?", node.Id).Update("node_id", nil).Error; err != nil { + t.Fatal(err) + } + if err := svc.Delete(node.Id); err != nil { + t.Fatal(err) + } + } else if err := svc.SetEnable(node.Id, false); err != nil { + t.Fatal(err) + } + unblock() + job.workers.Wait() + var attribution, flat int64 + if err := db.Model(&model.NodeClientIp{}).Where("email = ?", email).Count(&attribution).Error; err != nil { + t.Fatal(err) + } + if err := db.Model(&model.InboundClientIps{}).Where("client_email = ?", email).Count(&flat).Error; err != nil { + t.Fatal(err) + } + if attribution != 0 || flat != 0 { + t.Fatalf("obsolete poll persisted attribution=%d flat=%d", attribution, flat) + } + }) + } +} + +func isolateIPPollDatabase(t *testing.T) { + t.Helper() + if os.Getenv("XUI_DB_TYPE") != "postgres" { + return + } + cleanup, err := testpg.IsolatePackage("job_ip_poll") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) +} diff --git a/internal/web/job/node_traffic_sync_job.go b/internal/web/job/node_traffic_sync_job.go index 5dee54ab4..f86fc0934 100644 --- a/internal/web/job/node_traffic_sync_job.go +++ b/internal/web/job/node_traffic_sync_job.go @@ -2,6 +2,7 @@ package job import ( "context" + "errors" "maps" "strings" "sync" @@ -655,7 +656,10 @@ func (j *NodeTrafficSyncJob) syncOne(pollCtx context.Context, mgr *runtime.Manag nodeIps, err := rt.FetchAllClientIps(ipCtx) if err == nil && len(nodeIps) > 0 { - if err := j.inboundService.MergeNodeClientIps(n.Id, nodeIps); err != nil { + if err := j.inboundService.MergePolledNodeClientIps(ipCtx, n, nodeIps); err != nil { + if errors.Is(err, service.ErrIneligibleNodeIPReport) { + return + } logger.Warningf("node traffic sync: merge client ips from %s failed: %v", n.Name, err) } } else if err != nil { @@ -688,7 +692,8 @@ func (j *NodeTrafficSyncJob) syncOne(pollCtx context.Context, mgr *runtime.Manag } else { j.noGuidIpEndpoint.Delete(n.Id) if len(guidTrees) > 0 { - if err := j.inboundService.MergeClientIpsByGuid(n, guidTrees); err != nil { + if err := j.inboundService.MergePolledClientIpsByGuid(ipCtx, n, guidTrees); err != nil && + !errors.Is(err, service.ErrIneligibleNodeIPReport) { logger.Warningf("node traffic sync: merge client ip attribution from %s failed: %v", n.Name, err) } } diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index 371a1cd88..585689177 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -1021,9 +1021,9 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil { return e } - if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil { - return e - } + } + if e := inboundSvc.delClientIPsByEmails(tx, successEmails); e != nil { + return e } } for _, batch := range chunkInts(successIds, sqlInChunk) { diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index f805aa233..ca0746a39 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -251,14 +251,12 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId // Persist the batch deletion atomically, serialized against the traffic poll // to avoid the cross-transaction lock-order deadlock (runSerializedTx). if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { + var purgeIPs []string for _, t := range targets { if t.emailShared || keepTraffic { continue } - if e := inboundSvc.DelClientIPs(tx, t.email); e != nil { - logger.Error("Error in delete client IPs") - return e - } + purgeIPs = append(purgeIPs, t.email) if len(t.email) > 0 { if e := inboundSvc.DelClientStat(tx, t.email); e != nil { logger.Error("Delete stats Data Error") @@ -266,6 +264,9 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId } } } + if e := inboundSvc.delClientIPsByEmails(tx, purgeIPs); e != nil { + return e + } if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil { return e } diff --git a/internal/web/service/client_ip_sync_postgres_test.go b/internal/web/service/client_ip_sync_postgres_test.go index 7fc575313..cec89d4d4 100644 --- a/internal/web/service/client_ip_sync_postgres_test.go +++ b/internal/web/service/client_ip_sync_postgres_test.go @@ -21,6 +21,12 @@ func TestClientIpSyncPostgres(t *testing.T) { {"exhaustion rollback", TestClientIpSyncCASExhaustionRollsBack}, {"concurrent writer", TestMergeInboundClientIps_RetriesAfterConcurrentWriter}, {"attribution unchanged", TestNodeClientIpCanonicalUnchangedSkipsUpsert}, + {"attribution batched refresh", TestNodeClientIpRefreshBatchesWrites}, + {"attribution concurrent merge", TestNodeClientIpBatchRetriesConcurrentChange}, + {"attribution rollback", TestNodeClientIpBatchRollsBackOnLaterFailure}, + {"shared descendant writers", TestConcurrentPolledReportsMergeMixedRowsForSharedDescendant}, + {"later CAS conflicts", TestNodeClientIpLaterBatchCASRollsBackBeforeRetry}, + {"attribution concurrent prune", TestPruneNodeClientIpsPreservesConcurrentRefresh}, {"remote ids", TestMergeInboundClientIps_CreatesNodeOnlyRowIgnoringRemoteId}, {"attribution round trip", TestRecordLocalClientIps_RoundTripByGuid}, {"attribution expiry", TestRecordLocalClientIps_MergesAndDropsStale}, diff --git a/internal/web/service/client_portable.go b/internal/web/service/client_portable.go index 64c258a9c..a102212c7 100644 --- a/internal/web/service/client_portable.go +++ b/internal/web/service/client_portable.go @@ -314,9 +314,9 @@ func (s *ClientService) DeleteOrphans() (int, error) { if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil { return e } - if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil { - return e - } + } + if e := (&InboundService{}).delClientIPsByEmails(tx, emails); e != nil { + return e } if e := clearGlobalTraffic(tx, emails...); e != nil { return e diff --git a/internal/web/service/client_sync_orphan.go b/internal/web/service/client_sync_orphan.go index 809e25ad8..4010cc0ad 100644 --- a/internal/web/service/client_sync_orphan.go +++ b/internal/web/service/client_sync_orphan.go @@ -101,7 +101,7 @@ func (s *ClientService) ReapSyncOrphans() (int, error) { if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil { return err } - return tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error + return (&InboundService{}).delClientIPsByEmails(tx, batch) }); err != nil { return reaped, err } diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 1d9c194db..9097b5664 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -2631,6 +2631,7 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, inboundId int, oldCli // Drop stats rows for removed emails — but not when a sibling inbound // still references the email, since the row is the shared accumulator. + var removedIPs []string for i := range oldClients { email := oldClients[i].Email if email == "" { @@ -2649,11 +2650,11 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, inboundId int, oldCli if err := s.DelClientStat(tx, email); err != nil { return err } - // Keep inbound_client_ips in sync when the inbound edit drops an - // email, so the IP-limit job doesn't keep a ghost tracking row (#4963). - if err := s.DelClientIPs(tx, email); err != nil { - return err - } + removedIPs = append(removedIPs, email) + } + // The IP-limit job must not keep tracking removed clients (#4963). + if err := s.delClientIPsByEmails(tx, removedIPs); err != nil { + return err } keptEmails := make([]string, 0, len(newClients)) keptClients := make(map[string]*model.Client, len(newClients)) diff --git a/internal/web/service/inbound_client_ips.go b/internal/web/service/inbound_client_ips.go index 82c3e80dc..42e5082f0 100644 --- a/internal/web/service/inbound_client_ips.go +++ b/internal/web/service/inbound_client_ips.go @@ -1,8 +1,11 @@ package service import ( + "context" "encoding/json" + "errors" "fmt" + "slices" "sort" "time" @@ -76,7 +79,10 @@ func mergeClientIpEntries(old, incoming []model.ClientIpEntry, cutoff int64) []m // MergeInboundClientIps unions remote observations without losing concurrent scanner writes. func (s *InboundService) MergeInboundClientIps(incomingIps []model.InboundClientIps) error { - db := database.GetDB() + return mergeInboundClientIps(database.GetDB(), nil, incomingIps) +} + +func mergeInboundClientIps(db *gorm.DB, reporter *model.Node, incomingIps []model.InboundClientIps) error { var currentIps []model.InboundClientIps if err := db.Model(&model.InboundClientIps{}).Find(¤tIps).Error; err != nil { return err @@ -96,6 +102,15 @@ func (s *InboundService) MergeInboundClientIps(incomingIps []model.InboundClient }) tx := db.Begin() + if tx.Error != nil { + return tx.Error + } + if reporter != nil && tx.Name() != database.DialectPostgres { + if err := lockOnlineNodeIPReporter(tx, reporter); err != nil { + tx.Rollback() + return err + } + } defer func() { if r := recover(); r != nil { tx.Rollback() @@ -134,6 +149,9 @@ func (s *InboundService) MergeInboundClientIps(incomingIps []model.InboundClient } current = &model.InboundClientIps{} if err := tx.Where("client_email = ?", incoming.ClientEmail).First(current).Error; err != nil { + if reporter != nil && errors.Is(err, gorm.ErrRecordNotFound) { + continue + } tx.Rollback() return err } @@ -142,7 +160,21 @@ func (s *InboundService) MergeInboundClientIps(incomingIps []model.InboundClient // check_client_ip_job rewrites this blob too; an unconditional Update loses // whichever writer commits second and its remote IPs with it (#6587). - if err := mergeExistingClientIps(tx, current, incomingEntries, cutoff); err != nil { + err := mergeExistingClientIps(tx, current, incomingEntries, cutoff, reporter != nil) + // The observation belongs to the email in the report. A concurrent + // delete or rename can remove it while the poll waits for the row. + if reporter != nil && errors.Is(err, gorm.ErrRecordNotFound) { + continue + } + if err != nil { + tx.Rollback() + return err + } + } + // Client mutations lock flat IP rows before marking the node dirty. + // Take the PostgreSQL reporter lock last and roll back obsolete reports. + if reporter != nil && tx.Name() == database.DialectPostgres { + if err := lockOnlineNodeIPReporter(tx, reporter); err != nil { tx.Rollback() return err } @@ -167,7 +199,12 @@ func CasUpdateInboundClientIps(tx *gorm.DB, id int, expectedIps, newIps string) } // Seed the first CAS from the preload; only a competing write requires a re-read. -func mergeExistingClientIps(tx *gorm.DB, current *model.InboundClientIps, incoming []model.ClientIpEntry, cutoff int64) error { +func mergeExistingClientIps(tx *gorm.DB, current *model.InboundClientIps, incoming []model.ClientIpEntry, cutoff int64, polled bool) error { + if polled { + // Keep the observed email in every CAS attempt even if the ID is + // still present after a concurrent rename. + tx = tx.Where("client_email = ?", current.ClientEmail).Session(&gorm.Session{}) + } for attempt := range ClientIpCasRetries { var oldEntries []model.ClientIpEntry if current.Ips != "" { @@ -199,6 +236,11 @@ func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail // The caller only renames onto a free identity, so a row already sitting on // newEmail is stale tracking data — drop it instead of failing the edit. if oldEmail != newEmail { + if tx.Name() == database.DialectPostgres { + if _, err := lockFlatClientIPRows(tx, []string{oldEmail, newEmail}); err != nil { + return err + } + } if err := tx.Where("client_email = ?", newEmail).Delete(model.InboundClientIps{}).Error; err != nil { return err } @@ -212,15 +254,40 @@ func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error { func (s *InboundService) delClientIPsByEmails(tx *gorm.DB, emails []string) error { const chunk = 400 + postgres := tx.Name() == database.DialectPostgres + if postgres { + emails = slices.Clone(emails) + slices.Sort(emails) + } for start := 0; start < len(emails); start += chunk { end := min(start+chunk, len(emails)) - if err := tx.Where("client_email IN ?", emails[start:end]).Delete(model.InboundClientIps{}).Error; err != nil { + query := tx.Where("client_email IN ?", emails[start:end]) + if postgres { + ids, err := lockFlatClientIPRows(tx, emails[start:end]) + if err != nil { + return err + } + if len(ids) == 0 { + continue + } + query = tx.Where("id IN ?", ids) + } + if err := query.Delete(model.InboundClientIps{}).Error; err != nil { return err } } return nil } +// Acquire flat IP row locks in the same byte order as the scanner and poller. +// The planner may visit a multi-row DELETE's targets in heap order instead. +func lockFlatClientIPRows(tx *gorm.DB, emails []string) ([]int, error) { + var ids []int + err := tx.Model(&model.InboundClientIps{}).Where("client_email IN ?", emails). + Order(`client_email COLLATE "C"`).Clauses(clause.Locking{Strength: "UPDATE"}).Pluck("id", &ids).Error + return ids, err +} + func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) { db := database.GetDB() InboundClientIps := &model.InboundClientIps{} @@ -326,7 +393,16 @@ func nodeAttachedEmails(db *gorm.DB, nodeID int) (map[string]struct{}, error) { // MergeNodeClientIps merges one node's flat client-IP report, cut to the node's clients. func (s *InboundService) MergeNodeClientIps(nodeID int, rows []model.InboundClientIps) error { - attached, err := nodeAttachedEmails(database.GetDB(), nodeID) + return mergeNodeClientIps(database.GetDB(), nil, nodeID, rows) +} + +// MergePolledNodeClientIps preserves the flat union with an online reporter fence. +func (s *InboundService) MergePolledNodeClientIps(ctx context.Context, node *model.Node, rows []model.InboundClientIps) error { + return mergeNodeClientIps(database.GetDB().WithContext(ctx), node, node.Id, rows) +} + +func mergeNodeClientIps(db *gorm.DB, reporter *model.Node, nodeID int, rows []model.InboundClientIps) error { + attached, err := nodeAttachedEmails(db, nodeID) if err != nil { return err } @@ -347,7 +423,7 @@ func (s *InboundService) MergeNodeClientIps(nodeID int, rows []model.InboundClie if len(kept) == 0 { return nil } - return s.MergeInboundClientIps(kept) + return mergeInboundClientIps(db, reporter, kept) } // clampClientIpEntries caps reported timestamps at now: a future-dated entry would never diff --git a/internal/web/service/inbound_node_ips.go b/internal/web/service/inbound_node_ips.go index 76f75fd46..b3eb2767c 100644 --- a/internal/web/service/inbound_node_ips.go +++ b/internal/web/service/inbound_node_ips.go @@ -2,7 +2,9 @@ package service import ( "cmp" + "context" "encoding/json" + "errors" "slices" "sort" "time" @@ -45,26 +47,28 @@ func mergeModelClientIpEntries(old, incoming []model.ClientIpEntry, cutoff int64 return out } -// upsertNodeClientIps merges fresh observations per (guid, email). -// Empty results delete attribution instead of retaining expired rows. +// Stay under SQLite's 999-parameter limit with up to five binds per row, +// including the compare-and-set predicate. +const nodeClientIpWriteBatch = 190 + +var errNodeClientIpConflict = errors.New("node client IP attribution changed during merge") + +type nodeClientIpChange struct { + email string + ips string + previous *model.NodeClientIp +} + +// upsertNodeClientIps merges fresh observations in email order and retries +// the whole GUID after a concurrent write so no partial merge is committed. func upsertNodeClientIps(guid string, perEmail map[string][]model.ClientIpEntry) error { + return mergeNodeClientIpAttribution(database.GetDB(), nil, guid, perEmail) +} + +func mergeNodeClientIpAttribution(db *gorm.DB, reporter *model.Node, guid string, perEmail map[string][]model.ClientIpEntry) error { if guid == "" || len(perEmail) == 0 { return nil } - db := database.GetDB() - cutoff := time.Now().Unix() - clientIpStaleAfterSeconds - - var existing []model.NodeClientIp - if err := db.Where("node_guid = ?", guid).Find(&existing).Error; err != nil { - return err - } - existingByEmail := make(map[string]*model.NodeClientIp, len(existing)) - for i := range existing { - existingByEmail[existing[i].Email] = &existing[i] - } - - // Deterministic row order keeps concurrent guid merges from deadlocking on - // Postgres (40P01) — same discipline as MergeInboundClientIps. emails := make([]string, 0, len(perEmail)) for email := range perEmail { if email != "" { @@ -73,45 +77,153 @@ func upsertNodeClientIps(guid string, perEmail map[string][]model.ClientIpEntry) } sort.Strings(emails) - tx := db.Begin() - defer func() { - if r := recover(); r != nil { - tx.Rollback() + cutoff := time.Now().Unix() - clientIpStaleAfterSeconds + for range ClientIpCasRetries { + changes, err := planNodeClientIpChanges(db, guid, emails, perEmail, cutoff) + if err != nil || len(changes) == 0 { + return err } - }() - - for _, email := range emails { - incoming := perEmail[email] - var old []model.ClientIpEntry - if cur, ok := existingByEmail[email]; ok && cur.Ips != "" { - _ = json.Unmarshal([]byte(cur.Ips), &old) - } - merged := mergeModelClientIpEntries(old, incoming, cutoff) - if len(merged) == 0 { - // Nothing fresh: drop any stale row so attribution doesn't linger. - if _, ok := existingByEmail[email]; ok { - if err := tx.Where("node_guid = ? AND email = ?", guid, email). - Delete(&model.NodeClientIp{}).Error; err != nil { - tx.Rollback() + err = db.Transaction(func(tx *gorm.DB) error { + if reporter != nil { + if err := lockOnlineNodeIPReporter(tx, reporter); err != nil { return err } } - continue - } - encoded, _ := model.MarshalClientIpEntries(merged) - if current := existingByEmail[email]; current != nil && current.Ips == encoded { - continue - } - row := model.NodeClientIp{NodeGuid: guid, Email: email, Ips: encoded} - if err := tx.Clauses(clause.OnConflict{ - Columns: []clause.Column{{Name: "node_guid"}, {Name: "email"}}, - DoUpdates: clause.AssignmentColumns([]string{"ips"}), - }).Create(&row).Error; err != nil { - tx.Rollback() + return applyNodeClientIpChanges(tx, guid, changes) + }) + if !errors.Is(err, errNodeClientIpConflict) { return err } } - return tx.Commit().Error + return errNodeClientIpConflict +} + +func planNodeClientIpChanges(db *gorm.DB, guid string, emails []string, perEmail map[string][]model.ClientIpEntry, cutoff int64) ([]nodeClientIpChange, error) { + var existing []model.NodeClientIp + if err := db.Where("node_guid = ?", guid).Find(&existing).Error; err != nil { + return nil, err + } + existingByEmail := make(map[string]*model.NodeClientIp, len(existing)) + for i := range existing { + existingByEmail[existing[i].Email] = &existing[i] + } + + changes := make([]nodeClientIpChange, 0, len(emails)) + for _, email := range emails { + previous := existingByEmail[email] + var old []model.ClientIpEntry + if previous != nil && previous.Ips != "" { + _ = json.Unmarshal([]byte(previous.Ips), &old) + } + merged := mergeModelClientIpEntries(old, perEmail[email], cutoff) + if len(merged) == 0 { + if previous != nil { + changes = append(changes, nodeClientIpChange{email: email, previous: previous}) + } + continue + } + encoded, err := model.MarshalClientIpEntries(merged) + if err != nil { + return nil, err + } + if previous == nil || previous.Ips != encoded { + changes = append(changes, nodeClientIpChange{email: email, ips: encoded, previous: previous}) + } + } + return changes, nil +} + +func applyNodeClientIpChanges(tx *gorm.DB, guid string, changes []nodeClientIpChange) error { + for start := 0; start < len(changes); { + deleting := changes[start].ips == "" + end := start + 1 + // A multi-row DELETE does not guarantee row-lock order on PostgreSQL. + for !deleting && end < min(start+nodeClientIpWriteBatch, len(changes)) && changes[end].ips != "" { + end++ + } + batch := changes[start:end] + expected := make([]clause.Expression, 0, len(batch)) + previousIDs := make(map[string]int, len(batch)) + for _, change := range batch { + if change.previous != nil { + expected = append(expected, nodeClientIpSnapshot(*change.previous)) + previousIDs[change.email] = change.previous.Id + } + } + var result *gorm.DB + var rows []model.NodeClientIp + if deleting { + result = tx.Where(expected[0]).Delete(&model.NodeClientIp{}) + } else { + rows = make([]model.NodeClientIp, 0, len(batch)) + for _, change := range batch { + rows = append(rows, model.NodeClientIp{NodeGuid: guid, Email: change.email, Ips: change.ips}) + } + conflict := clause.OnConflict{ + Columns: []clause.Column{{Name: "node_guid"}, {Name: "email"}}, + DoNothing: len(expected) == 0, + } + // For DO NOTHING, GORM skips nonzero RETURNING fields in the + // input slice. Only the generated ID starts out unset. + returning := clause.Returning{Columns: []clause.Column{{Name: "id"}}} + if !conflict.DoNothing { + conflict.DoUpdates = clause.AssignmentColumns([]string{"ips"}) + conflict.Where = clause.Where{Exprs: []clause.Expression{clause.Or(expected...)}} + returning.Columns = append(returning.Columns, clause.Column{Name: "email"}) + } + result = tx.Clauses(conflict, returning).Create(&rows) + } + if result.Error != nil { + return result.Error + } + if result.RowsAffected != int64(len(batch)) { + return errNodeClientIpConflict + } + // An existing row can be deleted after the read. A replacement ID + // requires a retry so the new row cannot inherit the deleted IPs. + for _, row := range rows { + if id, existed := previousIDs[row.Email]; existed && row.Id != id { + return errNodeClientIpConflict + } + } + start = end + } + return nil +} + +func nodeClientIpSnapshot(row model.NodeClientIp) clause.Expression { + id := clause.Column{Table: clause.CurrentTable, Name: "id"} + ips := clause.Column{Table: clause.CurrentTable, Name: "ips"} + content := clause.Expression(clause.Eq{Column: ips, Value: row.Ips}) + if row.Ips == "" { + content = clause.Or(content, clause.Eq{Column: ips, Value: nil}) + } + return clause.And(clause.Eq{Column: id, Value: row.Id}, content) +} + +// ErrIneligibleNodeIPReport identifies work invalidated while in flight. +var ErrIneligibleNodeIPReport = errors.New("node IP report is no longer eligible") + +// Keep the reporter stable through commit. The flat PostgreSQL merge calls +// this after its IP writes. Attribution and node deletion lock the node first. +func lockOnlineNodeIPReporter(tx *gorm.DB, reporter *model.Node) error { + var current model.Node + query := tx.Select("id", "guid", "scheme", "address", "port", "base_path"). + Where("id = ? AND enable = ? AND status = ?", reporter.Id, true, "online") + if tx.Name() == database.DialectPostgres { + query = query.Clauses(clause.Locking{Strength: "SHARE"}) + } + if err := query.Take(¤t).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return ErrIneligibleNodeIPReport + } + return err + } + if current.Guid != reporter.Guid || current.Scheme != reporter.Scheme || current.Address != reporter.Address || + current.Port != reporter.Port || current.BasePath != reporter.BasePath { + return ErrIneligibleNodeIPReport + } + return nil } // RecordLocalClientIps stores the scanner's local observations under this panel's GUID. @@ -127,6 +239,15 @@ func (s *InboundService) RecordLocalClientIps(panelGuid string, observed map[str // clones don't collapse into one attribution row; descendant subtrees keep their // distinct GUIDs. A nil node merges the report verbatim. func (s *InboundService) MergeClientIpsByGuid(node *model.Node, trees map[string]map[string][]model.ClientIpEntry) error { + return mergeClientIpsByGuid(database.GetDB(), node, trees, false) +} + +// MergePolledClientIpsByGuid commits a node report only while its reporter is eligible. +func (s *InboundService) MergePolledClientIpsByGuid(ctx context.Context, node *model.Node, trees map[string]map[string][]model.ClientIpEntry) error { + return mergeClientIpsByGuid(database.GetDB().WithContext(ctx), node, trees, true) +} + +func mergeClientIpsByGuid(db *gorm.DB, node *model.Node, trees map[string]map[string][]model.ClientIpEntry, checkReporter bool) error { if node != nil && node.Guid != "" { if eff := effectiveNodeKey(node); eff != node.Guid { if sub, ok := trees[node.Guid]; ok { @@ -142,18 +263,22 @@ func (s *InboundService) MergeClientIpsByGuid(node *model.Node, trees map[string } } if node != nil { - scoped, err := scopeNodeClientIps(database.GetDB(), node, trees) + scoped, err := scopeNodeClientIps(db, node, trees) if err != nil { return err } trees = scoped } + var reporter *model.Node + if checkReporter { + reporter = node + } for guid, perEmail := range trees { // Stored once per email: an oversized key would multiply into every row. if len(guid) > maxPanelGuidLen { continue } - if err := upsertNodeClientIps(guid, perEmail); err != nil { + if err := mergeNodeClientIpAttribution(db, reporter, guid, perEmail); err != nil { return err } } @@ -329,7 +454,7 @@ func pruneStaleNodeClientIps(cutoff int64) error { } kept := mergeModelClientIpEntries(nil, entries, cutoff) if len(kept) == 0 { - if err := db.Delete(&model.NodeClientIp{}, row.Id).Error; err != nil { + if err := db.Where(nodeClientIpSnapshot(row)).Delete(&model.NodeClientIp{}).Error; err != nil { return err } continue @@ -338,7 +463,7 @@ func pruneStaleNodeClientIps(cutoff int64) error { continue } encoded, _ := model.MarshalClientIpEntries(kept) - if err := db.Model(&model.NodeClientIp{}).Where("id = ?", row.Id).Update("ips", encoded).Error; err != nil { + if err := db.Model(&model.NodeClientIp{}).Where(nodeClientIpSnapshot(row)).Update("ips", encoded).Error; err != nil { return err } } diff --git a/internal/web/service/node.go b/internal/web/service/node.go index bac491ed1..f24b6c618 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -29,6 +29,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/xray" "gorm.io/gorm" + "gorm.io/gorm/clause" ) type HeartbeatPatch struct { @@ -861,7 +862,12 @@ func (s *NodeService) Delete(id int) error { return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached)) } var n model.Node - if err := tx.Select("guid").Where("id = ?", id).First(&n).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + // Match the attribution reporter's node-before-attribution order. + reporter := tx.Select("guid").Where("id = ?", id) + if tx.Name() == database.DialectPostgres { + reporter = reporter.Clauses(clause.Locking{Strength: "UPDATE"}) + } + if err := reporter.First(&n).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return err } if err := tx.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil { diff --git a/internal/web/service/node_client_ips_batch_test.go b/internal/web/service/node_client_ips_batch_test.go new file mode 100644 index 000000000..b808bc8a6 --- /dev/null +++ b/internal/web/service/node_client_ips_batch_test.go @@ -0,0 +1,410 @@ +package service + +import ( + "errors" + "fmt" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestNodeClientIpRefreshBatchesWrites(t *testing.T) { + setupClientIpTestDB(t) + const clients = 552 + const guid = "edge" + now := time.Now().Unix() + report := make(map[string][]model.ClientIpEntry, clients) + for i := range clients { + report[fmt.Sprintf("client-%04d", i)] = []model.ClientIpEntry{ + {IP: "192.0.2.1", Timestamp: now - 10}, + {IP: "2001:db8::1", Timestamp: now - 20}, + } + } + svc := &InboundService{} + if err := svc.RecordLocalClientIps(guid, report); err != nil { + t.Fatal(err) + } + + counts := countClientIpSQL(t, "node_client_ips") + for _, entries := range report { + entries[0], entries[1] = entries[1], entries[0] + } + if err := svc.MergeClientIpsByGuid(nil, map[string]map[string][]model.ClientIpEntry{guid: report}); err != nil { + t.Fatal(err) + } + if got := counts.creates.Load(); got != 0 { + t.Fatalf("unchanged report executed %d upserts, want none", got) + } + + for email, entries := range report { + if email != "client-0000" { + entries[1].Timestamp = now + } + } + report["new@x"] = slices.Clone(report["client-0001"]) + if err := svc.MergeClientIpsByGuid(nil, map[string]map[string][]model.ClientIpEntry{guid: report}); err != nil { + t.Fatal(err) + } + if got := counts.creates.Load(); got != 3 || counts.affected.Load() != clients { + t.Fatalf("refreshed report executed %d upserts for %d rows, want 3 upserts for %d", got, counts.affected.Load(), clients) + } + + trees, err := svc.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if got := len(trees[guid]); got != len(report) { + t.Fatalf("saved clients = %d, want %d", got, len(report)) + } + for email, want := range report { + got := trees[guid][email] + if len(got) != 2 || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("saved IPs for %q = %v, want %v", email, got, want) + } + } +} + +func TestNodeClientIpBatchRetriesConcurrentChange(t *testing.T) { + for _, change := range []string{"insert", "insert in batch", "update", "refresh before delete", "delete before refresh", "replace before refresh"} { + t.Run(change, func(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + svc := &InboundService{} + now := time.Now().Unix() + first := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 10} + winner := model.ClientIpEntry{IP: "198.51.100.1", Timestamp: now - 5} + incoming := model.ClientIpEntry{IP: "203.0.113.1", Timestamp: now} + if change == "refresh before delete" { + first.Timestamp = now - clientIpStaleAfterSeconds - 20 + incoming.Timestamp = first.Timestamp + } + + inserting := change == "insert" || change == "insert in batch" + if !inserting { + row := model.NodeClientIp{NodeGuid: "edge", Email: "a@x", Ips: rawClientIpBlob(t, first)} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + } + replacement := []model.ClientIpEntry{winner} + if change == "delete before refresh" { + replacement = nil + } + if change == "update" { + replacement = []model.ClientIpEntry{first, winner} + } + blob := rawClientIpBlob(t, replacement...) + const callback = "test:node_ip_competing_writer" + wrote := false + if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) { + if wrote || tx.Statement.Table != "node_client_ips" { + return + } + wrote = true + if change == "delete before refresh" || change == "replace before refresh" { + _ = tx.AddError(db.Transaction(func(other *gorm.DB) error { + if err := other.Exec("DELETE FROM node_client_ips WHERE node_guid = ? AND email = ?", "edge", "a@x").Error; err != nil { + return err + } + if change == "replace before refresh" { + return other.Exec("INSERT INTO node_client_ips (node_guid, email, ips) VALUES (?, ?, ?)", "edge", "a@x", blob).Error + } + return nil + })) + return + } + if inserting { + tx.AddError(db.Exec("INSERT INTO node_client_ips (node_guid, email, ips) VALUES (?, ?, ?)", "edge", "a@x", blob).Error) + return + } + tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE node_guid = ? AND email = ?", blob, "edge", "a@x").Error) + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + + report := map[string][]model.ClientIpEntry{"a@x": {incoming}} + if change == "insert in batch" { + report["z@x"] = []model.ClientIpEntry{incoming} + } + if err := svc.RecordLocalClientIps("edge", report); err != nil { + t.Fatal(err) + } + tree, err := svc.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + want := replacement + if change != "refresh before delete" { + want = append(want, incoming) + } + if got := tree["edge"]["a@x"]; !wrote || !slices.Equal(got, want) { + t.Fatalf("saved after concurrent %s = %v, want %v (writer ran: %t)", change, got, want, wrote) + } + if change == "insert in batch" && !slices.Equal(tree["edge"]["z@x"], report["z@x"]) { + t.Fatalf("uncontested row = %v, want %v", tree["edge"]["z@x"], report["z@x"]) + } + }) + } +} + +func TestNodeClientIpBatchRollsBackOnLaterFailure(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + svc := &InboundService{} + now := time.Now().Unix() + report := make(map[string][]model.ClientIpEntry, 201) + for i := range 201 { + report[fmt.Sprintf("client-%03d", i)] = []model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now - 10}} + } + if err := svc.RecordLocalClientIps("edge", report); err != nil { + t.Fatal(err) + } + + const callback = "test:node_ip_second_batch_failure" + failure := errors.New("second attribution batch failed") + attempts := 0 + if err := db.Callback().Create().Before("gorm:create").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == "node_client_ips" { + attempts++ + if attempts == 2 { + tx.AddError(failure) + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Create().Remove(callback) }) + + for _, entries := range report { + entries[0].Timestamp = now + } + if err := svc.RecordLocalClientIps("edge", report); !errors.Is(err, failure) { + t.Fatalf("write error = %v, want %v", err, failure) + } + tree, err := svc.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if got := len(tree["edge"]); got != len(report) { + t.Fatalf("saved clients = %d, want %d", got, len(report)) + } + for email, entries := range tree["edge"] { + if len(entries) != 1 || entries[0].Timestamp != now-10 { + t.Fatalf("failed merge changed %q to %v", email, entries) + } + } +} + +func TestPruneNodeClientIpsPreservesConcurrentRefresh(t *testing.T) { + for _, withFreshEntry := range []bool{false, true} { + t.Run(fmt.Sprintf("partially-fresh=%t", withFreshEntry), func(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + now := time.Now().Unix() + cutoff := now - clientIpStaleAfterSeconds + fresh := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now} + stale := model.ClientIpEntry{IP: fresh.IP, Timestamp: cutoff - 1} + entries := []model.ClientIpEntry{stale} + if withFreshEntry { + entries = append(entries, model.ClientIpEntry{IP: "203.0.113.1", Timestamp: now - 5}) + } + if err := db.Create(&model.NodeClientIp{NodeGuid: "edge", Email: "a@x", Ips: rawClientIpBlob(t, entries...)}).Error; err != nil { + t.Fatal(err) + } + + const callback = "test:refresh_during_prune" + refresh := append(slices.Clone(entries[1:]), fresh) + blob := rawClientIpBlob(t, refresh...) + wrote := false + if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) { + if !wrote && tx.Statement.Table == "node_client_ips" { + wrote = true + tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE node_guid = ? AND email = ?", blob, "edge", "a@x").Error) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + if err := pruneStaleNodeClientIps(cutoff); err != nil { + t.Fatal(err) + } + tree, err := (&InboundService{}).GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if got := tree["edge"]["a@x"]; !wrote || !slices.Equal(got, refresh) { + t.Fatalf("saved IPs after prune = %v, want %v (refresh ran: %t)", got, refresh, wrote) + } + }) + } +} + +func TestConcurrentPolledReportsMergeMixedRowsForSharedDescendant(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + svc := &InboundService{} + const guid = "shared-descendant" + now := time.Now().Unix() + parents := []*model.Node{ + {Name: "parent-a", Guid: "parent-a", Address: "192.0.2.1", Port: 443, Enable: true, Status: "online"}, + {Name: "parent-b", Guid: "parent-b", Address: "192.0.2.2", Port: 443, Enable: true, Status: "online"}, + } + clients := []model.Client{{Email: "a@example.test", Enable: true}, {Email: "z@example.test", Enable: true}} + for i, node := range parents { + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + inbound := &model.Inbound{NodeID: &node.Id, OriginNodeGuid: guid, UserId: 1, Protocol: model.VLESS, Port: 25000 + i, Tag: node.Name} + if err := db.Create(inbound).Error; err != nil { + t.Fatal(err) + } + if err := (&ClientService{}).SyncInbound(db, inbound.Id, clients); err != nil { + t.Fatal(err) + } + } + if err := svc.RecordLocalClientIps(guid, map[string][]model.ClientIpEntry{ + clients[0].Email: {{IP: "192.0.2.1", Timestamp: now - 20}}, + }); err != nil { + t.Fatal(err) + } + + read := make(chan struct{}) + continueFirst := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(continueFirst) }) + var reads atomic.Int32 + var workers sync.WaitGroup + const hook = "test:shared-descendant-mixed-insert" + if err := db.Callback().Query().After("gorm:query").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "node_client_ips" && reads.Add(1) == 1 { + close(read) + <-continueFirst + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + unblock() + workers.Wait() + _ = db.Callback().Query().Remove(hook) + }) + report := func(node *model.Node, ip string, timestamp int64) error { + obs := []model.ClientIpEntry{{IP: ip, Timestamp: timestamp}} + return svc.MergePolledClientIpsByGuid(t.Context(), node, map[string]map[string][]model.ClientIpEntry{ + guid: {clients[0].Email: obs, clients[1].Email: obs}, + }) + } + done := make(chan error, 1) + workers.Go(func() { done <- report(parents[0], "198.51.100.1", now-5) }) + select { + case <-read: + case err := <-done: + t.Fatalf("first reporter did not plan an attribution transaction: %v", err) + case <-time.After(3 * time.Second): + t.Fatal("first reporter did not reach the attribution read") + } + if err := report(parents[1], "203.0.113.1", now); err != nil { + t.Fatal(err) + } + unblock() + if err := <-done; err != nil { + t.Fatal(err) + } + if reads.Load() != 3 { + t.Fatalf("read attempts = %d, want initial pair plus one whole-GUID retry", reads.Load()) + } + trees, err := svc.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + created := []model.ClientIpEntry{{IP: "198.51.100.1", Timestamp: now - 5}, {IP: "203.0.113.1", Timestamp: now}} + if got := trees[guid][clients[1].Email]; !slices.Equal(got, created) { + t.Fatalf("competing insert lost an observation: got %+v, want %+v", got, created) + } + updated := append([]model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now - 20}}, created...) + if got := trees[guid][clients[0].Email]; !slices.Equal(got, updated) { + t.Fatalf("mixed update lost an observation: got %+v, want %+v", got, updated) + } +} + +func TestNodeClientIpLaterBatchCASRollsBackBeforeRetry(t *testing.T) { + for _, exhaust := range []bool{false, true} { + t.Run(fmt.Sprintf("exhaust=%t", exhaust), func(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + svc := &InboundService{} + const guid = "later-cas" + now := time.Now().Unix() + original := rawClientIpBlob(t, model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 30}) + rows := make([]model.NodeClientIp, nodeClientIpWriteBatch+1) + report := make(map[string][]model.ClientIpEntry, len(rows)) + for i := range rows { + email := fmt.Sprintf("client-%03d@x", i) + rows[i] = model.NodeClientIp{NodeGuid: guid, Email: email, Ips: original} + report[email] = []model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now}} + } + if err := db.CreateInBatches(&rows, 100).Error; err != nil { + t.Fatal(err) + } + first, last := rows[0], rows[len(rows)-1] + attempts := 0 + const hook = "test:conflict-in-last-attribution-batch" + if err := db.Callback().Query().After("gorm:query").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table != "node_client_ips" { + return + } + attempts++ + var got string + if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", first.Id).Scan(&got).Error; err != nil { + _ = tx.AddError(err) + return + } + if got != original { + _ = tx.AddError(fmt.Errorf("earlier batch committed before attempt %d: %s", attempts, got)) + return + } + if exhaust || attempts == 1 { + blob := fmt.Sprintf(`[{"ip":"198.51.100.2","timestamp":%d}]`, now-int64(attempts)) + _ = tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE id = ?", blob, last.Id).Error) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(hook) }) + err := svc.RecordLocalClientIps(guid, report) + if exhaust { + if !errors.Is(err, errNodeClientIpConflict) || attempts != ClientIpCasRetries { + t.Fatalf("exhaustion = %v, attempts=%d", err, attempts) + } + } else if err != nil || attempts != 2 { + t.Fatalf("retry = %v, attempts=%d", err, attempts) + } + var stored string + if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", first.Id).Scan(&stored).Error; err != nil { + t.Fatal(err) + } + want := original + if !exhaust { + want = rawClientIpBlob(t, report[first.Email]...) + var late string + if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", last.Id).Scan(&late).Error; err != nil { + t.Fatal(err) + } + wantLate := rawClientIpBlob(t, model.ClientIpEntry{IP: "198.51.100.2", Timestamp: now - 1}, report[last.Email][0]) + if late != wantLate { + t.Fatalf("retry failed to merge the winning observation: %s want %s", late, wantLate) + } + } + if stored != want { + t.Fatalf("first batch after attempt sequence = %s, want %s", stored, want) + } + }) + } +} diff --git a/internal/web/service/node_ip_lock_order_postgres_test.go b/internal/web/service/node_ip_lock_order_postgres_test.go new file mode 100644 index 000000000..a35fe9651 --- /dev/null +++ b/internal/web/service/node_ip_lock_order_postgres_test.go @@ -0,0 +1,534 @@ +package service + +import ( + "context" + "errors" + "fmt" + "maps" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/config" + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +type nodeIPLockReportKey struct{} + +type nodeIPLockEvent struct { + PID int + SQL string + Err error +} + +func nodeIPTestBackend(tx *gorm.DB) nodeIPLockEvent { + event := nodeIPLockEvent{SQL: tx.Statement.SQL.String()} + event.Err = tx.Session(&gorm.Session{NewDB: true}).Raw("SELECT pg_backend_pid()").Scan(&event.PID).Error + return event +} + +func waitNodeIPTestValue[T any](t *testing.T, ctx context.Context, ready <-chan T, stage string) T { + t.Helper() + select { + case value := <-ready: + return value + case <-ctx.Done(): + t.Fatalf("%s: %v", stage, ctx.Err()) + var zero T + return zero + } +} + +func nodeIPBlocker(db *gorm.DB, waiter, blocker int) (bool, error) { + var blocked bool + err := db.Raw("SELECT ? = ANY(pg_blocking_pids(?))", blocker, waiter).Scan(&blocked).Error + return blocked, err +} + +func waitNodeIPBlocked(t *testing.T, ctx context.Context, db *gorm.DB, waiter, blocker int) { + t.Helper() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + blocked, err := nodeIPBlocker(db.WithContext(ctx), waiter, blocker) + if err != nil { + t.Fatal(err) + } + if blocked { + return + } + select { + case <-ctx.Done(): + t.Fatalf("backend %d never waited on %d: %v", waiter, blocker, ctx.Err()) + case <-ticker.C: + } + } +} + +func seedNodeIPLockFixture(t *testing.T, name string, port int, emails ...string) (model.Node, []model.Client) { + t.Helper() + db := database.GetDB() + node := model.Node{ + Name: name, Guid: name, Scheme: "http", Address: "127.0.0.1", Port: port, + BasePath: "/", AllowPrivateAddress: true, ApiToken: "test", Enable: true, Status: "online", + } + if err := db.Create(&node).Error; err != nil { + t.Fatal(err) + } + clients := make([]model.Client, 0, len(emails)) + for i, email := range emails { + clients = append(clients, model.Client{ + Email: email, SubID: email, Enable: true, + ID: fmt.Sprintf("00000000-0000-4000-8000-%012d", port*10+i), + }) + } + inbound := model.Inbound{ + NodeID: &node.Id, UserId: 1, Port: port, Tag: name, + Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, clients), + } + if err := db.Create(&inbound).Error; err != nil { + t.Fatal(err) + } + if err := (&ClientService{}).SyncInbound(db, inbound.Id, clients); err != nil { + t.Fatal(err) + } + return node, clients +} + +func TestPostgresNodeIPReporterClientLockOrder(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL row locks") + } + for _, operation := range []string{"delete", "rename", "bulk_delete"} { + t.Run(operation, func(t *testing.T) { testNodeIPReporterClientLockOrder(t, operation) }) + } +} + +func testNodeIPReporterClientLockOrder(t *testing.T, operation string) { + t.Helper() + setupClientIpTestDB(t) + resetTrafficWriterForTest(t) + StartTrafficWriter() + t.Cleanup(StopTrafficWriter) + db := database.GetDB() + const target, secondTarget, survivor = "a-target@example.test", "b-target@example.test", "z-survivor@example.test" + const healthyEmail = "healthy@example.test" + nodeEmails := []string{target, survivor} + removed := []string{target} + if operation == "bulk_delete" { + nodeEmails = append(nodeEmails, secondTarget) + removed = append(removed, secondTarget) + } + node, clients := seedNodeIPLockFixture(t, "contended-edge", 23081, nodeEmails...) + healthy, _ := seedNodeIPLockFixture(t, "healthy-edge", 23082, healthyEmail) + inbounds, clientService := &InboundService{}, &ClientService{} + record, err := clientService.GetRecordByEmail(nil, target) + if err != nil { + t.Fatal(err) + } + now := time.Now().Unix() + before := model.ClientIpEntry{IP: "192.0.2.10", Timestamp: now - 20} + refreshed := model.ClientIpEntry{IP: before.IP, Timestamp: now - 2} + fresh := model.ClientIpEntry{IP: "192.0.2.20", Timestamp: now - 1} + seedEmails := append([]string{healthyEmail}, nodeEmails...) + slices.Reverse(seedEmails) + for _, email := range seedEmails { + if err := db.Create(&model.InboundClientIps{ClientEmail: email, Ips: marshalIps(t, before)}).Error; err != nil { + t.Fatal(err) + } + } + payload := marshalIps(t, refreshed, fresh) + ctx, cancel := context.WithTimeout(t.Context(), 12*time.Second) + defer cancel() + reportCtx := context.WithValue(ctx, nodeIPLockReportKey{}, true) + mutationLocked := make(chan nodeIPLockEvent, 1) + reportWriting := make(chan nodeIPLockEvent, 1) + resumeMutation := make(chan struct{}) + releaseMutation := sync.OnceFunc(func() { close(resumeMutation) }) + var mutationStarted, reportStarted bool + mutationDone, reportDone := make(chan struct{}), make(chan struct{}) + var mutationErr, reportErr error + defer func() { + releaseMutation() + if mutationStarted { + <-mutationDone + } + if reportStarted { + <-reportDone + } + }() + blockMutation := func(tx *gorm.DB) { + if tx.Statement.Table != "inbound_client_ips" || tx.RowsAffected == 0 || tx.Error != nil || + tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil { + return + } + select { + case mutationLocked <- nodeIPTestBackend(tx): + <-resumeMutation + default: + } + } + const cb = "test:node_ip_lock_order" + var hookedMutation bool + mutationHook := func(tx *gorm.DB) { + if tx.Statement.Table == "inbound_client_ips" && !hookedMutation { + hookedMutation = true + blockMutation(tx) + } + } + if operation == "rename" { + if err := db.Callback().Update().After("gorm:update").Register(cb+"-mutation", mutationHook); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(cb + "-mutation") }) + } else { + if err := db.Callback().Delete().After("gorm:delete").Register(cb+"-mutation", mutationHook); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Delete().Remove(cb + "-mutation") }) + } + if err := db.Callback().Update().Before("gorm:update").Register(cb+"-report", func(tx *gorm.DB) { + if tx.Statement.Table == "inbound_client_ips" && tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil { + select { + case reportWriting <- nodeIPTestBackend(tx): + default: + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(cb + "-report") }) + + mutationStarted = true + go func() { + defer close(mutationDone) + switch operation { + case "delete": + _, mutationErr = clientService.Delete(inbounds, record.Id, false) + case "rename": + updated := clients[0] + updated.Email = "renamed@example.test" + _, mutationErr = clientService.Update(inbounds, record.Id, updated, 0) + case "bulk_delete": + result, _, err := clientService.BulkDelete(inbounds, []string{secondTarget, target}, false) + mutationErr = err + if err == nil && (result.Deleted != len(removed) || len(result.Skipped) != 0) { + mutationErr = fmt.Errorf("bulk delete did not commit: %+v", result) + } + } + }() + mutation := waitNodeIPTestValue(t, ctx, mutationLocked, "mutation holds flat IP row") + if mutation.Err != nil { + t.Fatal(mutation.Err) + } + reportStarted = true + payloadRows := make([]model.InboundClientIps, 0, len(nodeEmails)) + for _, email := range nodeEmails { + payloadRows = append(payloadRows, model.InboundClientIps{ClientEmail: email, Ips: payload}) + } + go func() { + defer close(reportDone) + reportErr = inbounds.MergePolledNodeClientIps(reportCtx, &node, payloadRows) + }() + report := waitNodeIPTestValue(t, ctx, reportWriting, "report attempts flat IP write") + if report.Err != nil { + t.Fatal(report.Err) + } + waitNodeIPBlocked(t, ctx, db, report.PID, mutation.PID) + + healthyCtx, stopHealthy := context.WithTimeout(ctx, 2*time.Second) + err = inbounds.MergePolledNodeClientIps(healthyCtx, &healthy, []model.InboundClientIps{{ClientEmail: healthyEmail, Ips: payload}}) + stopHealthy() + if err != nil { + t.Fatalf("independent reporter stalled: %v", err) + } + releaseMutation() + logNodeIPWaitCycle(t, ctx, db, mutation, report, mutationDone, reportDone) + + for name, err := range map[string]error{"mutation": mutationErr, "report": reportErr} { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "40P01" { + t.Errorf("%s SQLSTATE %s: %s\n%s", name, pgErr.Code, pgErr.Detail, pgErr.Where) + } else if err != nil { + t.Errorf("%s: %v", name, err) + } + } + if t.Failed() { + return + } + var records int64 + if err := db.Model(&model.ClientRecord{}).Where("email IN ?", removed).Count(&records).Error; err != nil { + t.Fatal(err) + } + for _, email := range removed { + if _, exists := readClientIps(t, email); exists || records != 0 { + t.Fatalf("obsolete email %s survived: IP row=%t, client records=%d", email, exists, records) + } + } + if operation != "rename" { + var pending int64 + if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email IN ?", node.Id, removed). + Count(&pending).Error; err != nil || pending != int64(len(removed)) { + t.Fatalf("permanent-delete outbox count = %d, want %d: %v", pending, len(removed), err) + } + } + if operation == "rename" { + got, exists := readClientIps(t, "renamed@example.test") + if !exists || !maps.Equal(got, map[string]int64{before.IP: before.Timestamp}) { + t.Fatalf("rename should move only the committed history: %v", got) + } + } + _, _, dirty, generation, err := (&NodeService{}).NodeSyncState(node.Id) + if err != nil || !dirty || generation <= node.ConfigDirtyAt { + t.Fatalf("dirty generation after %s: dirty=%t generation=%d err=%v", operation, dirty, generation, err) + } + want := map[string]int64{refreshed.IP: refreshed.Timestamp, fresh.IP: fresh.Timestamp} + for _, email := range []string{survivor, healthyEmail} { + if got, _ := readClientIps(t, email); !maps.Equal(got, want) { + t.Errorf("%s: IP union = %v, want %v", email, got, want) + } + } +} + +func logNodeIPWaitCycle(t *testing.T, ctx context.Context, db *gorm.DB, mutation, report nodeIPLockEvent, mutationDone, reportDone <-chan struct{}) { + t.Helper() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-mutationDone: + waitNodeIPTestValue(t, ctx, reportDone, "report completion") + return + case <-reportDone: + waitNodeIPTestValue(t, ctx, mutationDone, "mutation completion") + return + case <-ticker.C: + cycle, err := nodeIPBlocker(db.WithContext(ctx), mutation.PID, report.PID) + if err != nil { + t.Fatal(err) + } + if !cycle { + continue + } + var queries []struct { + PID int `gorm:"column:pid"` + Query string + WaitEvent string + } + if err := db.WithContext(ctx).Raw( + "SELECT pid, query, wait_event FROM pg_stat_activity WHERE pid IN (?, ?) ORDER BY pid", + mutation.PID, report.PID, + ).Scan(&queries).Error; err != nil { + t.Fatal(err) + } + t.Logf("mutual PostgreSQL blockers: %+v; first mutation: %s", queries, mutation.SQL) + var ungranted []struct { + PID int `gorm:"column:pid"` + Mode string + Type string + } + if err := db.WithContext(ctx).Raw( + "SELECT pid, mode, locktype AS type FROM pg_locks WHERE pid IN (?, ?) AND NOT granted ORDER BY pid", + mutation.PID, report.PID, + ).Scan(&ungranted).Error; err != nil { + t.Fatal(err) + } + t.Logf("ungranted PostgreSQL locks: %+v", ungranted) + waitNodeIPTestValue(t, ctx, mutationDone, "deadlock victim releases mutation") + waitNodeIPTestValue(t, ctx, reportDone, "deadlock victim releases report") + return + case <-ctx.Done(): + t.Fatalf("waiting for database transactions: %v", ctx.Err()) + } + } +} + +func TestPostgresFlatIPReporterLifecycleCommit(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL row locks") + } + for _, change := range []string{"disable", "delete", "endpoint", "guid"} { + t.Run(change, func(t *testing.T) { testFlatIPReporterLifecycleCommit(t, change) }) + } +} + +func testFlatIPReporterLifecycleCommit(t *testing.T, change string) { + t.Helper() + setupClientIpTestDB(t) + db := database.GetDB() + const first, second = "a@example.test", "z@example.test" + node, _ := seedNodeIPLockFixture(t, "replaced-edge", 23083, first, second) + now := time.Now().Unix() + old := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 10} + fresh := model.ClientIpEntry{IP: "192.0.2.2", Timestamp: now - 1} + var rows []model.InboundClientIps + for _, email := range []string{first, second} { + rows = append(rows, model.InboundClientIps{ClientEmail: email, Ips: marshalIps(t, old)}) + } + if err := db.Create(&rows).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.NodeClientIp{NodeGuid: node.Guid, Email: first, Ips: rows[0].Ips}).Error; err != nil { + t.Fatal(err) + } + payload := marshalIps(t, fresh) + for i := range rows { + rows[i].Ips = payload + } + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + reportCtx := context.WithValue(ctx, nodeIPLockReportKey{}, true) + staged, resume := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(resume) }) + writes := 0 + const cb = "test:flat_ip_lifecycle_commit" + if err := db.Callback().Update().After("gorm:update").Register(cb, func(tx *gorm.DB) { + if tx.Statement.Table == "inbound_client_ips" && tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil && tx.RowsAffected == 1 { + writes++ + if writes == len(rows) { + close(staged) + <-resume + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(cb) }) + inbounds, nodes := &InboundService{}, &NodeService{} + reportDone := make(chan error, 1) + var reportExited bool + defer func() { + unblock() + if !reportExited { + <-reportDone + } + }() + go func() { reportDone <- inbounds.MergePolledNodeClientIps(reportCtx, &node, rows) }() + waitNodeIPTestValue(t, ctx, staged, "flat report staged both rows") + + mutationDone := make(chan error, 1) + go func() { + switch change { + case "disable": + mutationDone <- nodes.SetEnable(node.Id, false) + case "delete": + var row model.Inbound + if err := db.WithContext(ctx).Where("node_id = ?", node.Id).Take(&row).Error; err != nil { + mutationDone <- err + return + } + if _, err := inbounds.DelInbound(row.Id); err != nil { + mutationDone <- err + return + } + mutationDone <- nodes.Delete(node.Id) + case "endpoint": + replacement := node + replacement.ApiToken = "" + replacement.Port++ + mutationDone <- nodes.Update(node.Id, &replacement) + case "guid": + mutationDone <- nodes.UpdateHeartbeat(node.Id, HeartbeatPatch{Guid: "new-guid", Status: "online", LastHeartbeat: now}) + } + }() + var mutationExited bool + defer func() { + unblock() + if !mutationExited { + <-mutationDone + } + }() + mutationCtx, stopMutation := context.WithTimeout(ctx, 3*time.Second) + defer stopMutation() + err := waitNodeIPTestValue(t, mutationCtx, mutationDone, "lifecycle update completes while flat rows are staged") + mutationExited = true + if err != nil { + t.Fatal(err) + } + unblock() + err = waitNodeIPTestValue(t, ctx, reportDone, "obsolete report rolls back") + reportExited = true + if !errors.Is(err, ErrIneligibleNodeIPReport) { + t.Fatalf("report error = %v, want ineligible reporter", err) + } + for _, email := range []string{first, second} { + got, _ := readClientIps(t, email) + if !maps.Equal(got, map[string]int64{old.IP: old.Timestamp}) { + t.Errorf("%s committed some of the obsolete report: %v", email, got) + } + } + if change == "delete" { + var count int64 + if err := db.Model(&model.NodeClientIp{}).Where("node_guid = ?", node.Guid).Count(&count).Error; err != nil || count != 0 { + t.Fatalf("deleted reporter left %d attribution rows: %v", count, err) + } + } +} + +func TestPostgresPolledAttributionSurvivesConcurrentPrune(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL") + } + setupClientIpTestDB(t) + db := database.GetDB() + const email = "a@example.test" + node, _ := seedNodeIPLockFixture(t, "prune-edge", 23084, email) + now := time.Now().Unix() + stale := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - clientIpStaleAfterSeconds - 60} + renewed := model.ClientIpEntry{IP: stale.IP, Timestamp: now - 1} + fresh := model.ClientIpEntry{IP: "192.0.2.2", Timestamp: now} + if err := db.Create(&model.NodeClientIp{NodeGuid: node.Guid, Email: email, Ips: marshalIps(t, stale)}).Error; err != nil { + t.Fatal(err) + } + read, resume := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(resume) }) + var readStale atomic.Bool + const cb = "test:park_attribution_prune" + if err := db.Callback().Query().After("gorm:query").Register(cb, func(tx *gorm.DB) { + if tx.Statement.Table == "node_client_ips" && readStale.CompareAndSwap(false, true) { + close(read) + <-resume + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(cb) }) + inbounds := &InboundService{} + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + pruneDone := make(chan error, 1) + go func() { pruneDone <- inbounds.PruneStaleClientIps() }() + var pruneExited bool + defer func() { + unblock() + if !pruneExited { + <-pruneDone + } + }() + waitNodeIPTestValue(t, ctx, read, "pruner has stale attribution snapshot") + want := []model.ClientIpEntry{renewed, fresh} + if err := inbounds.MergePolledClientIpsByGuid(ctx, &node, map[string]map[string][]model.ClientIpEntry{ + node.Guid: {email: slices.Clone(want)}, + }); err != nil { + t.Fatal(err) + } + unblock() + err := waitNodeIPTestValue(t, ctx, pruneDone, "stale pruner completes") + pruneExited = true + if err != nil { + t.Fatal(err) + } + trees, err := inbounds.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if got := trees[node.Guid][email]; !slices.Equal(got, want) { + t.Fatalf("pruner lost refreshed attribution: %v, want %v", got, want) + } +} From 91d5ff400d00823fc17bea0efb69116ff5e79ae3 Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 00:08:12 +0330 Subject: [PATCH 08/14] perf(clients): batch client creation by destination node (#7367) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Group compatible client creates by destination and effective payload via the existing clients/add API. Resolve node-local inbound IDs, preserve distinct flow/address/credential payloads, bound delivery concurrency and use a shared four-second remote delivery budget after local commits. Advance reconciliation fingerprints only for acknowledged intended settings, retaining previous-fingerprint CAS rather than stamping unrelated rebased changes. Preserve FIFO turns, node-wide barriers, dirty generations, durable delete supersession, partial and uncertain delivery recovery and downstream outcomes. Protect later reattachments in final Delete cleanup and complete Create metadata before remote delivery. Validation: all 12 CI jobs passed on 63e70cda387e3221550b6a2e029ef59863b07f07 (run 46935177853). PostgreSQL logs confirm 21 ordering/grouped-create tests and prior reporter-lock, reconciliation and traffic contention gates; node E2E confirms all four version pairings. Author reports SQLite/PostgreSQL race tests, make verify and isolated full make race. Author-reported paired PostgreSQL 18 benchmark: 11 -> 1 RPC, fixed 200 ms peer delay 11-target p95 1552.0 -> 731.9 ms, timeout probe 12.41–12.42 -> 4.41–4.50 s. Size-dependent peer cost can instead cause pending delivery (1.74 -> 4.51 s with 0.74 s recovery); four stalled nodes can defer a fifth. Monitor production convergence and pending rate. No general production latency or allocation improvement claimed. Refs #7299 --- .github/workflows/ci.yml | 6 +- internal/nodee2e/node_snapshot_test.go | 58 ++- internal/web/controller/client.go | 2 +- internal/web/node_contract_test.go | 48 +- internal/web/runtime/remote.go | 91 +++- .../web/service/client_create_dispatch.go | 193 +++++++ .../web/service/client_create_fanout_test.go | 242 +++++++++ .../web/service/client_create_order_test.go | 308 +++++++++++ .../service/client_create_reconcile_test.go | 487 ++++++++++++++++++ internal/web/service/client_crud.go | 55 +- internal/web/service/client_inbound_apply.go | 27 + internal/web/service/client_node_dispatch.go | 42 +- internal/web/service/node_http_fake_test.go | 21 +- 13 files changed, 1521 insertions(+), 59 deletions(-) create mode 100644 internal/web/service/client_create_dispatch.go create mode 100644 internal/web/service/client_create_order_test.go create mode 100644 internal/web/service/client_create_reconcile_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e9311d42..54c7e2e04 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -158,10 +158,10 @@ jobs: - name: PostgreSQL node client push ordering run: | set -o pipefail - go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log + go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush|Create(GroupsCompatibleInboundsOnOneRemote|SplitsFlowAndSendsResolvedInbounds|UsesEffectiveAllowedIPsOnRemote|DispatchesReadyLaneBeforeBlockedLane|CancellationStopsFurtherNodeWaves)|GroupedCreate(ReconcilesUnsentRebasedSettings|RecoversIndeterminateDelivery|RepairsDeferredTargets|DispatchesIndependentReadyPayload|OrdersLaterClientMutations|ReconcileBarrierDrainsAfterAcknowledgment|KeepsFifthNodeDurablyPendingWhenBudgetExpires|PreservesProtocolCredentials))$' -count=1 -v | tee /tmp/postgres-node-client-order.log passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) - if [ "$passed" -ne 8 ]; then - echo "expected 8 passing PostgreSQL node client ordering tests, got $passed" >&2 + if [ "$passed" -ne 21 ]; then + echo "expected 21 passing PostgreSQL node client ordering tests, got $passed" >&2 exit 1 fi diff --git a/internal/nodee2e/node_snapshot_test.go b/internal/nodee2e/node_snapshot_test.go index 6cf4f7388..dcdbf55cf 100644 --- a/internal/nodee2e/node_snapshot_test.go +++ b/internal/nodee2e/node_snapshot_test.go @@ -3,6 +3,7 @@ package nodee2e import ( "bytes" "compress/gzip" + "context" "encoding/json" "fmt" "io" @@ -11,9 +12,14 @@ import ( "net/http/httputil" "net/url" "os" + "slices" "strconv" "sync/atomic" "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) func TestNodeSnapshotVersionCompatibility(t *testing.T) { @@ -39,7 +45,7 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { token := node.mintToken("snapshot-link", "node-sync") master.start() node.start() - var lists, compact, full, unchanged atomic.Int32 + var lists, compact, full, unchanged, clientAdds atomic.Int32 target, err := url.Parse(node.url()) if err != nil { t.Fatal(err) @@ -88,6 +94,8 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { lists.Add(1) case "/panel/api/inbounds/trafficSnapshot": compact.Add(1) + case "/panel/api/clients/add": + clientAdds.Add(1) } proxy.ServeHTTP(w, req) })) @@ -101,10 +109,14 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { t.Fatal(err) } inboundPort := freePort(t) + secondaryPort := freePort(t) var source inboundView if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil { t.Fatal(err) } + if version.master == current { + node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix-secondary", secondaryPort, nil)) + } master.call(http.MethodPost, "/panel/api/nodes/add", map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}) eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) { ib, ok := master.inboundOnPort(inboundPort) @@ -136,6 +148,50 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { master.start() eventually(t, settleTimeout, "master restart reacquires complete structure", func() (bool, string) { return full.Load() > before, fmt.Sprint(full.Load()) }) } + if version.master == current { + first, hasFirst := master.inboundOnPort(inboundPort) + second, hasSecond := master.inboundOnPort(secondaryPort) + if !hasFirst || !hasSecond { + t.Fatal("master did not adopt both inbounds") + } + const email = "matrix-shared-create" + master.call(http.MethodPost, "/panel/api/clients/add", map[string]any{ + "client": map[string]any{"email": email, "enable": true}, "inboundIds": []int{first.Id, second.Id}, + }) + if got := clientAdds.Load(); got != 1 { + t.Fatalf("node-sync received %d add requests, want one", got) + } + var tags []string + for _, port := range []int{inboundPort, secondaryPort} { + if ib, ok := node.inboundOnPort(port); !ok || ib.client(email) == nil { + t.Fatalf("node did not apply the grouped client on port %d", port) + } else { + tags = append(tags, ib.Tag) + } + } + admin := runtime.NewRemote(&model.Node{ + Name: "matrix-admin", Scheme: "http", Address: address.Hostname(), Port: port, + BasePath: "/", ApiToken: node.token, Enable: true, AllowPrivateAddress: true, + }, nil) + const adminEmail = "matrix-admin-create" + raw, err := json.Marshal(vlessClient(adminEmail)) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + if _, ack, err := admin.AddClientGroup(ctx, tags, raw); err != nil || !slices.Equal(ack, []bool{true, true}) { + t.Fatalf("admin grouped add acknowledged %v, err=%v", ack, err) + } + if got := clientAdds.Load(); got != 2 { + t.Fatalf("admin sent %d add requests, want one", got-1) + } + for _, port := range []int{inboundPort, secondaryPort} { + if ib, ok := node.inboundOnPort(port); !ok || ib.client(adminEmail) == nil { + t.Fatalf("admin grouped client absent on port %d", port) + } + } + } }) } } diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 1287fa777..b2b5c43d7 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -269,7 +269,7 @@ func (a *ClientController) create(c *gin.Context) { return } clientSvc := a.clientService.TrackNodeApplies() - needRestart, err := clientSvc.Create(&a.inboundService, &payload) + needRestart, err := clientSvc.CreateWithContext(c.Request.Context(), &a.inboundService, &payload) // Flagged before the error check: a partly-applied create leaves clients // committed on the inbounds that succeeded, and those still need the restart. if needRestart { diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index a54cb27d5..f2e13b453 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -2,12 +2,14 @@ package web import ( "context" + "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "path/filepath" "reflect" + "slices" "strconv" "strings" "sync" @@ -235,6 +237,35 @@ func TestMasterNodeContract(t *testing.T) { t.Fatalf("node clients = %v, want c3 among them", got) } }}, + {"AddClientGroup attaches one client to two inbounds", []string{"AddClientGroup"}, func() error { + second := masterInbound("grouped", false) + second.Tag, second.Port = "in-51002-tcp", 51002 + if err := master.AddInbound(ctx, second); err != nil { + return err + } + client, err := json.Marshal(model.Client{ + Email: "grouped", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000004", SubID: "s-grouped", Enable: true, + }) + if err != nil { + return err + } + _, ack, err := master.AddClientGroup(ctx, []string{contractTag, second.Tag}, client) + if err == nil && !slices.Equal(ack, []bool{true, true}) { + return fmt.Errorf("acknowledged inbounds %v, want both", ack) + } + return err + }, func(t *testing.T) { + for _, tag := range []string{contractTag, "in-51002-tcp"} { + inbound, ok := nodeRow(t, tag) + if !ok { + t.Fatalf("node has no inbound %s", tag) + } + clients, err := (&service.InboundService{}).GetClients(inbound) + if err != nil || !slices.ContainsFunc(clients, func(c model.Client) bool { return c.Email == "grouped" }) { + t.Fatalf("node inbound %s received no grouped client, err=%v", tag, err) + } + } + }}, {"UpdateUser changes the client's limits", []string{"UpdateUser"}, func() error { _, err := master.UpdateUser(ctx, masterInbound("updated", false), "c3", model.Client{ Email: "c3", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000003", SubID: "s-c3", Enable: true, TotalGB: 5 << 30, @@ -421,14 +452,15 @@ func TestMasterNodeContract(t *testing.T) { // Remote methods that never reach the node, or that this table must not run. var remoteMethodsOutsideContract = map[string]string{ - "Name": "local label", - "RecordAdoptedInbound": "local fingerprint bookkeeping", - "AdoptInboundAlias": "local alias bookkeeping", - "AdoptedInboundAliases": "local alias bookkeeping", - "AdvancePushedInbound": "local fingerprint bookkeeping", - "ForgetPushedInbound": "local fingerprint bookkeeping", - "ForgetInbound": "local bookkeeping for an inbound the node no longer has", - "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)", + "Name": "local label", + "RecordAdoptedInbound": "local fingerprint bookkeeping", + "AdoptInboundAlias": "local alias bookkeeping", + "AdoptedInboundAliases": "local alias bookkeeping", + "AdvancePushedInbound": "local fingerprint bookkeeping", + "PreparePushedInboundAdvance": "local fingerprint bookkeeping", + "ForgetPushedInbound": "local fingerprint bookkeeping", + "ForgetInbound": "local bookkeeping for an inbound the node no longer has", + "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)", } // A Remote method with no cell is how activeInbounds and bulkResetTraffic diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index 8448cabc1..7f9eab52f 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -473,19 +473,21 @@ func stripNodeInboundTagPrefix(nodeID int, tag string) string { // that lives on only one of the two panels: the node may carry the bare tag // while the central panel stores the prefixed form, or vice versa. func (r *Remote) cacheGetTag(tag string) (int, bool) { - if id, ok := r.cacheGet(tag); ok { + r.mu.RLock() + defer r.mu.RUnlock() + return r.cachedTagID(tag) +} + +func (r *Remote) cachedTagID(tag string) (int, bool) { + if id, ok := r.remoteIDByTag[tag]; ok { return id, true } prefix := nodeInboundTagPrefix(r.node.Id) if stripped, found := strings.CutPrefix(tag, prefix); found { - return r.cacheGet(stripped) + tag = stripped + } else { + tag = prefix + tag } - return r.cacheGet(prefix + tag) -} - -func (r *Remote) cacheGet(tag string) (int, bool) { - r.mu.RLock() - defer r.mu.RUnlock() id, ok := r.remoteIDByTag[tag] return id, ok } @@ -738,13 +740,21 @@ func (r *Remote) AdoptedInboundAliases() []string { // node held the exact pre-edit state; otherwise the stale fingerprint stays and // the next reconcile re-sends the full inbound. func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) { + r.PreparePushedInboundAdvance(prevIb, ib)() +} + +// PreparePushedInboundAdvance keeps large settings blobs out of pending client batches. +func (r *Remote) PreparePushedInboundAdvance(prevIb, ib *model.Inbound) func() { + tag := ib.Tag prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id)) next := stampPushedInbound(ib, r.node.Id) - r.mu.Lock() - if r.pushedFP[ib.Tag].fingerprint == prevFP { - r.pushedFP[ib.Tag] = next + return func() { + r.mu.Lock() + defer r.mu.Unlock() + if r.pushedFP[tag].fingerprint == prevFP { + r.pushedFP[tag] = next + } } - r.mu.Unlock() } type pushedInboundClient struct { @@ -813,12 +823,59 @@ func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model. if err != nil { return ClientApplyResult{}, fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err) } - payload := map[string]any{ - "client": client, - "inboundIds": []int{id}, + return remoteClientApplyResult(r.postClientAdd(ctx, []int{id}, client)) +} + +// AddClientGroup returns the subset of tags acknowledged by one existing add RPC. +func (r *Remote) AddClientGroup(ctx context.Context, tags []string, client json.RawMessage) (ClientApplyResult, []bool, error) { + var refreshErr error + for _, tag := range tags { + if id, ok := r.cacheGetTag(tag); !ok || id <= 0 { + refreshErr = r.refreshRemoteIDs(ctx) + break + } } - env, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload) - return remoteClientApplyResult(env, err) + ids := make([]int, 0, len(tags)) + acknowledged := make([]bool, len(tags)) + seen := make(map[int]struct{}, len(tags)) + var missing []error + r.mu.RLock() + for i, tag := range tags { + id, ok := r.cachedTagID(tag) + if !ok || id <= 0 { + missing = append(missing, fmt.Errorf("%w: tag %q on node %s", errRemoteInboundNotFound, tag, r.node.Name)) + continue + } + acknowledged[i] = true + if _, duplicate := seen[id]; !duplicate { + ids = append(ids, id) + seen[id] = struct{}{} + } + } + r.mu.RUnlock() + unresolved := errors.Join(refreshErr, errors.Join(missing...)) + if len(ids) == 0 { + return ClientApplyResult{}, nil, unresolved + } + env, err := r.postClientAdd(ctx, ids, client) + if err != nil { + return ClientApplyResult{}, nil, errors.Join(err, unresolved) + } + var ack struct { + NodePending bool `json:"nodePending"` + } + // Legacy success replies omit obj or send null. + if len(env.Obj) != 0 { + if err := json.Unmarshal(env.Obj, &ack); err != nil { + return ClientApplyResult{}, nil, errors.Join(fmt.Errorf("decode grouped client add acknowledgment: %w", err), unresolved) + } + } + return ClientApplyResult{DownstreamPending: ack.NodePending}, acknowledged, unresolved +} + +func (r *Remote) postClientAdd(ctx context.Context, ids []int, client any) (*envelope, error) { + payload := map[string]any{"client": client, "inboundIds": ids} + return r.do(ctx, http.MethodPost, "panel/api/clients/add", payload) } func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) { diff --git a/internal/web/service/client_create_dispatch.go b/internal/web/service/client_create_dispatch.go new file mode 100644 index 000000000..47ec3db5c --- /dev/null +++ b/internal/web/service/client_create_dispatch.go @@ -0,0 +1,193 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "runtime/debug" + "sync" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/logger" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +type queuedClientCreate struct { + turn *nodeConfigTurn + remote *runtime.Remote + tag string + client string + advance func() + queuedAt time.Time +} + +func (q *queuedClientCreate) prepare(turn *nodeConfigTurn, remote *runtime.Remote, previous, inbound *model.Inbound, client string, prunedOrphans bool) { + q.turn, q.remote, q.tag, q.client = turn, remote, inbound.Tag, client + q.queuedAt = time.Now() + if !prunedOrphans { + q.advance = remote.PreparePushedInboundAdvance(previous, inbound) + } +} + +func (s *ClientService) pushClientCreates(parent context.Context, pushes []queuedClientCreate) (bool, error) { + ctx, cancel := context.WithTimeout(parent, nodeClientPushTimeout) + defer cancel() + byNode := make(map[int][]*queuedClientCreate) + var nodeOrder []int + for i := range pushes { + push := &pushes[i] + if push.turn == nil { + continue + } + nodeID := push.turn.nodeID + if len(byNode[nodeID]) == 0 { + nodeOrder = append(nodeOrder, nodeID) + } + byNode[nodeID] = append(byNode[nodeID], push) + } + + applies := make([]inboundApply, 0, len(byNode)) + // Reserve one delivery slot per admitted node. Extra groups use spare capacity. + spare := make(chan struct{}, max(0, inboundFanoutConcurrency-len(byNode))) + for _, nodeID := range nodeOrder { + group := byNode[nodeID] + applies = append(applies, inboundApply{id: group[0].turn.inboundID, nodeID: &nodeID, run: func() (bool, error) { + s.pushClientCreatesOnNode(ctx, spare, group) + return false, nil + }}) + } + return fanoutInboundApplies(applies) +} + +func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, spare chan struct{}, pending []*queuedClientCreate) { + queue := pending[0].turn.queue + nodeID := pending[0].turn.nodeID + defer func() { + for _, push := range pending { + push.turn.release() + } + }() + var workers sync.WaitGroup + defer workers.Wait() + primary := make(chan struct{}, 1) + for len(pending) > 0 { + if err := ctx.Err(); err != nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + return + } + changed := queue.changes() + type batchKey struct { + remote *runtime.Remote + client string + } + var batches [][]*queuedClientCreate + positions := make(map[batchKey]int) + var waiting []*queuedClientCreate + for _, push := range pending { + select { + case <-push.turn.ready: + key := batchKey{remote: push.remote, client: push.client} + i, found := positions[key] + if !found { + i = len(batches) + positions[key] = i + batches = append(batches, nil) + } + batches[i] = append(batches[i], push) + default: + waiting = append(waiting, push) + } + } + if len(batches) == 0 { + select { + case <-changed: + case <-ctx.Done(): + } + continue + } + // Release ready lanes before waiting for lanes behind a node-wide turn. + for _, batch := range batches { + slot := reserveClientCreateSlot(ctx, primary, spare) + if slot == nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, ctx.Err()) + return + } + run := func() { + defer func() { <-slot }() + defer func() { + for _, push := range batch { + push.turn.release() + } + }() + s.applyClientCreateBatch(ctx, nodeID, queue, batch) + } + if len(batches) == 1 && len(waiting) == 0 { + run() + } else { + workers.Go(run) + } + } + pending = waiting + } +} + +func reserveClientCreateSlot(ctx context.Context, primary, spare chan struct{}) chan struct{} { + select { + case primary <- struct{}{}: + return primary + default: + } + select { + case primary <- struct{}{}: + return primary + case spare <- struct{}{}: + return spare + case <-ctx.Done(): + return nil + } +} + +func (s *ClientService) applyClientCreateBatch(ctx context.Context, nodeID int, queue *nodeConfigQueue, batch []*queuedClientCreate) { + if err := ctx.Err(); err != nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + return + } + if !queue.acquireLive() { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) + return + } + defer queue.releaseLive() + defer func() { + if panicValue := recover(); panicValue != nil { + for _, push := range batch { + push.remote.ForgetPushedInbound(push.tag) + } + err := fmt.Errorf("panic applying grouped client create: %v", panicValue) + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + logger.Errorf("%v for node %d\n%s", err, nodeID, debug.Stack()) + } + }() + tags := make([]string, len(batch)) + for i, push := range batch { + tags[i] = push.tag + } + remote := batch[0].remote + started := time.Now() + result, acknowledged, err := remote.AddClientGroup(ctx, tags, json.RawMessage(batch[0].client)) + if err != nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + logger.Warning("Error applying clients on", remote.Name(), ":", err) + } + for i, push := range batch { + if i >= len(acknowledged) || !acknowledged[i] || push.advance == nil { + remote.ForgetPushedInbound(push.tag) + s.recordClientNodePush(nodeID, i < len(acknowledged) && acknowledged[i] && result.DownstreamPending, result, nil) + continue + } + push.advance() + s.recordClientNodePush(nodeID, true, result, nil) + } + logger.Debugf("client create node apply: node_id=%d inbounds=%d queue_wait_ms=%d rpc_ms=%d", + nodeID, len(tags), started.Sub(batch[0].queuedAt).Milliseconds(), time.Since(started).Milliseconds()) +} diff --git a/internal/web/service/client_create_fanout_test.go b/internal/web/service/client_create_fanout_test.go index 4b8ada29c..940ca93e4 100644 --- a/internal/web/service/client_create_fanout_test.go +++ b/internal/web/service/client_create_fanout_test.go @@ -56,6 +56,248 @@ func TestCreateAcrossManyInboundsUsesOneEmailSnapshot(t *testing.T) { } } +func TestCreateGroupsCompatibleInboundsOnOneRemote(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + first := realNodeInbound(t, fake, 40301, nil) + ids := []int{first.Id} + remoteIDs := []int{101} + for i := 1; i < 11; i++ { + ib := nodeInbound(t, *first.NodeID, 40301+i, nil) + ids = append(ids, ib.Id) + remoteIDs = append(remoteIDs, 101+i) + fake.tags[ib.Tag] = 101 + i + } + + svc := (&ClientService{}).TrackNodeApplies() + const email = "grouped@x" + const uuid = "bbbbbbbb-1111-2222-3333-555555555555" + for range 2 { + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: email, ID: uuid, SubID: "sub-grouped", Enable: true}, InboundIds: ids, + }) + if err != nil { + t.Fatal(err) + } + } + + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + if len(pushes) != 1 { + t.Fatalf("client add RPCs = %d, want one for all 11 inbounds and none on retry", len(pushes)) + } + slices.Sort(pushes[0].InboundIds) + if !slices.Equal(pushes[0].InboundIds, remoteIDs) || pushes[0].Client.ID != uuid { + t.Fatalf("node received wrong IDs or credentials: %+v", pushes[0]) + } + rec := lookupClientRecord(t, email) + attached, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil { + t.Fatal(err) + } + slices.Sort(attached) + if !slices.Equal(attached, ids) { + t.Fatalf("local attachments = %v, want %v", attached, ids) + } + if r := svc.NodeApplyResponse(); r == nil || r.NodePending || !slices.Equal(r.NodeResults, []ClientNodeApplyOutcome{ + {NodeID: *first.NodeID, Status: "applied"}, + }) { + t.Fatalf("node outcome = %+v, want applied", r) + } +} + +func TestCreateSplitsFlowAndSendsResolvedInbounds(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + raw := realNodeInbound(t, fake, 40321, nil) + tls := nodeInbound(t, *raw.NodeID, 40322, nil) + missing := nodeInbound(t, *raw.NodeID, 40323, nil) + if err := database.GetDB().Model(tls).Update("stream_settings", `{"network":"tcp","security":"tls"}`).Error; err != nil { + t.Fatal(err) + } + fake.tags[tls.Tag] = 122 + + svc := (&ClientService{}).TrackNodeApplies() + const flow = "xtls-rprx-vision" + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "split@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Flow: flow, Enable: true}, + InboundIds: []int{raw.Id, tls.Id, missing.Id}, + }) + if err != nil { + t.Fatal(err) + } + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + slices.SortFunc(pushes, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] }) + if len(pushes) != 2 || !slices.Equal(pushes[0].InboundIds, []int{121}) || !slices.Equal(pushes[1].InboundIds, []int{122}) || + pushes[0].Client.Flow != "" || pushes[1].Client.Flow != flow { + t.Fatalf("wrong delivery for mixed flow and missing tag: %+v", pushes) + } + res := svc.NodeApplyResponse() + want := []ClientNodeApplyOutcome{{NodeID: *raw.NodeID, Status: "pending", Reason: "push_failed"}} + if res == nil || !res.NodePending || !slices.Equal(res.NodeResults, want) { + t.Fatalf("node outcome = %+v, want %v", res, want) + } + _, _, dirty, _, err := (&NodeService{}).NodeSyncState(*raw.NodeID) + if err != nil || !dirty { + t.Fatalf("missing inbound must leave a durable reconcile: dirty=%t err=%v", dirty, err) + } +} + +func TestCreateUsesEffectiveAllowedIPsOnRemote(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + wg := realNodeInbound(t, fake, 40331, nil) + awg := nodeInbound(t, *wg.NodeID, 40332, nil) + for _, inbound := range []struct { + id int + protocol model.Protocol + settings string + }{ + {id: wg.Id, protocol: model.WireGuard, settings: wgServerSettings()}, + {id: awg.Id, protocol: model.AmneziaWG, settings: amneziawgClientTestSettings}, + } { + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", inbound.id). + Updates(map[string]any{"protocol": inbound.protocol, "settings": inbound.settings}).Error; err != nil { + t.Fatal(err) + } + } + fake.tags[awg.Tag] = 132 + + _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{ + Email: "split-tunnel@x", Enable: true, + AllowedIPsByInbound: map[int][]string{wg.Id: {"10.0.0.9/32"}, awg.Id: {"10.8.1.9/32"}}, + }, + InboundIds: []int{wg.Id, awg.Id}, + }) + if err != nil { + t.Fatal(err) + } + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + slices.SortFunc(pushes, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] }) + if len(pushes) != 2 { + t.Fatalf("node received %d add requests, want 2 distinct tunnel payloads", len(pushes)) + } + for i, addr := range []string{"10.0.0.9/32", "10.8.1.9/32"} { + push := pushes[i] + if !slices.Equal(push.InboundIds, []int{131 + i}) || !slices.Equal(push.Client.AllowedIPs, []string{addr}) || + len(push.Client.AllowedIPsByInbound) != 0 { + t.Fatalf("tunnel %d payload = %+v, want remote inbound %d and %s", i, push, 131+i, addr) + } + } +} + +func TestCreateDispatchesReadyLaneBeforeBlockedLane(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + first := realNodeInbound(t, fake, 40341, nil) + second := nodeInbound(t, *first.NodeID, 40342, nil) + fake.tags[second.Tag] = 142 + predecessor := reserveNodeConfigTurn(*first.NodeID, first.Id, nodeClientDelta) + defer predecessor.release() + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan struct{}) + var saveErr error + go func() { + defer close(done) + _, saveErr = (&ClientService{}).CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "ordered-add@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Enable: true}, + InboundIds: []int{first.Id, second.Id}, + }) + }() + t.Cleanup(func() { + cancel() + <-done + }) + wantRPC := func(remoteID int) { + t.Helper() + select { + case got := <-fake.clientAddEvents: + if !slices.Equal(got.InboundIds, []int{remoteID}) { + t.Fatalf("node received inbound IDs %v, want [%d]", got.InboundIds, remoteID) + } + case <-time.After(5 * time.Second): + t.Fatalf("ready inbound %d was not dispatched", remoteID) + } + } + wantRPC(142) + predecessor.release() + wantRPC(141) + select { + case <-done: + if saveErr != nil { + t.Fatal(saveErr) + } + case <-time.After(5 * time.Second): + t.Fatal("create waited after both requests were delivered") + } +} + +func TestCreateCancellationStopsFurtherNodeWaves(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + const nodeCount = inboundFanoutConcurrency + 1 + fakes := make([]*fakeNodeHTTP, nodeCount) + var ids []int + for i := range nodeCount { + fakes[i] = newFakeNodeHTTP(t) + fakes[i].setHold(true) + ids = append(ids, realNodeInbound(t, fakes[i], 40351+i, nil).Id) + } + + svc := (&ClientService{}).TrackNodeApplies() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + var saveErr error + go func() { + defer close(done) + _, saveErr = svc.CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "cancel-add@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Enable: true}, + InboundIds: ids, + }) + }() + t.Cleanup(func() { cancel(); <-done }) + deadline := time.After(5 * time.Second) + for _, fake := range fakes[:inboundFanoutConcurrency] { + select { + case <-fake.clientAddEvents: + case <-deadline: + t.Fatal("the first wave did not reach every admitted node") + } + } + cancel() + select { + case <-done: + if saveErr != nil { + t.Fatal(saveErr) + } + case <-time.After(3 * time.Second): + t.Fatal("cancelled pushes held up the create") + } + if got := fakes[nodeCount-1].hitCount("/clients/add"); got != 0 { + t.Fatalf("queued node received %d RPCs after request cancellation", got) + } + rec := lookupClientRecord(t, "cancel-add@x") + links, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil || len(links) != nodeCount { + t.Fatalf("cancellation lost a committed membership: %v, err=%v", links, err) + } + if res := svc.NodeApplyResponse(); res == nil || !res.NodePending || len(res.NodeResults) != nodeCount { + t.Fatalf("node outcome = %+v, want all %d pending", res, nodeCount) + } +} + func TestAttachAcrossManyInboundsUsesOneEmailSnapshot(t *testing.T) { setupBulkDB(t) svc := &ClientService{} diff --git a/internal/web/service/client_create_order_test.go b/internal/web/service/client_create_order_test.go new file mode 100644 index 000000000..7e6cfb191 --- /dev/null +++ b/internal/web/service/client_create_order_test.go @@ -0,0 +1,308 @@ +package service + +import ( + "context" + "net/http" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +func TestGroupedCreateOrdersLaterClientMutations(t *testing.T) { + for _, change := range []string{"update", "rename", "detach", "delete", "delete and reattach"} { + t.Run(change, func(t *testing.T) { + peer, node, ibs, _ := setupGroupedCreatePeer(t) + db := database.GetDB() + svc, inboundSvc := &ClientService{}, &InboundService{} + client := groupedRecoveryClient("ordered-group@x") + updateEmail := client.Email + if change == "rename" { + updateEmail = "renamed-group@x" + } + blocked, release := make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + var workers sync.WaitGroup + t.Cleanup(func() { free(); workers.Wait() }) + var requests atomic.Int32 + calls := make(chan string, 8) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + calls <- "add" + if requests.Add(1) == 1 { + close(blocked) + select { + case <-release: + case <-r.Context().Done(): + return + } + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + } + peer.mutate = func(w http.ResponseWriter, r *http.Request) { + calls <- r.URL.Path + _, _ = w.Write([]byte(`{"success":true}`)) + } + async := func(op func() (bool, error)) <-chan error { + done := make(chan error, 1) + workers.Go(func() { _, err := op(); done <- err }) + return done + } + created := async(func() (bool, error) { + return svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{ibs[0].Id, ibs[1].Id}}) + }) + waitTrafficWriterSignal(t, blocked, "grouped create never reached the node") + original := lookupClientRecord(t, client.Email) + before := groupedDirtyGeneration(t, node.Id) + const callback = "test:observe-later-grouped-commit" + marked := make(chan struct{}, 8) + if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == "nodes" && strings.Contains(tx.Statement.SQL.String(), "config_dirty_at") { + marked <- struct{}{} + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) }) + waitCommit := func(previous int64) int64 { + t.Helper() + deadline := time.After(2 * time.Second) + for { + select { + case <-marked: + case <-deadline: + t.Fatal("later local mutation did not advance the dirty generation") + } + if err := submitTrafficWrite(func() error { return nil }); err != nil { + t.Fatal(err) + } + if generation := groupedDirtyGeneration(t, node.Id); generation > previous { + return generation + } + } + } + mutated := async(func() (bool, error) { + switch change { + case "update", "rename": + next := client + next.Comment, next.Email = "committed later", updateEmail + return svc.UpdateByEmail(inboundSvc, client.Email, next, 0, ibs[0].Id) + case "detach": + return svc.DetachByEmail(inboundSvc, ibs[0].Id, client.Email) + default: + return svc.DeleteByEmail(inboundSvc, client.Email, false) + } + }) + after := waitCommit(before) + if change == "update" || change == "rename" { + for { + stored, ok := settingsClient(t, ibs[0].Id, updateEmail) + if ok && stored.Comment == "committed later" { + break + } + after = waitCommit(after) + } + } + if strings.HasPrefix(change, "delete") { + for { + links, err := svc.GetInboundIdsForRecord(original.Id) + if err != nil { + t.Fatal(err) + } + if len(links) == 0 { + break + } + after = waitCommit(after) + } + } + deletes := func() int64 { + t.Helper() + var n int64 + if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email = ?", node.Id, client.Email).Count(&n).Error; err != nil { + t.Fatal(err) + } + return n + } + var reattached <-chan error + if strings.HasPrefix(change, "delete") && deletes() != 1 { + t.Fatal("queued full delete has no durable outbox entry") + } + if change == "delete and reattach" { + reattached = async(func() (bool, error) { + return svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{ibs[0].Id}}) + }) + waitCommit(after) + } + if err := (&NodeService{}).ClearNodeDirty(node.Id, before); err != nil { + t.Fatal(err) + } + groupedDirtyGeneration(t, node.Id) + if len(calls) != 1 { + t.Fatalf("later operation reached peer before grouped create acknowledgment (%d calls)", len(calls)) + } + free() + done := []<-chan error{created, mutated} + if reattached != nil { + done = append(done, reattached) + } + for i, settled := range done { + if err := waitTrafficWriterErr(t, settled); err != nil { + t.Fatalf("operation %d failed: %v", i+1, err) + } + } + var got []string + for len(calls) > 0 { + got = append(got, <-calls) + } + second := "/panel/api/clients/update/" + client.Email + switch change { + case "detach": + second = "/panel/api/clients/" + client.Email + "/detach" + case "delete": + second = "/panel/api/clients/del/" + client.Email + case "delete and reattach": + second = "add" + } + if !slices.Equal(got, []string{"add", second}) { + t.Fatalf("remote order = %v, want [add %s]", got, second) + } + if deletes() != 0 { + t.Fatal("completed or superseded delete was retained") + } + if reattached != nil { + rec := lookupClientRecord(t, client.Email) + links, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil || !slices.Equal(links, []int{ibs[0].Id}) { + t.Fatalf("later attachment lost: %v, err=%v", links, err) + } + } + }) + } +} + +func TestGroupedCreateKeepsFifthNodeDurablyPendingWhenBudgetExpires(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const nodes = inboundFanoutConcurrency + 1 + var peers []*fakeNodeHTTP + var ids []int + var healthy *model.Inbound + for i := range nodes { + fake := newFakeNodeHTTP(t) + fake.setHold(i < inboundFanoutConcurrency) + peers = append(peers, fake) + healthy = realNodeInbound(t, fake, 46231+i, nil) + ids = append(ids, healthy.Id) + } + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + started := time.Now() + client := groupedRecoveryClient("fifth-destination@x") + if _, err := svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: ids}); err != nil { + t.Fatal(err) + } + elapsed := time.Since(started) + if elapsed >= 2*nodeClientPushTimeout { + t.Fatalf("create took %v, want one delivery window", elapsed) + } + status := svc.NodeApplyResponse() + if status == nil || !status.NodePending || len(status.NodeResults) != nodes { + t.Fatalf("node outcomes = %+v, want %d pending", status, nodes) + } + for i, p := range peers { + want := 1 + if i == inboundFanoutConcurrency { + want = 0 + } + if got := p.hitCount("/clients/add"); got != want { + t.Fatalf("peer %d received %d adds, want %d with shared timeout", i, got, want) + } + if outcome := status.NodeResults[i]; outcome.Status != "pending" || outcome.Reason != "timeout" { + t.Fatalf("peer %d outcome = %+v, want timeout", i, outcome) + } + } + inboundID := *healthy.NodeID + groupedDirtyGeneration(t, inboundID) + if got := settingsClientEmails(t, healthy.Id); !slices.Equal(got, []string{client.Email}) { + t.Fatalf("healthy peer membership was dropped: %v", got) + } + var node model.Node + if err := database.GetDB().First(&node, inboundID).Error; err != nil { + t.Fatal(err) + } + rt, err := mgr.RuntimeFor(&inboundID) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + if err := inboundSvc.ReconcileNode(ctx, rt.(*runtime.Remote), &node); err != nil { + t.Fatal(err) + } + if got := peers[nodes-1].hitCount("/inbounds/update/"); got != 1 { + t.Fatalf("healthy peer received %d recovery updates, want 1", got) + } + t.Logf("four slow deliveries used %v and the fifth peer converged on reconciliation", elapsed) +} + +func TestGroupedCreateReconcileBarrierDrainsAfterAcknowledgment(t *testing.T) { + peer, node, ibs, remote := setupGroupedCreatePeer(t) + blocked, release := make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + var workers sync.WaitGroup + t.Cleanup(func() { free(); workers.Wait() }) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + close(blocked) + select { + case <-release: + case <-r.Context().Done(): + return + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + } + created, reconciled := make(chan error, 1), make(chan error, 1) + inboundSvc := &InboundService{} + workers.Go(func() { + _, err := (&ClientService{}).Create(inboundSvc, &ClientCreatePayload{ + Client: groupedRecoveryClient("reconcile-barrier@x"), InboundIds: []int{ibs[0].Id, ibs[1].Id}, + }) + created <- err + }) + waitTrafficWriterSignal(t, blocked, "grouped add never reached peer") + workers.Go(func() { reconciled <- inboundSvc.ReconcileNode(t.Context(), remote, node) }) + deadline := time.Now().Add(2 * time.Second) + for { + nodeConfigDispatchMu.Lock() + q := nodeConfigDispatch[node.Id] + waiting := q != nil && q.reconciles == 1 + nodeConfigDispatchMu.Unlock() + if waiting { + break + } + select { + case err := <-reconciled: + t.Fatalf("reconcile overtook the blocked grouped create, err=%v", err) + default: + } + if time.Now().After(deadline) { + t.Fatal("reconciliation never reached the node-wide barrier") + } + time.Sleep(time.Millisecond) + } + free() + for _, done := range []<-chan error{created, reconciled} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } + assertGroupedRecovery(t, peer, node, remote, ibs, 1, nil) +} diff --git a/internal/web/service/client_create_reconcile_test.go b/internal/web/service/client_create_reconcile_test.go new file mode 100644 index 000000000..65567d38e --- /dev/null +++ b/internal/web/service/client_create_reconcile_test.go @@ -0,0 +1,487 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +type groupedCreatePeer struct { + mu sync.Mutex + tags map[string]int + settings map[int]string + adds []ClientCreatePayload + updates []int + respond func(http.ResponseWriter, *http.Request, ClientCreatePayload, func(int)) + mutate func(http.ResponseWriter, *http.Request) +} + +func (p *groupedCreatePeer) serve(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + p.mu.Lock() + catalog := make([]runtime.RemoteInboundOption, 0, len(p.tags)) + for tag, id := range p.tags { + catalog = append(catalog, runtime.RemoteInboundOption{Id: id, Tag: tag}) + } + p.mu.Unlock() + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": catalog}) + case strings.HasSuffix(r.URL.Path, "/clients/add"): + var payload ClientCreatePayload + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + p.mu.Lock() + p.adds = append(p.adds, payload) + p.mu.Unlock() + apply := func(count int) { + p.mu.Lock() + defer p.mu.Unlock() + for _, id := range payload.InboundIds[:count] { + var settings map[string]any + _ = json.Unmarshal([]byte(p.settings[id]), &settings) + clients, _ := settings["clients"].([]any) + if slices.ContainsFunc(clients, func(entry any) bool { + _, email := clientEntryEmail(entry) + return email == payload.Client.Email + }) { + continue + } + settings["clients"] = append(clients, payload.Client) + encoded, _ := json.Marshal(settings) + p.settings[id] = string(encoded) + } + } + if p.respond != nil { + p.respond(w, r, payload, apply) + return + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + case strings.Contains(r.URL.Path, "/inbounds/update/"): + _, suffix, _ := strings.Cut(r.URL.Path, "/inbounds/update/") + id, err := strconv.Atoi(suffix) + if err != nil || r.ParseForm() != nil || r.Form.Get("settings") == "" { + http.Error(w, "missing inbound ID or settings", http.StatusBadRequest) + return + } + p.mu.Lock() + p.settings[id] = r.Form.Get("settings") + p.updates = append(p.updates, id) + p.mu.Unlock() + _, _ = w.Write([]byte(`{"success":true}`)) + default: + if p.mutate == nil { + http.NotFound(w, r) + } else { + p.mutate(w, r) + } + } +} + +func TestGroupedCreateRecoversIndeterminateDelivery(t *testing.T) { + for _, tc := range []struct { + name string + reason string + reply func(w http.ResponseWriter, r *http.Request, apply func(int)) + }{ + {"partially applied HTTP error", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(1) + http.Error(w, "second write failed", http.StatusInternalServerError) + }}, + {"lost acknowledgment", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(2) + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + } + }}, + {"deadline after persistence", "timeout", func(_ http.ResponseWriter, r *http.Request, apply func(int)) { + apply(2) + <-r.Context().Done() + }}, + {"malformed acknowledgment", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(1) + _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":"unknown"}}`)) + }}, + {"downstream pending", "downstream_pending", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(2) + _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":true}}`)) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + peer.respond = func(w http.ResponseWriter, r *http.Request, _ ClientCreatePayload, apply func(int)) { + tc.reply(w, r, apply) + } + client := groupedRecoveryClient("unknown-delivery@x") + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + payload := &ClientCreatePayload{Client: client, InboundIds: []int{inbounds[0].Id, inbounds[1].Id}} + if _, err := svc.Create(inboundSvc, payload); err != nil { + t.Fatal(err) + } + wantGroupedOutcome(t, &svc, node.Id, "pending", tc.reason) + dirtyAt := groupedDirtyGeneration(t, node.Id) + if _, err := (&ClientService{}).Create(inboundSvc, payload); err != nil { + t.Fatal(err) + } + if got := groupedDirtyGeneration(t, node.Id); dirtyAt != got { + t.Fatalf("idempotent create changed generation from %d to %d", dirtyAt, got) + } + for _, inbound := range inbounds { + if got := settingsClientEmails(t, inbound.Id); !slices.Equal(got, []string{client.Email}) { + t.Fatalf("master inbound %d lost or duplicated commits: %v", inbound.Id, got) + } + } + want := []int{101, 102} + if tc.reason == "downstream_pending" { + want = nil + } + assertGroupedRecovery(t, peer, node, remote, inbounds, 1, want) + }) + } +} + +func TestGroupedCreateDispatchesIndependentReadyPayload(t *testing.T) { + peer, _, inbounds, _ := setupGroupedCreatePeer(t) + first, second := inbounds[0], inbounds[1] + if err := database.GetDB().Model(first).Update("stream_settings", `{"network":"tcp","security":"reality"}`).Error; err != nil { + t.Fatal(err) + } + slow, healthy, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + t.Cleanup(free) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + if slices.Equal(payload.InboundIds, []int{101}) && payload.Client.Flow == "xtls-rprx-vision" { + close(slow) + select { + case <-release: + case <-r.Context().Done(): + return + } + } else if slices.Equal(payload.InboundIds, []int{102}) && payload.Client.Flow == "" { + close(healthy) + } else { + http.Error(w, "unexpected grouping", http.StatusBadRequest) + return + } + apply(1) + _, _ = w.Write([]byte(`{"success":true}`)) + } + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) + done := make(chan struct{}) + var createErr error + t.Cleanup(func() { cancel(); free(); <-done }) + go func() { + defer close(done) + client := groupedRecoveryClient("independent-flow@x") + client.Flow = "xtls-rprx-vision" + _, createErr = (&ClientService{}).CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: client, InboundIds: []int{first.Id, second.Id}, + }) + }() + for _, call := range []<-chan struct{}{slow, healthy} { + select { + case <-call: + case <-ctx.Done(): + t.Fatal("independent payload waited behind the parked RPC") + } + } + free() + <-done + if createErr != nil { + t.Fatal(createErr) + } +} + +func TestGroupedCreateRepairsDeferredTargets(t *testing.T) { + for _, scenario := range []string{"missing tag", "disabled client", "pruned orphan", "one rollback", "transport panic"} { + t.Run(scenario, func(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + first, second := inbounds[0], inbounds[1] + db := database.GetDB() + wantAdds, status, reason, want := 1, "pending", "deferred", []int{101} + client := groupedRecoveryClient("recover-target@x") + switch scenario { + case "missing tag": + delete(peer.tags, first.Tag) + reason = "push_failed" + case "disabled client": + client.Enable = false + wantAdds, want = 0, []int{101, 102} + case "pruned orphan": + first.Settings = clientsSettings(t, []model.Client{groupedRecoveryClient("removed@x")}) + if err := db.Model(first).Update("settings", first.Settings).Error; err != nil { + t.Fatal(err) + } + remote.RecordAdoptedInbound(first) + peer.settings[101] = first.Settings + case "one rollback": + status, reason, want = "failed", "local_save_failed", nil + const callback = "test:grouped-create-local-rollback" + if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) { + vars := tx.Statement.Vars + if tx.Statement.Table == "inbounds" && len(vars) == 2 && vars[1] == first.Id { + _ = tx.AddError(errors.New("forced create rollback")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) }) + case "transport panic": + wantAdds, reason, want = 0, "push_failed", []int{101, 102} + failing := *node + failing.OutboundTag = "test-egress" + remote = runtime.NewRemote(&failing, panickingCreateEgress{}) + runtime.GetManager().SetRuntimeOverride(node.Id, remote) + for _, inbound := range inbounds { + remote.RecordAdoptedInbound(inbound) + } + } + svc := (&ClientService{}).TrackNodeApplies() + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{Client: client, InboundIds: []int{first.Id, second.Id}}) + if scenario == "one rollback" { + if err == nil || !strings.Contains(err.Error(), "forced create rollback") { + t.Fatalf("partial local failure = %v", err) + } + if _, ok := settingsClient(t, first.Id, client.Email); ok { + t.Fatal("rolled back inbound retained its client") + } + } else if err != nil { + t.Fatal(err) + } + if _, ok := settingsClient(t, second.Id, client.Email); !ok { + t.Fatal("successful inbound lost its committed client") + } + wantGroupedOutcome(t, &svc, node.Id, status, reason) + groupedDirtyGeneration(t, node.Id) + if scenario == "transport panic" { + nodeConfigDispatchMu.Lock() + leftover := nodeConfigDispatch[node.Id] + nodeConfigDispatchMu.Unlock() + if leftover != nil { + t.Fatal("recovered transport panic left a reserved node turn") + } + remote = runtime.NewRemote(node, nil) + } + peer.mu.Lock() + peer.tags[first.Tag] = 101 + peer.mu.Unlock() + assertGroupedRecovery(t, peer, node, remote, inbounds, wantAdds, want) + }) + } +} + +type panickingCreateEgress struct{} + +func (panickingCreateEgress) NodeEgressProxyURL(int) string { panic("fixture egress failure") } + +func TestGroupedCreatePreservesProtocolCredentials(t *testing.T) { + for _, tc := range []struct { + protocol model.Protocol + settings string + check func(model.Client) bool + }{ + {model.Shadowsocks, `{"clients":[],"method":"2022-blake3-aes-128-gcm"}`, func(c model.Client) bool { + return validShadowsocksClientKey("2022-blake3-aes-128-gcm", c.Password) + }}, + {model.MTProto, `{"clients":[],"fakeTlsDomain":"example.test"}`, func(c model.Client) bool { return c.Secret != "" }}, + {model.TUIC, `{"clients":[]}`, func(c model.Client) bool { return c.ID != "" && c.Password != "" }}, + } { + t.Run(string(tc.protocol), func(t *testing.T) { + peer, _, inbounds, remote := setupGroupedCreatePeer(t) + db := database.GetDB() + var ids []int + for _, ib := range inbounds { + if err := db.Model(ib).Updates(map[string]any{"protocol": tc.protocol, "settings": tc.settings}).Error; err != nil { + t.Fatal(err) + } + ids = append(ids, ib.Id) + } + first, second := inbounds[0], inbounds[1] + delete(peer.tags, first.Tag) + peer.tags["adopted-legacy-tag"] = 101 + remote.AdoptInboundAlias(first, runtime.RemoteInboundOption{Tag: "adopted-legacy-tag", Id: 101}) + delete(peer.tags, second.Tag) + peer.tags["n"+strconv.Itoa(*second.NodeID)+"-"+second.Tag] = 102 + + const email = "protocol-default-create" + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: email, Enable: true}, InboundIds: ids, + }); err != nil { + t.Fatal(err) + } + peer.mu.Lock() + adds := slices.Clone(peer.adds) + peer.mu.Unlock() + if len(adds) != 1 || !slices.Equal(adds[0].InboundIds, []int{101, 102}) || !tc.check(adds[0].Client) { + t.Fatalf("expected one acknowledged %s add with generated credentials and both mapped IDs", tc.protocol) + } + want := adds[0].Client + for _, ib := range inbounds { + local, ok := settingsClient(t, ib.Id, email) + if !ok || local.ID != want.ID || local.Secret != want.Secret || local.Password != want.Password { + t.Fatalf("grouped RPC changed the local %s credentials for inbound %d", tc.protocol, ib.Id) + } + } + }) + } +} + +func groupedRecoveryClient(email string) model.Client { + return model.Client{ + Email: email, Enable: true, ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: email, + } +} + +func wantGroupedOutcome(t *testing.T, svc *ClientService, nodeID int, status, reason string) { + t.Helper() + res := svc.NodeApplyResponse() + want := []ClientNodeApplyOutcome{{NodeID: nodeID, Status: status, Reason: reason}} + if res == nil || res.NodePending != (status == "pending") || !slices.Equal(res.NodeResults, want) { + t.Fatalf("node outcome = %+v, want %v", res, want) + } +} + +func groupedDirtyGeneration(t *testing.T, nodeID int) int64 { + t.Helper() + _, _, dirty, generation, err := (&NodeService{}).NodeSyncState(nodeID) + if err != nil || !dirty || generation <= 0 { + t.Fatalf("node dirty=%t generation=%d err=%v", dirty, generation, err) + } + return generation +} + +func assertGroupedRecovery(t *testing.T, peer *groupedCreatePeer, node *model.Node, remote *runtime.Remote, inbounds []*model.Inbound, addCount int, wantUpdates []int) { + t.Helper() + svc := &InboundService{} + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + for range 2 { + if err := svc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + } + peer.mu.Lock() + defer peer.mu.Unlock() + slices.Sort(peer.updates) + if len(peer.adds) != addCount || !slices.Equal(peer.updates, wantUpdates) { + t.Fatalf("add RPCs=%d, repaired IDs=%v, want %d and %v", len(peer.adds), peer.updates, addCount, wantUpdates) + } + for _, ib := range inbounds { + master := settingsClientEmails(t, ib.Id) + var doc struct{ Clients []model.Client } + if err := json.Unmarshal([]byte(peer.settings[peer.tags[ib.Tag]]), &doc); err != nil { + t.Fatal(err) + } + if got := emailsOf(doc.Clients); !slices.Equal(got, master) { + t.Fatalf("node inbound %q has %v, master has %v", ib.Tag, got, master) + } + } +} + +func setupGroupedCreatePeer(t *testing.T) (*groupedCreatePeer, *model.Node, []*model.Inbound, *runtime.Remote) { + t.Helper() + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + peer := &groupedCreatePeer{tags: map[string]int{}, settings: map[int]string{}} + srv := httptest.NewServer(http.HandlerFunc(peer.serve)) + t.Cleanup(srv.Close) + nodeHTTP := &fakeNodeHTTP{srv: srv, tags: peer.tags} + first := realNodeInbound(t, nodeHTTP, 46201, nil) + second := nodeInbound(t, *first.NodeID, 46202, nil) + peer.tags[second.Tag] = 102 + var node model.Node + if err := database.GetDB().First(&node, *first.NodeID).Error; err != nil { + t.Fatal(err) + } + rt, err := mgr.RuntimeFor(&node.Id) + if err != nil { + t.Fatal(err) + } + remote, ok := rt.(*runtime.Remote) + if !ok { + t.Fatalf("runtime = %T, want actual remote", rt) + } + inbounds := []*model.Inbound{first, second} + for _, inbound := range inbounds { + remote.RecordAdoptedInbound(inbound) + peer.settings[peer.tags[inbound.Tag]] = inbound.Settings + } + return peer, &node, inbounds, remote +} + +func TestGroupedCreateReconcilesUnsentRebasedSettings(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + changed := inbounds[0] + client := model.Client{ + Email: "group-rebased@x", Enable: true, + ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: "group-rebased", + } + db := database.GetDB() + var reads atomic.Int32 + const callback = "test:concurrent-settings-before-grouped-write" + if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) { + read, ok := tx.Statement.Dest.(*model.Inbound) + if ok && read.Id == changed.Id && reads.Add(1) == 3 { + _ = tx.AddError(db.Model(&model.Inbound{}).Where("id = ?", changed.Id). + Update("settings", `{"clients":[],"decryption":"none"}`).Error) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + _, createErr := svc.Create(inboundSvc, &ClientCreatePayload{ + Client: client, InboundIds: []int{changed.Id, inbounds[1].Id}, + }) + if createErr != nil { + t.Fatal(createErr) + } + for _, inbound := range inbounds { + if c, ok := settingsClient(t, inbound.Id, client.Email); !ok || c.ID != client.ID { + t.Fatalf("master lost grouped client in inbound %d: %+v", inbound.Id, c) + } + } + stored, err := inboundSvc.GetInbound(changed.Id) + if err != nil || !strings.Contains(stored.Settings, `"decryption": "none"`) { + t.Fatalf("master lost concurrent settings change: %+v, %v", stored, err) + } + peer.mu.Lock() + adds := slices.Clone(peer.adds) + delivered := peer.settings[101] + peer.mu.Unlock() + if len(adds) != 1 || !slices.Equal(adds[0].InboundIds, []int{101, 102}) || adds[0].Client.Email != client.Email || + strings.Contains(delivered, "decryption") || !strings.Contains(delivered, client.Email) { + t.Fatalf("grouped add was not limited to the new client: %+v, peer settings %s", adds, delivered) + } + for range 2 { + if err := inboundSvc.ReconcileNode(t.Context(), remote, node); err != nil { + t.Fatal(err) + } + } + peer.mu.Lock() + defer peer.mu.Unlock() + if !slices.Equal(peer.updates, []int{101}) || peer.settings[101] != stored.Settings { + t.Fatalf("reconcile updates=%v settings=%s, want exactly one repair of inbound 101", peer.updates, peer.settings[101]) + } +} diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 687f45f01..e35b4b6fb 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -1,6 +1,7 @@ package service import ( + "context" "encoding/base64" "encoding/json" "errors" @@ -203,6 +204,11 @@ func quotaDisabledEmails(tx *gorm.DB, within []string) ([]string, error) { // Create applies the client to every requested inbound: one failing inbound no // longer aborts the others, so the error can name several and needRestart holds. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) { + return s.CreateWithContext(context.Background(), inboundSvc, payload) +} + +// CreateWithContext applies the request context to delivery after the local commits. +func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) { if payload == nil { return false, common.NewError("empty payload") } @@ -317,21 +323,19 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate } adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID}) } - needRestart, fanoutErr := s.fanoutInboundClientAdds(inboundSvc, adds) - if fanoutErr != nil { - // Never on a failed create: this retrims the devices of an email that - // already existed, and a create the panel reported as failed must not. - return needRestart, fanoutErr - } - // nil means omitted and preserves the stored binding. - if client.ClientHostRuleIds != nil { - if err := database.GetDB().Model(&model.ClientRecord{}). + pushes := make([]queuedClientCreate, len(adds)) + needRestart, saveErr := s.fanoutInboundClientAdds(inboundSvc, adds, pushes) + // Finish create metadata before remote delivery can overlap a later rename. + if saveErr == nil && client.ClientHostRuleIds != nil { + saveErr = database.GetDB().Model(&model.ClientRecord{}). Where("email = ?", client.Email). - Update("client_host_rule_ids", model.EncodeClientHostRuleIds(client.ClientHostRuleIds)).Error; err != nil { - return needRestart, err - } + Update("client_host_rule_ids", model.EncodeClientHostRuleIds(client.ClientHostRuleIds)).Error } - return needRestart, s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid) + if saveErr == nil { + saveErr = s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid) + } + remoteRestart, pushErr := s.pushClientCreates(ctx, pushes) + return needRestart || remoteRestart, errors.Join(saveErr, pushErr) } // inboundFanoutConcurrency caps how many inbounds one client op applies at @@ -384,12 +388,15 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) { return needRestart.Load(), errors.Join(errs...) } -// fanoutInboundClientAdds applies one payload per inbound. -func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) { +func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound, pushes []queuedClientCreate) (bool, error) { applies := make([]inboundApply, 0, len(adds)) - for _, add := range adds { + for i, add := range adds { + var queued *queuedClientCreate + if pushes != nil { + queued = &pushes[i] + } applies = append(applies, inboundApply{id: add.Id, nodeID: add.NodeID, run: func() (bool, error) { - return s.AddInboundClient(inboundSvc, add) + return s.addInboundClient(inboundSvc, add, queued) }}) } return fanoutInboundApplies(applies) @@ -1143,6 +1150,18 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b } if err := runSerializedTx(func(tx *gorm.DB) error { + // A later create can commit while this delete's node turn is waiting. + var attached []int + if err := tx.Table("client_inbounds"). + Joins("JOIN clients ON clients.id = client_inbounds.client_id"). + Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id"). + Where("clients.id = ? OR clients.email = ?", id, existing.Email). + Limit(1).Pluck("client_inbounds.client_id", &attached).Error; err != nil { + return err + } + if len(attached) != 0 { + return nil + } if existing.Email != "" { if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil { return err @@ -1319,7 +1338,7 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds [] } adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID}) } - return s.fanoutInboundClientAdds(inboundSvc, adds) + return s.fanoutInboundClientAdds(inboundSvc, adds, nil) } func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) { diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index ca0746a39..74e01da35 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -397,6 +397,10 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c } func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (restartNeeded bool, saveErr error) { + return s.addInboundClient(inboundSvc, data, nil) +} + +func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, queued *queuedClientCreate) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(data.Id) defer mutation.close() @@ -712,6 +716,29 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } } else if push && len(clients) <= nodeBulkPushThreshold { + if remote, ok := rt.(*runtime.Remote); ok && queued != nil && len(clients) == 1 { + if mutation.turn == nil || !clients[0].Enable { + s.recordClientNodeDeferred(oldInbound.NodeID) + } else { + mutation.unlock() + client := clients[0] + // Create already selected the effective addresses for this inbound. + client.AllowedIPsByInbound = nil + raw, err := json.Marshal(client) + if err != nil { + s.recordClientNodePush(*oldInbound.NodeID, true, runtime.ClientApplyResult{}, err) + return needRestart, nil + } + previous := *oldInbound + previous.Settings = prevSettings + pushed := *oldInbound + // The add RPC omits unrelated settings merged by the write transaction. + pushed.Settings = string(newSettings) + queued.prepare(mutation.turn, remote, &previous, &pushed, string(raw), prunedOrphans) + mutation.turn = nil + } + return needRestart, nil + } mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for _, client := range clients { // Older nodes coerce enable=true. Reconcile the rest of this batch. diff --git a/internal/web/service/client_node_dispatch.go b/internal/web/service/client_node_dispatch.go index fc3aae0aa..244f7a64c 100644 --- a/internal/web/service/client_node_dispatch.go +++ b/internal/web/service/client_node_dispatch.go @@ -22,6 +22,7 @@ type nodeConfigQueue struct { groups list.List reconciles int live int + changed chan struct{} } // Inbounds in the same group can push concurrently. A node-wide operation @@ -109,6 +110,10 @@ func (t *nodeConfigTurn) release() { return } q, group := t.queue, t.group + if q.changed != nil { + close(q.changed) + q.changed = nil + } lane := group.inbounds[t.inboundID] wasReady := q.groups.Front() == group.position && lane.Front() == t.position lane.Remove(t.position) @@ -136,6 +141,31 @@ func (t *nodeConfigTurn) release() { } } +func (q *nodeConfigQueue) changes() <-chan struct{} { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if q.changed == nil { + q.changed = make(chan struct{}) + } + return q.changed +} + +func (q *nodeConfigQueue) acquireLive() bool { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if q.live >= inboundFanoutConcurrency { + return false + } + q.live++ + return true +} + +func (q *nodeConfigQueue) releaseLive() { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + q.live-- +} + type inboundClientMutation struct { lock *inboundMutationLock turn *nodeConfigTurn @@ -211,19 +241,11 @@ func (m *inboundClientMutation) push(s *ClientService, rt runtime.Runtime, inbou return } // Conflicting turns wait without consuming a live slot. - nodeConfigDispatchMu.Lock() - if m.turn.queue.live >= inboundFanoutConcurrency { - nodeConfigDispatchMu.Unlock() + if !m.turn.queue.acquireLive() { s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) return } - m.turn.queue.live++ - nodeConfigDispatchMu.Unlock() - defer func() { - nodeConfigDispatchMu.Lock() - m.turn.queue.live-- - nodeConfigDispatchMu.Unlock() - }() + defer m.turn.queue.releaseLive() ctx, cancel := nodePushContext() defer cancel() complete := false diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go index b5ce92530..aaf21b930 100644 --- a/internal/web/service/node_http_fake_test.go +++ b/internal/web/service/node_http_fake_test.go @@ -25,6 +25,8 @@ type fakeNodeHTTP struct { hits map[string]int caps string pendingClientAcks int + clientAdds []ClientCreatePayload + clientAddEvents chan ClientCreatePayload // hold makes every non-list request block until the master gives up. hold bool release chan struct{} @@ -32,7 +34,10 @@ type fakeNodeHTTP struct { func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { t.Helper() - f := &fakeNodeHTTP{tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{})} + f := &fakeNodeHTTP{ + tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{}), + clientAddEvents: make(chan ClientCreatePayload, 16), + } f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") f.mu.Lock() @@ -62,6 +67,20 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { f.pendingClientAcks-- } f.mu.Unlock() + if strings.HasSuffix(r.URL.Path, "/clients/add") { + var payload ClientCreatePayload + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + f.mu.Lock() + f.clientAdds = append(f.clientAdds, payload) + f.mu.Unlock() + select { + case f.clientAddEvents <- payload: + default: + } + } if hold { // Drain first: the server only notices a client disconnect once the // body is consumed, and Close would otherwise wait on this forever. From 1e1b32247e1cde1ac60891b8a96051ebfa390e40 Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 00:56:57 +0330 Subject: [PATCH 09/14] perf(clients): avoid repeated inbound settings reads (#7312) Reduce repeated inbound settings materialization with a protocol-aware preparation projection that retains node_id. Reuse the locked validation/mutation snapshot while preserving the transaction-time settings reread and three-way rebase. Gate effective Create/Attach Flow before grouped payload construction; retain public Add and bulk/copy semantics. Preserve #7367 grouped Create, intended-payload fingerprint CAS, ordered turns, cancellation, metadata ordering, durable delete/reattachment safeguards, node outcomes and PostgreSQL lock ordering. Add a mandatory PostgreSQL gate for nine read/protocol regressions without weakening the existing 21 ordering/grouped-create cases. Validation: all 12 CI jobs passed on 9062e5cf9465982c2f21f831c3a8bebd7f4cb0ba (run 46971334865), including PostgreSQL 9/9 and 21/21 focused gates, race, and all four version pairings. Author-reported paired PostgreSQL 16 fixture: 44 -> 22 full reads, 64.82 -> 32.41 MiB materialized per local Create, p95 497.0 -> 400.9 ms; contended Create p95 994.2 -> 633.5 ms and Update 1118.4 -> 937.5 ms. Single-node grouped Create stays one RPC. Necessary protocol/Flow reads and Attach preparation remain; no WAL redesign or production latency claim. Refs #7300 --- .github/workflows/ci.yml | 10 + .../service/client_create_node_reads_test.go | 286 ++++++++++++++++++ .../web/service/client_create_reads_test.go | 174 +++++++++++ .../service/client_create_reconcile_test.go | 12 +- internal/web/service/client_crud.go | 44 ++- internal/web/service/client_inbound_apply.go | 27 +- 6 files changed, 524 insertions(+), 29 deletions(-) create mode 100644 internal/web/service/client_create_node_reads_test.go create mode 100644 internal/web/service/client_create_reads_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 54c7e2e04..5d00c7086 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -165,6 +165,16 @@ jobs: exit 1 fi + - name: PostgreSQL client inbound read regressions + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(ClientCreate(ReadsInboundSettingsOnlyForMutation|ClearsFlowOnIneligibleInbound|PreservesSettingsBasedDefaults)|UpdateInboundClientReadsSettingsOnceBeforeCommit|Slim(Create(UsesLockedFlowForGroupedDelivery|HealthyTargetsProgressWithBlockedPeer|ProjectionPreservesNodeIDAndProtocolSettings)|AttachUsesLockedFlowAndPreservesRawAdd|UpdateRebasesConcurrentSettings))$' -count=1 -v | tee /tmp/postgres-client-inbound-reads.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-client-inbound-reads.log || true) + if [ "$passed" -ne 9 ]; then + echo "expected 9 passing PostgreSQL client inbound read tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL global-traffic heartbeat regressions run: | set -o pipefail diff --git a/internal/web/service/client_create_node_reads_test.go b/internal/web/service/client_create_node_reads_test.go new file mode 100644 index 000000000..4c0d3ed75 --- /dev/null +++ b/internal/web/service/client_create_node_reads_test.go @@ -0,0 +1,286 @@ +package service + +import ( + "context" + "net/http" + "slices" + "sync" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestSlimCreateUsesLockedFlowForGroupedDelivery(t *testing.T) { + peer, _, inbounds, _ := setupGroupedCreatePeer(t) + db := database.GetDB() + first, second := inbounds[0], inbounds[1] + const tls = `{"network":"tcp","security":"tls"}` + const reality = `{"network":"tcp","security":"reality"}` + if err := db.Model(first).Update("stream_settings", tls).Error; err != nil { + t.Fatal(err) + } + third := nodeInbound(t, *first.NodeID, 46203, nil) + peer.tags[third.Tag] = 103 + peer.settings[103] = third.Settings + if err := db.Model(third).Update("settings", `{"clients":[],"decryption":"mlkem768x25519plus.native.0rtt.test"}`).Error; err != nil { + t.Fatal(err) + } + var disableFirst, enableSecond sync.Once + const hook = "test:flow-changes-after-create-preparation-read" + query := db.Callback().Query() + if err := query.After("gorm:query").Register(hook, func(tx *gorm.DB) { + ib, ok := tx.Statement.Dest.(*model.Inbound) + if !ok || tx.Error != nil { + return + } + switch ib.Id { + case first.Id: + disableFirst.Do(func() { _ = tx.AddError(db.Model(first).Update("disable_flow", true).Error) }) + case second.Id: + enableSecond.Do(func() { _ = tx.AddError(db.Model(second).Update("stream_settings", reality).Error) }) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = query.Remove(hook) }) + + const flow = "xtls-rprx-vision" + client := groupedRecoveryClient("locked-flow@x") + client.Flow = flow + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + Client: client, InboundIds: []int{first.Id, second.Id, third.Id}, + }); err != nil { + t.Fatal(err) + } + peer.mu.Lock() + calls := slices.Clone(peer.adds) + peer.mu.Unlock() + slices.SortFunc(calls, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] }) + if len(calls) != 2 || !slices.Equal(calls[0].InboundIds, []int{101}) || calls[0].Client.Flow != "" || + !slices.Equal(calls[1].InboundIds, []int{102, 103}) || calls[1].Client.Flow != flow { + t.Fatalf("peer received %+v, want no flow on 101 and Vision on 102/103", calls) + } + for _, ib := range []*model.Inbound{first, second, third} { + want := flow + if ib.Id == first.Id { + want = "" + } + if c, ok := settingsClient(t, ib.Id, client.Email); !ok || c.Flow != want { + t.Fatalf("stored flow for inbound %d = %q, want %q", ib.Id, c.Flow, want) + } + } +} + +func TestSlimCreateHealthyTargetsProgressWithBlockedPeer(t *testing.T) { + slow, node, slowTargets, _ := setupGroupedCreatePeer(t) + healthy := newFakeNodeHTTP(t) + firstHealthy := realNodeInbound(t, healthy, 46321, nil) + secondHealthy := nodeInbound(t, *firstHealthy.NodeID, 46322, nil) + healthy.tags[secondHealthy.Tag] = 122 + for i := range 2 { + ib := nodeInbound(t, node.Id, 46331+i, nil) + slow.tags[ib.Tag] = 131 + i + slow.settings[131+i] = ib.Settings + slowTargets = append(slowTargets, ib) + } + var ids []int + var locks []*inboundMutationLock + for _, ib := range slowTargets { + ids = append(ids, ib.Id) + locks = append(locks, lockInbound(ib.Id)) + } + releaseLocks := sync.OnceFunc(func() { + for _, lock := range locks { + lock.Unlock() + } + }) + ids = append(ids, firstHealthy.Id, secondHealthy.Id) + healthySent := make(chan struct{}) + releaseRPC := sync.OnceFunc(func() { close(healthySent) }) + slow.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + select { + case <-healthySent: + case <-r.Context().Done(): + return + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + } + saved := make(chan int, 2) + db := database.GetDB() + const hook = "test:healthy-inbound-write-while-other-inbounds-block" + updates := db.Callback().Update() + if err := updates.After("gorm:update").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" && len(tx.Statement.Vars) == 2 { + if id, ok := tx.Statement.Vars[1].(int); ok && (id == firstHealthy.Id || id == secondHealthy.Id) { + saved <- id + } + } + }); err != nil { + releaseLocks() + t.Fatal(err) + } + t.Cleanup(func() { _ = updates.Remove(hook) }) + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + svc := (&ClientService{}).TrackNodeApplies() + var createErr error + t.Cleanup(func() { releaseLocks(); releaseRPC(); cancel(); <-done }) + go func() { + defer close(done) + _, createErr = svc.CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: groupedRecoveryClient("healthy-node@x"), InboundIds: ids, + }) + }() + deadline := time.After(3 * time.Second) + seen := make(map[int]bool) + for range 2 { + select { + case id := <-saved: + seen[id] = true + case <-deadline: + t.Fatalf("healthy node's writes waited for parked lanes: %v", seen) + } + } + if len(seen) != 2 { + t.Fatalf("healthy writes seen = %v", seen) + } + if err := submitTrafficWrite(func() error { return nil }); err != nil { + t.Fatal(err) + } + releaseLocks() + select { + case call := <-healthy.clientAddEvents: + if !slices.Equal(call.InboundIds, []int{121, 122}) { + t.Fatalf("healthy peer received IDs %v, want 121 and 122 together", call.InboundIds) + } + case <-time.After(3 * time.Second): + t.Fatal("healthy peer waited for the slow peer's RPC") + } + releaseRPC() + select { + case <-done: + if createErr != nil { + t.Fatal(createErr) + } + case <-time.After(5 * time.Second): + t.Fatal("create did not return") + } + result := svc.NodeApplyResponse() + want := []ClientNodeApplyOutcome{{NodeID: node.Id, Status: "applied"}, {NodeID: *firstHealthy.NodeID, Status: "applied"}} + if result == nil || result.NodePending || !slices.Equal(result.NodeResults, want) { + t.Fatalf("node outcomes = %+v, want %v", result, want) + } +} + +func TestSlimCreateProjectionPreservesNodeIDAndProtocolSettings(t *testing.T) { + setupClientNodeOrderDB(t) + fake := newFakeNodeHTTP(t) + remote := realNodeInbound(t, fake, 46341, nil) + local := seedInboundSettingsReadTest(t, 46342, model.VLESS, `{"clients":[]}`) + mtproto := seedInboundSettingsReadTest(t, 46343, model.MTProto, `{"clients":[],"fakeTlsDomain":"front.example.test"}`) + for _, tc := range []struct { + inbound *model.Inbound + generate bool + settings string + }{ + {inbound: remote}, + {inbound: local}, + {inbound: mtproto, generate: true, settings: mtproto.Settings}, + {inbound: mtproto}, + } { + got, err := getInboundForClientPreparation(tc.inbound.Id, tc.generate) + if err != nil { + t.Fatal(err) + } + var nodeID, wantNodeID int + if got.NodeID != nil { + nodeID = *got.NodeID + } + if tc.inbound.NodeID != nil { + wantNodeID = *tc.inbound.NodeID + } + if got.Id != tc.inbound.Id || nodeID != wantNodeID || got.Protocol != tc.inbound.Protocol || + got.Enable != tc.inbound.Enable || got.Listen != tc.inbound.Listen || got.Settings != tc.settings { + t.Fatalf("projection id=%d node=%d protocol=%s settings bytes=%d, want id=%d node=%d protocol=%s settings bytes=%d", + got.Id, nodeID, got.Protocol, len(got.Settings), tc.inbound.Id, wantNodeID, tc.inbound.Protocol, len(tc.settings)) + } + } + secret := model.GenerateFakeTLSSecret("supplied.example.test") + const email = "preserve-supplied-secret@x" + if _, err := (&ClientService{}).CreateOne(&InboundService{}, mtproto.Id, model.Client{Email: email, Secret: secret}); err != nil { + t.Fatal(err) + } + if c, ok := settingsClient(t, mtproto.Id, email); !ok || c.Secret != secret { + t.Fatal("create regenerated the supplied MTProto secret") + } +} + +func TestSlimAttachUsesLockedFlowAndPreservesRawAdd(t *testing.T) { + setupClientNodeOrderDB(t) + db := database.GetDB() + inboundSvc, svc := &InboundService{}, &ClientService{} + client := groupedRecoveryClient("attach-flow@x") + client.Flow = "xtls-rprx-vision" + source := seedInboundSettingsReadTest(t, 46351, model.VLESS, clientsSettings(t, []model.Client{client})) + if err := svc.SyncInbound(nil, source.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + target := seedInboundSettingsReadTest(t, 46352, model.VLESS, `{"clients":[]}`) + if err := db.Model(target).Update("stream_settings", `{"network":"tcp","security":"tls"}`).Error; err != nil { + t.Fatal(err) + } + query := db.Callback().Query() + const hook = "test:disable-flow-after-attach-preparation-read" + var disable sync.Once + if err := query.After("gorm:query").Register(hook, func(tx *gorm.DB) { + if ib, ok := tx.Statement.Dest.(*model.Inbound); ok && ib.Id == target.Id && tx.Error == nil { + disable.Do(func() { _ = tx.AddError(db.Model(target).Update("disable_flow", true).Error) }) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = query.Remove(hook) }) + if _, err := svc.AttachByEmail(inboundSvc, client.Email, []int{target.Id}); err != nil { + t.Fatal(err) + } + if c, ok := settingsClient(t, target.Id, client.Email); !ok || c.Flow != "" { + t.Fatalf("attach retained stale flow %q", c.Flow) + } + client.Email, client.SubID, client.ID = "legacy-add@x", "legacy-add", "aaaaaaaa-1111-2222-3333-555555555555" + if _, err := svc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: target.Id, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + if c, ok := settingsClient(t, target.Id, client.Email); !ok || c.Flow != client.Flow { + t.Fatalf("raw AddInboundClient changed its caller-owned flow to %q", c.Flow) + } +} + +func TestSlimUpdateRebasesConcurrentSettings(t *testing.T) { + setupClientNodeOrderDB(t) + ib := seedRenewableNeighbour(t, 46361, nil) + record := lookupClientRecord(t, "x@stale") + current := record.ToClient() + current.Comment = "updated alongside renewal" + reads := trackInboundSettingsReads(t) + var editErr error + commitTickBetweenReadAndWrite(t, renewYTick(ib.Id), func() { + _, editErr = (&ClientService{}).Update(&InboundService{}, record.Id, *current, 0) + }) + if editErr != nil { + t.Fatal(editErr) + } + if len(reads.sizes) != 4 || reads.sizes[0] != 0 || reads.sizes[1] == 0 || reads.sizes[2] == 0 || reads.sizes[3] == 0 { + t.Fatalf("update settings reads = %v, want empty preparation plus full locked, renewal and transactional reads", reads.sizes) + } + requireNeighbourRenewed(t, ib.Id) + if saved, ok := settingsClient(t, ib.Id, current.Email); !ok || saved.Comment != current.Comment { + t.Fatalf("update lost the edited comment: %+v", saved) + } +} diff --git a/internal/web/service/client_create_reads_test.go b/internal/web/service/client_create_reads_test.go new file mode 100644 index 000000000..283c7cc83 --- /dev/null +++ b/internal/web/service/client_create_reads_test.go @@ -0,0 +1,174 @@ +package service + +import ( + "encoding/hex" + "fmt" + "slices" + "strings" + "sync" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +type inboundSettingsReads struct { + mu sync.Mutex + sizes []int +} + +func trackInboundSettingsReads(t testing.TB) *inboundSettingsReads { + t.Helper() + reads := &inboundSettingsReads{} + query := database.GetDB().Callback().Query() + const name = "test:track_client_inbound_settings" + if err := query.After("gorm:query").Register(name, func(tx *gorm.DB) { + if tx.Statement.Table != "inbounds" || tx.Error != nil { + return + } + projection, _, _ := strings.Cut(tx.Statement.SQL.String(), " FROM ") + if !strings.Contains(projection, "settings") && !strings.Contains(projection, "*") { + return + } + reads.mu.Lock() + defer reads.mu.Unlock() + switch dest := tx.Statement.Dest.(type) { + case *model.Inbound: + reads.sizes = append(reads.sizes, len(dest.Settings)) + case *[]string: + for _, settings := range *dest { + reads.sizes = append(reads.sizes, len(settings)) + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := query.Remove(name); err != nil { + t.Error(err) + } + }) + return reads +} + +func seedInboundSettingsReadTest(t *testing.T, port int, protocol model.Protocol, settings string) *model.Inbound { + t.Helper() + ib := &model.Inbound{Tag: fmt.Sprintf("settings-reads-%d", port), Enable: true, Port: port, Protocol: protocol, Settings: settings} + if err := database.GetDB().Create(ib).Error; err != nil { + t.Fatal(err) + } + return ib +} + +func TestClientCreateReadsInboundSettingsOnlyForMutation(t *testing.T) { + setupBulkDB(t) + const flow = "xtls-rprx-vision" + ib := seedInboundSettingsReadTest(t, 23121, model.VLESS, `{"clients":[],"decryption":"mlkem768x25519plus.native.0rtt.test"}`) + reads := trackInboundSettingsReads(t) + + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + InboundIds: []int{ib.Id}, + Client: model.Client{Email: "create-reads@example.test", Flow: flow}, + }); err != nil { + t.Fatal(err) + } + want := []int{0, len(ib.Settings), len(ib.Settings)} + if !slices.Equal(reads.sizes, want) { + t.Fatalf("inbound settings bytes by read = %v, want %v (preparation, locked read, transaction guard)", reads.sizes, want) + } + if client, found := settingsClient(t, ib.Id, "create-reads@example.test"); !found || client.Flow != flow { + t.Fatalf("encrypted VLESS inbound saved flow %q, want %q", client.Flow, flow) + } +} + +func TestClientCreateClearsFlowOnIneligibleInbound(t *testing.T) { + setupBulkDB(t) + ib := seedInboundSettingsReadTest(t, 23123, model.VLESS, `{"clients":[],"decryption":"none"}`) + if _, err := (&ClientService{}).CreateOne(&InboundService{}, ib.Id, model.Client{ + Email: "create-noflow@example.test", Flow: "xtls-rprx-vision", + }); err != nil { + t.Fatal(err) + } + if client, found := settingsClient(t, ib.Id, "create-noflow@example.test"); !found || client.Flow != "" { + t.Fatalf("ineligible VLESS inbound has client=%v with flow %q, want client without flow", found, client.Flow) + } +} + +func TestClientCreatePreservesSettingsBasedDefaults(t *testing.T) { + setupBulkDB(t) + const method = "2022-blake3-aes-256-gcm" + const domain = "front.example.test" + ss := seedInboundSettingsReadTest(t, 23124, model.Shadowsocks, `{"clients":[],"method":"`+method+`","password":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}`) + mt := seedInboundSettingsReadTest(t, 23125, model.MTProto, `{"clients":[],"fakeTlsDomain":"`+domain+`"}`) + const email = "create-defaults@example.test" + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + InboundIds: []int{ss.Id, mt.Id}, + Client: model.Client{Email: email}, + }); err != nil { + t.Fatal(err) + } + if client, found := settingsClient(t, ss.Id, email); !found || !validShadowsocksClientKey(method, client.Password) { + t.Fatalf("Shadowsocks client found=%v, want a valid %s key", found, method) + } + if client, found := settingsClient(t, mt.Id, email); !found || !model.ValidMtprotoSecret(client.Secret) || + !strings.HasSuffix(client.Secret, hex.EncodeToString([]byte(domain))) { + t.Fatalf("MTProto client found=%v, want a valid FakeTLS secret for %s", found, domain) + } +} + +func TestUpdateInboundClientReadsSettingsOnceBeforeCommit(t *testing.T) { + setupBulkDB(t) + svc, inbounds := &ClientService{}, &InboundService{} + client := model.Client{Email: "update-reads@example.test", ID: "225452da-1385-4a1c-84ab-05481e000001", SubID: "update-reads"} + ib := seedInboundSettingsReadTest(t, 23122, model.VLESS, clientsSettings(t, []model.Client{client})) + if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + reads := trackInboundSettingsReads(t) + + client.Comment = "changed" + if _, err := svc.UpdateInboundClient(inbounds, &model.Inbound{ + Id: ib.Id, Settings: clientsSettings(t, []model.Client{client}), + }, client.Email); err != nil { + t.Fatal(err) + } + want := []int{len(ib.Settings), len(ib.Settings)} + if !slices.Equal(reads.sizes, want) { + t.Fatalf("inbound settings bytes by read = %v, want %v (locked read, transaction guard)", reads.sizes, want) + } +} + +func BenchmarkClientCreateLargeInboundSettings(b *testing.B) { + setupScaleDB(b) + const inbounds, clientsPerInbound = 11, 4000 + data := seedScaleDataset(b, inbounds*clientsPerInbound, inbounds) + svc, inboundSvc := &ClientService{}, &InboundService{} + reads := trackInboundSettingsReads(b) + var times []time.Duration + for b.Loop() { + payload := &ClientCreatePayload{ + InboundIds: data.inboundIds, + Client: model.Client{Email: fmt.Sprintf("add-%d@example.test", len(times))}, + } + start := time.Now() + if _, err := svc.Create(inboundSvc, payload); err != nil { + b.Fatal(err) + } + times = append(times, time.Since(start)) + } + slices.Sort(times) + b.ReportMetric(float64(times[(95*len(times)+99)/100-1].Microseconds())/1000, "p95-ms") + bytes, blobs := 0, 0 + for _, size := range reads.sizes { + bytes += size + if size > 0 { + blobs++ + } + } + b.ReportMetric(float64(len(reads.sizes))/float64(b.N), "inbound-projections/op") + b.ReportMetric(float64(bytes)/float64(b.N), "settings-bytes/op") + b.ReportMetric(float64(blobs)/float64(b.N), "settings-reads/op") +} diff --git a/internal/web/service/client_create_reconcile_test.go b/internal/web/service/client_create_reconcile_test.go index 65567d38e..87f435e46 100644 --- a/internal/web/service/client_create_reconcile_test.go +++ b/internal/web/service/client_create_reconcile_test.go @@ -10,7 +10,6 @@ import ( "strconv" "strings" "sync" - "sync/atomic" "testing" "time" @@ -439,13 +438,16 @@ func TestGroupedCreateReconcilesUnsentRebasedSettings(t *testing.T) { ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: "group-rebased", } db := database.GetDB() - var reads atomic.Int32 + var inject sync.Once const callback = "test:concurrent-settings-before-grouped-write" if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) { read, ok := tx.Statement.Dest.(*model.Inbound) - if ok && read.Id == changed.Id && reads.Add(1) == 3 { - _ = tx.AddError(db.Model(&model.Inbound{}).Where("id = ?", changed.Id). - Update("settings", `{"clients":[],"decryption":"none"}`).Error) + if ok && read.Id == changed.Id && read.Settings == changed.Settings { + // VLESS preparation omits settings. The first full read is under the mutation lock. + inject.Do(func() { + _ = tx.AddError(db.Model(&model.Inbound{}).Where("id = ?", changed.Id). + Update("settings", `{"clients":[],"decryption":"none"}`).Error) + }) } }); err != nil { t.Fatal(err) diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index e35b4b6fb..780cfcf29 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -295,7 +295,7 @@ func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *Inbou // shared credentials on the first inbound and every later one reuses them. adds := make([]*model.Inbound, 0, len(payload.InboundIds)) for _, ibId := range payload.InboundIds { - inbound, getErr := inboundSvc.GetInbound(ibId) + inbound, getErr := getInboundForClientPreparation(ibId, client.Secret == "") if getErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, getErr) } @@ -317,7 +317,7 @@ func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *Inbou if err := validateAmneziaWGClientWrite(inbound, []model.Client{clientForInbound}, ""); err != nil { return false, fmt.Errorf("inbound %d: %w", ibId, err) } - settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}}) + settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientForInbound}}) if mErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, mErr) } @@ -338,6 +338,23 @@ func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *Inbou return needRestart || remoteRestart, errors.Join(saveErr, pushErr) } +// getInboundForClientPreparation returns the settings blob only for protocols +// that need it to prepare the client before any writes. +func getInboundForClientPreparation(id int, generateSecret bool) (*model.Inbound, error) { + protocolsWithSettings := []model.Protocol{model.Shadowsocks, model.AmneziaWG} + if generateSecret { + protocolsWithSettings = append(protocolsWithSettings, model.MTProto) + } + var inbound model.Inbound + if err := database.GetDB().Select( + "id, node_id, protocol, enable, listen, CASE WHEN protocol IN ? THEN settings ELSE '' END AS settings", + protocolsWithSettings, + ).First(&inbound, id).Error; err != nil { + return nil, err + } + return &inbound, nil +} + // inboundFanoutConcurrency caps how many inbounds one client op applies at // once, so a client spanning many of them can't start an unbounded RPC burst. const inboundFanoutConcurrency = 4 @@ -396,7 +413,7 @@ func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds queued = &pushes[i] } applies = append(applies, inboundApply{id: add.Id, nodeID: add.NodeID, run: func() (bool, error) { - return s.addInboundClient(inboundSvc, add, queued) + return s.addInboundClient(inboundSvc, add, true, queued) }}) } return fanoutInboundApplies(applies) @@ -603,7 +620,7 @@ func mtprotoDomainFromSettings(settings string) string { } func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client { - if ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) { + if c.Flow != "" && (ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings)) { c.Flow = "" } return c @@ -893,7 +910,18 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model // mints the shared credentials on the first inbound, later ones reuse them. applies := make([]inboundApply, 0, len(inboundIds)) for _, ibId := range inboundIds { - inbound, getErr := inboundSvc.GetInbound(ibId) + requestedFlow := updated.Flow + if keepInboundFlows { + requestedFlow = inboundFlows[ibId] + } + + var inbound *model.Inbound + var getErr error + if requestedFlow == "" { + inbound, getErr = getInboundForClientPreparation(ibId, updated.Secret == "") + } else { + inbound, getErr = inboundSvc.GetInbound(ibId) + } if getErr != nil { if errors.Is(getErr, gorm.ErrRecordNotFound) { if err := database.GetDB(). @@ -915,9 +943,7 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model if inbound.Protocol == model.WireGuard && tunnelCount > 1 { clientForInbound.WireguardDevices = nil } - if keepInboundFlows { - clientForInbound.Flow = inboundFlows[ibId] - } + clientForInbound.Flow = requestedFlow if ips, ok := updated.AllowedIPsByInbound[ibId]; ok { clientForInbound.AllowedIPs = ips } else if tunnelCount > 1 && (inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG) { @@ -1332,7 +1358,7 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds [] if err := s.fillProtocolDefaults(©Client, inbound); err != nil { return false, fmt.Errorf("inbound %d: %w", ibId, err) } - settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}}) + settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}}) if mErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, mErr) } diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 74e01da35..84413233b 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -397,10 +397,10 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c } func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (restartNeeded bool, saveErr error) { - return s.addInboundClient(inboundSvc, data, nil) + return s.addInboundClient(inboundSvc, data, false, nil) } -func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, queued *queuedClientCreate) (restartNeeded bool, saveErr error) { +func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, gateFlow bool, queued *queuedClientCreate) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(data.Id) defer mutation.close() @@ -412,15 +412,15 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model if err := validateClientsRenewal(clients); err != nil { return false, err } - inbound, err := inboundSvc.GetInbound(data.Id) + oldInbound, err := inboundSvc.GetInbound(data.Id) if err != nil { return false, err } - existingClients, err := inboundSvc.GetClients(inbound) + existingClients, err := inboundSvc.GetClients(oldInbound) if err != nil { return false, err } - if err := validateClientsKeepAliveAgainstExisting(inbound.Protocol, clients, existingClients); err != nil { + if err := validateClientsKeepAliveAgainstExisting(oldInbound.Protocol, clients, existingClients); err != nil { return false, err } @@ -434,6 +434,11 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model nowTs := time.Now().Unix() * 1000 for i := range interfaceClients { if cm, ok := interfaceClients[i].(map[string]any); ok { + // Create and attach filter flow against the locked inbound snapshot. + if gateFlow && clients[i].Flow != "" && clientWithInboundFlow(clients[i], oldInbound).Flow == "" { + clients[i].Flow = "" + delete(cm, "flow") + } if _, ok2 := cm["created_at"]; !ok2 { cm["created_at"] = nowTs } @@ -453,10 +458,6 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model return false, common.NewError("Duplicate email:", existEmail) } - oldInbound, err := inboundSvc.GetInbound(data.Id) - if err != nil { - return false, err - } defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err @@ -774,7 +775,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if err := validateClientsRenewal(clients); err != nil { return false, err } - inbound, err := inboundSvc.GetInbound(data.Id) + oldInbound, err := inboundSvc.GetInbound(data.Id) if err != nil { return false, err } @@ -786,10 +787,6 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo interfaceClients := settings["clients"].([]any) - oldInbound, err := inboundSvc.GetInbound(data.Id) - if err != nil { - return false, err - } defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err @@ -804,7 +801,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if i == 0 { identityEmail = oldEmail } - if err := validateClientKeepAliveAgainstExisting(inbound.Protocol, client, oldClients, identityEmail); err != nil { + if err := validateClientKeepAliveAgainstExisting(oldInbound.Protocol, client, oldClients, identityEmail); err != nil { return false, fmt.Errorf("client %q: %w", client.Email, err) } } From b351b08601d52689b06cf11193e2d5610a4564ce Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 01:18:05 +0330 Subject: [PATCH 10/14] feat(dashboard): persist one overview time range (#7277) Consolidate the six overview range selectors into a single translated action-bar control beside Xray Metrics. Persist the validated selection per browser origin and panel base path with a safe 2m fallback, including unavailable storage. Restore the preference before history fetching and retain live status sampling while viewing longer ranges. Avoid overlapping delayed live-history seeds, track sampled scope epochs, use separate scoped/unscoped boundaries and reject stale responses. Cover scope transitions, clock skew bounds, storage failures and range propagation. Update English and Persian documentation without changing schema or backend API contracts. Validation: all 12 CI jobs and Docs CI passed on 2d3992766b277974f2cb4b4b44af1a6a456653dd; frontend 265 files / 2,330 tests, including 12 global-range, 11 ranged-history and 8 container-history cases. Browser restart and responsive/RTL checks reported by author, not independently rerun. Persistence is browser-local; arbitrary clock skew cannot guarantee complete live history. Closes #7276 --- .../docs/en/operations/system-monitoring.mdx | 2 +- .../docs/fa/operations/system-monitoring.mdx | 2 +- frontend/src/pages/index/ConnectionsCard.tsx | 9 - frontend/src/pages/index/IndexPage.css | 19 +- frontend/src/pages/index/IndexPage.tsx | 35 ++- .../src/pages/index/OverviewActionBar.tsx | 23 +- .../src/pages/index/OverviewRangeSelect.tsx | 33 +-- frontend/src/pages/index/ThroughputCard.tsx | 9 - frontend/src/pages/index/VitalTile.tsx | 11 - .../src/pages/index/useOverviewHistory.ts | 111 +++++---- frontend/src/test/container-history.test.tsx | 6 +- .../src/test/network-traffic-status.test.tsx | 2 - .../src/test/overview-global-range.test.tsx | 150 ++++++++++++ .../src/test/overview-ranged-history.test.tsx | 230 +++++++++++++++++- .../src/test/overview-stop-confirm.test.tsx | 2 + .../overview-update-tag-keyboard.test.tsx | 2 + 16 files changed, 527 insertions(+), 119 deletions(-) create mode 100644 frontend/src/test/overview-global-range.test.tsx diff --git a/docs/content/docs/en/operations/system-monitoring.mdx b/docs/content/docs/en/operations/system-monitoring.mdx index d80b2791f..83c0b2ac2 100644 --- a/docs/content/docs/en/operations/system-monitoring.mdx +++ b/docs/content/docs/en/operations/system-monitoring.mdx @@ -8,7 +8,7 @@ The overview page combines a current server snapshot with short time-series char ## Choose a chart window -Each overview chart has the same time-range selector in its upper-right corner. The default is **2m**. The choices are **2m**, **5m**, **30m**, **1h**, **6h**, and **12h**. Changing any selector changes the window on every overview chart. +Use **Time range** beside **Xray Metrics** to change the window on every overview chart. The choices are **2m**, **5m**, **30m**, **1h**, **6h**, and **12h**. The default is **2m**. This browser remembers your selection for the panel across reloads and panel restarts. The number of chart points stays capped at 60. Short windows use finer samples; longer windows use averages. At **2m** the charts are live: every status poll, once every 2 seconds, adds a point. A longer window is read from the server's stored history and refreshed once per point, at most once a minute. diff --git a/docs/content/docs/fa/operations/system-monitoring.mdx b/docs/content/docs/fa/operations/system-monitoring.mdx index 2082e9c59..2e3d46d0f 100644 --- a/docs/content/docs/fa/operations/system-monitoring.mdx +++ b/docs/content/docs/fa/operations/system-monitoring.mdx @@ -8,7 +8,7 @@ icon: ChartNoAxesCombined ## انتخاب بازهٔ نمودار -هر نمودار نمای کلی یک سلکت بازهٔ زمانی در گوشهٔ بالای سمت راست دارد. مقدار پیش‌فرض **2m** است. گزینه‌ها **2m**، **5m**، **30m**، **1h**، **6h** و **12h** هستند. تغییر بازه در هر نمودار، بازهٔ همهٔ نمودارهای نمای کلی را تغییر می‌دهد. +از گزینهٔ **بازهٔ زمانی** کنار **شاخص‌های Xray** برای تغییر بازهٔ همهٔ نمودارهای نمای کلی استفاده کنید. گزینه‌ها **2m**، **5m**، **30m**، **1h**، **6h** و **12h** هستند. مقدار پیش‌فرض **2m** است. مرورگر انتخاب شما را برای این پنل پس از بارگیری مجدد صفحه و راه‌اندازی دوبارهٔ پنل حفظ می‌کند. تعداد نقطه‌های نمودار حداکثر ۶۰ نقطه است. بازه‌های کوتاه‌تر از نمونه‌های دقیق‌تر و بازه‌های بلندتر از میانگین نمونه‌ها استفاده می‌کنند. در بازهٔ **2m** نمودارها زنده‌اند: هر بار دریافت وضعیت، یعنی هر ۲ ثانیه، یک نقطه اضافه می‌کند. بازه‌های بلندتر از تاریخچهٔ ذخیره‌شده در سرور خوانده می‌شوند و به‌ازای هر نقطه یک بار، و حداکثر دقیقه‌ای یک بار، به‌روزرسانی می‌شوند. diff --git a/frontend/src/pages/index/ConnectionsCard.tsx b/frontend/src/pages/index/ConnectionsCard.tsx index 128e9b4ab..35d4d3140 100644 --- a/frontend/src/pages/index/ConnectionsCard.tsx +++ b/frontend/src/pages/index/ConnectionsCard.tsx @@ -4,8 +4,6 @@ import { Card, theme } from 'antd'; import { Sparkline } from '@/components/viz'; import type { Status } from '@/models/status'; -import OverviewRangeSelect from './OverviewRangeSelect'; -import type { OverviewRange } from './OverviewRangeSelect'; interface ConnectionsCardProps { status: Status; @@ -13,8 +11,6 @@ interface ConnectionsCardProps { udp: number[]; labels: string[]; isMobile: boolean; - range: OverviewRange; - onRangeChange: (range: OverviewRange) => void; } export default function ConnectionsCard({ @@ -23,8 +19,6 @@ export default function ConnectionsCard({ udp, labels, isMobile, - range, - onRangeChange, }: ConnectionsCardProps) { const { t } = useTranslation(); const { token } = theme.useToken(); @@ -49,9 +43,6 @@ export default function ConnectionsCard({ -
- -
diff --git a/frontend/src/pages/index/IndexPage.css b/frontend/src/pages/index/IndexPage.css index 22f689698..7e07bab85 100644 --- a/frontend/src/pages/index/IndexPage.css +++ b/frontend/src/pages/index/IndexPage.css @@ -133,6 +133,12 @@ } } +.ov-bar-range { + display: inline-flex; + align-items: center; + gap: 4px; +} + .ov-bar-sep { width: 1px; height: 20px; @@ -284,12 +290,13 @@ margin-top: 6px; } -.ov-range-toolbar { - position: absolute; - z-index: 1; - top: 14px; - right: var(--ov-pad); - display: flex; +.ov-range-control { + display: inline-flex; + align-items: center; + gap: 8px; + white-space: nowrap; + font-size: 12px; + color: var(--ov-label); } .ov-range-select { diff --git a/frontend/src/pages/index/IndexPage.tsx b/frontend/src/pages/index/IndexPage.tsx index 63fda3f39..9311889c3 100644 --- a/frontend/src/pages/index/IndexPage.tsx +++ b/frontend/src/pages/index/IndexPage.tsx @@ -30,6 +30,7 @@ import ThroughputCard from './ThroughputCard'; import ConnectionsCard from './ConnectionsCard'; import SystemStrip from './SystemStrip'; import { mean, peak, useOverviewHistory } from './useOverviewHistory'; +import { OVERVIEW_RANGES } from './OverviewRangeSelect'; import type { OverviewRange } from './OverviewRangeSelect'; import type { PanelUpdateInfo } from './PanelUpdateModal'; const JsonEditor = lazy(() => import('@/components/form/JsonEditor')); @@ -52,6 +53,15 @@ function metricFoot(label: string, value: string) { ); } +function readHistoryRange(key: string): OverviewRange { + try { + const saved = localStorage.getItem(key); + return OVERVIEW_RANGES.find((range) => String(range) === saved) ?? 2; + } catch { + return 2; + } +} + export default function IndexPage() { const { t } = useTranslation(); const { isDark, isUltra, antdThemeConfig } = useTheme(); @@ -86,7 +96,16 @@ export default function IndexPage() { const [loading, setLoading] = useState(false); const [loadingTip, setLoadingTip] = useState(t('loading')); - const [historyRange, setHistoryRange] = useState(2); + const historyRangeKey = '3x-ui:overview-range:' + (basePath || '/'); + const [historyRange, setHistoryRange] = useState(() => readHistoryRange(historyRangeKey)); + const changeHistoryRange = (range: OverviewRange) => { + setHistoryRange(range); + try { + localStorage.setItem(historyRangeKey, String(range)); + } catch { + // A blocked browser store should still allow changes for this visit. + } + }; const history = useOverviewHistory(status, fetched && !fetchError, historyRange); useEffect(() => { @@ -213,6 +232,8 @@ export default function IndexPage() { panelVersion={displayVersion} latestVersion={panelUpdateInfo.latestVersion} updateAvailable={panelUpdateInfo.updateAvailable} + historyRange={historyRange} + onHistoryRangeChange={changeHistoryRange} onStopXray={stopXray} onRestartXray={restartXray} onOpenLogs={() => setLogsOpen(true)} @@ -259,8 +280,6 @@ export default function IndexPage() { )} data={history.series.cpu} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} /> } @@ -278,8 +297,6 @@ export default function IndexPage() { )} data={history.series.mem} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} /> } @@ -298,8 +315,6 @@ export default function IndexPage() { )} data={history.series.swap} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} /> } @@ -317,8 +332,6 @@ export default function IndexPage() { )} data={history.series.diskUsage} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} />
@@ -329,8 +342,6 @@ export default function IndexPage() { down={history.series.netDown} labels={history.labels} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} />
diff --git a/frontend/src/pages/index/OverviewActionBar.tsx b/frontend/src/pages/index/OverviewActionBar.tsx index 9a5dbab7f..b7de16cab 100644 --- a/frontend/src/pages/index/OverviewActionBar.tsx +++ b/frontend/src/pages/index/OverviewActionBar.tsx @@ -19,6 +19,7 @@ import { import { formatPanelVersion } from '@/lib/panel-version'; import { activateOnKey } from '@/utils/a11y'; import type { Status } from '@/models/status'; +import OverviewRangeSelect, { type OverviewRange } from './OverviewRangeSelect'; interface OverviewActionBarProps { status: Status; @@ -27,6 +28,8 @@ interface OverviewActionBarProps { panelVersion: string; latestVersion: string; updateAvailable: boolean; + historyRange: OverviewRange; + onHistoryRangeChange: (range: OverviewRange) => void; onStopXray: () => void | Promise; onRestartXray: () => void; onOpenLogs: () => void; @@ -64,6 +67,8 @@ export default function OverviewActionBar({ panelVersion, latestVersion, updateAvailable, + historyRange, + onHistoryRangeChange, onStopXray, onRestartXray, onOpenLogs, @@ -158,12 +163,6 @@ export default function OverviewActionBar({ text: t('pages.index.systemHistoryTitle'), onClick: onOpenSystemHistory, }, - { - key: 'metrics', - icon: , - text: t('pages.index.xrayMetricsTitle'), - onClick: onOpenXrayMetrics, - }, ], ]; @@ -241,6 +240,18 @@ export default function OverviewActionBar({ ))} ))} +
+ + +
); diff --git a/frontend/src/pages/index/OverviewRangeSelect.tsx b/frontend/src/pages/index/OverviewRangeSelect.tsx index a9878cee2..cfc25467c 100644 --- a/frontend/src/pages/index/OverviewRangeSelect.tsx +++ b/frontend/src/pages/index/OverviewRangeSelect.tsx @@ -9,26 +9,27 @@ interface OverviewRangeSelectProps { onChange: (value: OverviewRange) => void; } -const OPTIONS = [ - { value: 2, label: '2m' }, - { value: 5, label: '5m' }, - { value: 30, label: '30m' }, - { value: 60, label: '1h' }, - { value: 360, label: '6h' }, - { value: 720, label: '12h' }, -]; +const OPTIONS = OVERVIEW_RANGES.map((value) => ({ + value, + label: value < 60 ? String(value) + 'm' : String(value / 60) + 'h', +})); export default function OverviewRangeSelect({ value, onChange }: OverviewRangeSelectProps) { const { t } = useTranslation(); + const label = t('pages.index.timeRange'); return ( - setInput(event.target.value)} /> + +

+ {clientCount[30] + ? 'Rollups ready' + : dbInbounds.length + ? 'Calculating rollups' + : 'Waiting for inbounds'} +

+ +
Last inbound online: {clientCount[30]?.online.length ?? '…'}
+
First inbound online: {clientCount[1]?.online.length ?? '…'}
+ + ); +} + +function Fixture() { + const [queryClient] = useState(() => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + client.setQueryData(keys.settings.defaults(), {}); + client.setQueryData(keys.inbounds.slim(), []); + client.setQueryData(keys.clients.onlines(), []); + client.setQueryData(keys.clients.onlinesByGuid(), {}); + client.setQueryData(keys.clients.activeInbounds(), {}); + client.setQueryData(keys.clients.lastOnline(), {}); + return client; + }); + + return ( + + + + + ); +} + +export const LargeDeployment: StoryObj = { + render: () => , + play: async ({ canvas, userEvent }) => { + const start = performance.now(); + await userEvent.click(canvas.getByRole('button', { name: 'Load 120,000 memberships' })); + await userEvent.type(canvas.getByRole('textbox', { name: 'Filter' }), 'a'); + const responsiveAt = performance.now(); + await canvas.findByText('Rollups ready'); + const readyAt = performance.now(); + const updateAt = performance.now(); + await userEvent.click(canvas.getByRole('button', { name: 'Apply online update' })); + await canvas.findByText('Last inbound online: 1'); + await expect(canvas.getByText('First inbound online: 0')).toBeVisible(); + await expect(canvas.getByRole('textbox', { name: 'Filter' })).toHaveValue('a'); + console.info('120,000 memberships (ms)', { + input: Math.round(responsiveAt - start), + initial: Math.round(readyAt - start), + update: Math.round(performance.now() - updateAt), + }); + }, +}; diff --git a/frontend/src/pages/inbounds/InboundsPage.tsx b/frontend/src/pages/inbounds/InboundsPage.tsx index 7ffaf5de0..6c062533f 100644 --- a/frontend/src/pages/inbounds/InboundsPage.tsx +++ b/frontend/src/pages/inbounds/InboundsPage.tsx @@ -89,6 +89,7 @@ export default function InboundsPage() { fetchError, dbInbounds, clientCount, + clientCountsPending, onlineClients, lastOnlineMap, inboundSpeed, @@ -558,7 +559,8 @@ export default function InboundsPage() { const confirmDelAllClients = useCallback( (dbInbound: DBInbound) => { - const count = clientCount[dbInbound.id]?.clients || 0; + const count = clientCount[dbInbound.id]?.clients; + if (count === undefined || count === 0) return; modal.confirm({ title: t('pages.inbounds.delAllClientsConfirmTitle', { remark: dbInbound.remark, count }), content: t('pages.inbounds.delAllClientsConfirmContent'), @@ -796,6 +798,7 @@ export default function InboundsPage() { ; + clientCountsPending: boolean; onlineClients: string[]; lastOnlineMap: Record; inboundSpeed: Record; diff --git a/frontend/src/pages/inbounds/list/useInboundColumns.tsx b/frontend/src/pages/inbounds/list/useInboundColumns.tsx index fc1d10d05..63e42b33a 100644 --- a/frontend/src/pages/inbounds/list/useInboundColumns.tsx +++ b/frontend/src/pages/inbounds/list/useInboundColumns.tsx @@ -1,4 +1,4 @@ -import { useMemo, type ReactElement } from 'react'; +import { useMemo, useState, type ReactElement } from 'react'; import { useTranslation } from 'react-i18next'; import { onlineStatusLabel } from './onlineStatusLabel'; import { Popover, Switch, Tag, Tooltip, type TableColumnType } from 'antd'; @@ -28,6 +28,49 @@ import { } from './helpers'; import type { ClientCountEntry, DBInboundRecord, InboundSpeedEntry, RowAction } from './types'; +function ClientEmailBadge({ + emails, + title, + color, + suffix, +}: { + emails: string[]; + title: string; + color?: string; + suffix?: string; +}) { + const [open, setOpen] = useState(false); + const badge = ( + + {emails.length} + {suffix && ` ${suffix}`} + + ); + if (!emails.length) return badge; + return ( + + {emails.map((email) => ( +
{email}
+ ))} + + ) : null + } + > + {badge} +
+ ); +} + interface UseInboundColumnsParams { hasAnyRemark: boolean; hasAnySubSortIndex: boolean; @@ -35,6 +78,7 @@ interface UseInboundColumnsParams { nodesById: Map; hostRemarksByInboundId: Map; clientCount: Record; + clientCountsPending: boolean; inboundSpeed: Record; subEnable: boolean; expireDiff: number; @@ -50,6 +94,7 @@ export function useInboundColumns({ nodesById, hostRemarksByInboundId, clientCount, + clientCountsPending, inboundSpeed, subEnable, expireDiff, @@ -70,7 +115,9 @@ export function useInboundColumns({ }; const clientTotal = (record: DBInboundRecord) => - (clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0; + clientCountsPending + ? 0 + : ((clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0); const speedTotal = (record: DBInboundRecord) => { const speed = inboundSpeed[record.id]; @@ -290,8 +337,11 @@ export function useInboundColumns({ width: 200, sorter: (a, b) => clientTotal(a) - clientTotal(b), render: (_, record) => { + if (clientCountsPending) return t('loading'); const cc = clientCount[record.id] || fallbackClientCount(record); if (!cc) return null; + const onlineScope = + cc.onlineAttribution === 'node' ? `(${t('pages.inbounds.node')})` : undefined; return ( <> {cc.clients} - {cc.active.length > 0 ? ( - - {cc.active.map((e) => ( -
{e}
- ))} - - } - > - - {cc.active.length} - -
- ) : ( - - 0 - - )} + {cc.deactive.length > 0 && ( - - {cc.deactive.map((e) => ( -
{e}
- ))} - - } - > - - {cc.deactive.length} - -
+ )} {cc.depleted.length > 0 && ( - - {cc.depleted.map((e) => ( -
{e}
- ))} - - } - > - - {cc.depleted.length} - -
+ )} {cc.onlineAttribution && cc.online.length === 0 && ( @@ -373,29 +363,12 @@ export function useInboundColumns({ )} {cc.online.length > 0 && ( - - {cc.online.map((e) => ( -
{e}
- ))} - - } - > - - {cc.online.length} - {cc.onlineAttribution === 'node' && ` (${t('pages.inbounds.node')})`} - -
+ )} ); @@ -488,6 +461,7 @@ export function useInboundColumns({ nodesById, hostRemarksByInboundId, clientCount, + clientCountsPending, inboundSpeed, subEnable, expireDiff, diff --git a/frontend/src/pages/inbounds/useInbounds.ts b/frontend/src/pages/inbounds/useInbounds.ts index 8911c0ce6..4cc55c11a 100644 --- a/frontend/src/pages/inbounds/useInbounds.ts +++ b/frontend/src/pages/inbounds/useInbounds.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { HttpUtil } from '@/utils'; @@ -58,6 +58,15 @@ interface ClientRollup { comments: Map; } +interface CachedClientRollup { + base: ClientRollup; + refreshAt: number; + online?: { emails?: Set; result: ClientRollup }; +} + +const EMPTY_ONLINE: string[] = []; +const EMPTY_ROLLUPS: Record = {}; + const TRACKED_PROTOCOLS: readonly string[] = [ Protocols.VMESS, Protocols.VLESS, @@ -124,27 +133,37 @@ function toActiveInboundMap( data: Record, ): Map | null> { const map = new Map | null>(); - for (const [key, tags] of Object.entries(data)) { - if (tags === null) map.set(key, null); - else if (Array.isArray(tags)) map.set(key, new Set(tags)); + for (const [guid, tags] of Object.entries(data)) { + if (tags === null) map.set(guid, null); + else if (Array.isArray(tags)) map.set(guid, new Set(tags)); } return map; } -// Most pushes repeat the previous online sets; handing back a new Map anyway -// re-ran the client rollup over every inbound on each traffic event. -function sameGuidSets( - a: ReadonlyMap | null>, - b: ReadonlyMap | null>, -): boolean { - if (a.size !== b.size) return false; - for (const [key, set] of b) { - const prev = a.get(key); - if (prev === set) continue; - if (!prev || !set || prev.size !== set.size) return false; - for (const value of set) if (!prev.has(value)) return false; +function reuseGuidSets | null>( + previous: Map, + next: Map, +): Map { + let changed = previous.size !== next.size; + for (const [guid, set] of next) { + const prior = previous.get(guid); + if (prior === set) continue; + let same = !!prior && !!set && prior.size === set.size; + if (same && prior && set) { + for (const value of set) { + if (!prior.has(value)) { + same = false; + break; + } + } + } + if (same && prior) { + next.set(guid, prior); + } else { + changed = true; + } } - return true; + return changed ? next : previous; } async function fetchLastOnlineMap(): Promise> { @@ -237,6 +256,7 @@ export function useInbounds() { // dbInbounds mirrors the slim query data wrapped as DBInbound instances. The // WS handlers rebuild only the rows they touch, so no refetch is needed. const [dbInbounds, setDbInbounds] = useState([]); + const [inboundGeneration, setInboundGeneration] = useState(0); const dbInboundsRef = useRef([]); useEffect(() => { dbInboundsRef.current = dbInbounds; @@ -265,10 +285,7 @@ export function useInbounds() { const [lastOnlineMap, setLastOnlineMap] = useState>({}); const rollupClients = useCallback( - ( - dbInbound: DBInboundInstance, - inbound: { clients?: { email?: string; enable?: boolean; comment?: string }[] }, - ): ClientRollup => { + (dbInbound: DBInboundInstance, now: number): CachedClientRollup => { const clientStats = Array.isArray((dbInbound as { clientStats?: unknown }).clientStats) ? ( dbInbound as unknown as { @@ -282,37 +299,16 @@ export function useInbounds() { } ).clientStats : []; - const clients = inbound?.clients || []; + const settings = coerceInboundJsonField(dbInbound.settings) as { + clients?: { email?: string; enable?: boolean; comment?: string }[]; + }; + const clients = Array.isArray(settings.clients) ? settings.clients : []; const active: string[] = []; const deactive: string[] = []; const depleted: string[] = []; const expiring: string[] = []; - const online: string[] = []; const comments = new Map(); - const now = Date.now(); - - // Attribution key: the GUID of the node that physically hosts this - // inbound. Local inbounds carry the panel's own GUID (filled server-side); - // a node-managed inbound carries its origin node's GUID, or falls back to - // the master-local synthetic id for an old-build node without one (#4983). - const guid = - dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : ''); - const nodeOnline = onlineByGuid.get(guid); - const activeForNode = activeByGuid.get(guid); - let onlineAttribution: ClientRollup['onlineAttribution'] = onlinePending - ? 'pending' - : 'unavailable'; - let inboundActive = false; - if (!dbInbound.enable) { - onlineAttribution = 'inbound'; - } else if (activeForNode === null) { - onlineAttribution = nodeOnline === undefined ? 'unsupported' : 'node'; - inboundActive = true; - } else if (nodeOnline !== undefined && activeForNode !== undefined && dbInbound.tag) { - inboundActive = activeForNode.has(dbInbound.tag); - // A partial report only vouches for the listed sidecar inbounds. - if (inboundActive || !activeForNode.has('\0')) onlineAttribution = 'inbound'; - } + let refreshAt = Infinity; if (dbInbound.enable) { const statsByEmail = new Map< @@ -333,17 +329,20 @@ export function useInbounds() { depleted.push(client.email); continue; } + if (stats && stats.expiryTime > now) refreshAt = Math.min(refreshAt, stats.expiryTime); if (!client.enable) { deactive.push(client.email); continue; } active.push(client.email); - if (inboundActive && nodeOnline?.has(client.email)) online.push(client.email); if (stats) { const expiringSoon = (stats.expiryTime > 0 && stats.expiryTime - now < expireDiff) || (stats.total > 0 && stats.total - (stats.up + stats.down) < trafficDiff); if (expiringSoon) expiring.push(client.email); + if (stats.expiryTime > now && !expiringSoon && expireDiff > 0) { + refreshAt = Math.min(refreshAt, Math.floor(stats.expiryTime - expireDiff) + 1); + } } } } else { @@ -353,39 +352,148 @@ export function useInbounds() { } return { - clients: clients.length, - active, - deactive, - depleted, - expiring, - online, - onlineAttribution, - comments, + base: { + clients: clients.length, + active, + deactive, + depleted, + expiring, + online: EMPTY_ONLINE, + onlineAttribution: 'inbound', + comments, + }, + refreshAt, }; }, - [onlineByGuid, activeByGuid, onlinePending, expireDiff, trafficDiff], + [expireDiff, trafficDiff], ); - // Every write to a DBInbound row also replaces the dbInbounds array, so this - // recomputes on both a refetch and a WS-merged stats update. - const clientCount = useMemo(() => { + const rollupCache = useMemo( + () => ({ rows: new WeakMap(), compute: rollupClients }), + [rollupClients], + ); + + // The WebSocket subscription keeps the callback installed at mount. + const rollupCacheRef = useRef(rollupCache); + useLayoutEffect(() => { + rollupCacheRef.current = rollupCache; + }, [rollupCache]); + + const rollupForInbound = useCallback( + (dbInbound: DBInboundInstance, now = Date.now()) => { + if (!TRACKED_PROTOCOLS.includes(dbInbound.protocol)) return undefined; + let rollup = rollupCache.rows.get(dbInbound); + if (rollup === undefined || now >= rollup.refreshAt) { + rollup = rollupCache.compute(dbInbound, now); + rollupCache.rows.set(dbInbound, rollup); + } + + // Scope the report to the node that physically hosts this inbound. + const guid = + dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : ''); + const nodeOnline = onlineByGuid.get(guid); + const activeForNode = activeByGuid.get(guid); + let attribution: ClientRollup['onlineAttribution'] = onlinePending + ? 'pending' + : 'unavailable'; + let inboundActive = false; + if (!dbInbound.enable) { + attribution = 'inbound'; + } else if (activeForNode === null) { + attribution = nodeOnline === undefined ? 'unsupported' : 'node'; + inboundActive = true; + } else if (nodeOnline !== undefined && activeForNode !== undefined && dbInbound.tag) { + inboundActive = activeForNode.has(dbInbound.tag); + // A partial report only vouches for the listed sidecar inbounds. + if (inboundActive || !activeForNode.has('\0')) attribution = 'inbound'; + } + + const emails = inboundActive && nodeOnline?.size ? nodeOnline : undefined; + const cached = rollup.online; + if (cached && cached.emails === emails && cached.result.onlineAttribution === attribution) { + return cached.result; + } + + const matched = emails + ? rollup.base.active.filter((email) => emails.has(email)) + : EMPTY_ONLINE; + const result = + matched.length || attribution !== rollup.base.onlineAttribution + ? { ...rollup.base, online: matched, onlineAttribution: attribution } + : rollup.base; + rollup.online = { emails, result }; + return result; + }, + [rollupCache, activeByGuid, onlineByGuid, onlinePending], + ); + + const largeList = useMemo( + () => + dbInbounds.reduce((size, row) => { + const settings = row.settings; + const objectClients = + settings && typeof settings === 'object' && !Array.isArray(settings) + ? settings.clients + : undefined; + return ( + size + + (typeof settings === 'string' ? settings.length : 0) + + (Array.isArray(objectClients) ? objectClients.length * 64 : 0) + + (Array.isArray(row.clientStats) ? row.clientStats.length * 100 : 0) + ); + }, 0) > + 256 * 1024, + [dbInbounds], + ); + const [scheduled, setScheduled] = useState<{ + generation: number; + counts: Record; + }>(); + useEffect(() => { + if (!largeList) return; const counts: Record = {}; - for (const dbInbound of dbInbounds) { - const protocol = dbInbound.protocol; - if (!TRACKED_PROTOCOLS.includes(protocol)) continue; - const settings = coerceInboundJsonField(dbInbound.settings) as { - clients?: Array<{ email?: string; enable?: boolean; comment?: string }>; - }; - counts[dbInbound.id] = rollupClients(dbInbound, { clients: settings.clients }); + const now = Date.now(); + let index = 0; + let timer: ReturnType; + function computeSlice() { + const end = performance.now() + 8; + do { + const row = dbInbounds[index++]; + const rollup = rollupForInbound(row, now); + if (rollup) counts[row.id] = rollup; + } while (index < dbInbounds.length && performance.now() < end); + if (index < dbInbounds.length) { + timer = setTimeout(computeSlice, 0); + } else { + setScheduled({ generation: inboundGeneration, counts }); + } + } + timer = setTimeout(computeSlice, 0); + return () => clearTimeout(timer); + }, [largeList, dbInbounds, inboundGeneration, rollupForInbound]); + + const syncCounts = useMemo(() => { + if (largeList) return EMPTY_ROLLUPS; + const counts: Record = {}; + for (const row of dbInbounds) { + const rollup = rollupForInbound(row); + if (rollup) counts[row.id] = rollup; } return counts; - }, [dbInbounds, rollupClients]); + }, [largeList, dbInbounds, rollupForInbound]); + // Online and counter updates can reuse the last rollup while the next slice + // runs, but a refetch or hydration may have changed the client membership. + const rollupsReady = !largeList || scheduled?.generation === inboundGeneration; + const clientCount = largeList + ? ((rollupsReady ? scheduled?.counts : undefined) ?? EMPTY_ROLLUPS) + : syncCounts; // Adopting fetched data during render (rather than in an effect) keeps the // list from painting one frame of the previous data after a refetch. const [syncedSlim, setSyncedSlim] = useState(); if (slimQuery.data && slimQuery.data !== syncedSlim) { setSyncedSlim(slimQuery.data); + setInboundGeneration((generation) => generation + 1); setDbInbounds( (slimQuery.data as { protocol: string; id: number }[]).map( (row) => new DBInbound(row) as DBInboundInstance, @@ -450,6 +558,7 @@ export function useInbounds() { const validated = parseMsg(msg, InboundDetailSchema, `inbounds/get/${id}`); if (!validated.obj) return null; const dbInbound = new DBInbound(validated.obj) as DBInboundInstance; + setInboundGeneration((generation) => generation + 1); setDbInbounds((prev) => { const next = prev.map((row) => (row as unknown as { id: number }).id === id ? dbInbound : row, @@ -475,11 +584,11 @@ export function useInbounds() { } if (p.onlineByGuid && typeof p.onlineByGuid === 'object') { const next = toGuidOnlineMap(p.onlineByGuid); - setOnlineByGuid((prev) => (sameGuidSets(prev, next) ? prev : next)); + setOnlineByGuid((prev) => reuseGuidSets(prev, next)); } if (p.activeInbounds && typeof p.activeInbounds === 'object') { const next = toActiveInboundMap(p.activeInbounds); - setActiveByGuid((prev) => (sameGuidSets(prev, next) ? prev : next)); + setActiveByGuid((prev) => reuseGuidSets(prev, next)); } if (p.lastOnlineMap && typeof p.lastOnlineMap === 'object') { setLastOnlineMap((prev) => ({ ...prev, ...p.lastOnlineMap! })); @@ -611,6 +720,11 @@ export function useInbounds() { if (typeof upd.enable === 'boolean') row.enable = upd.enable; } if (statsTouched && nextStats) row.clientStats = nextStats; + if (!statsTouched && ib.enable === row.enable) { + const cache = rollupCacheRef.current.rows; + const cached = cache.get(ib); + if (cached) cache.set(row, cached); + } return row; }); @@ -635,6 +749,7 @@ export function useInbounds() { fetchError, dbInbounds, clientCount, + clientCountsPending: !rollupsReady, onlineClients, lastOnlineMap, inboundSpeed, diff --git a/frontend/src/test/inbounds-ws-identity.test.tsx b/frontend/src/test/inbounds-ws-identity.test.tsx index d8b6fc34b..70118871f 100644 --- a/frontend/src/test/inbounds-ws-identity.test.tsx +++ b/frontend/src/test/inbounds-ws-identity.test.tsx @@ -1,19 +1,27 @@ -import type { ReactNode } from 'react'; -import { act, renderHook, waitFor } from '@testing-library/react'; +import { useLayoutEffect, type ReactNode } from 'react'; +import { act, fireEvent, renderHook, screen, waitFor, within } from '@testing-library/react'; import { QueryClientProvider } from '@tanstack/react-query'; import { describe, expect, it, vi } from 'vitest'; +import { MemoryRouter } from 'react-router'; -import { HttpUtil } from '@/utils'; import { keys } from '@/api/queryKeys'; +import { getSharedWebSocketClient } from '@/api/websocket'; +import { useWebSocket } from '@/hooks/useWebSocket'; +import InboundsPage from '@/pages/inbounds/InboundsPage'; +import { HttpUtil, Msg } from '@/utils'; import { useInbounds } from '@/pages/inbounds/useInbounds'; -import { makeTestQueryClient } from './test-utils'; +import { makeTestQueryClient, renderWithProviders } from './test-utils'; + +vi.mock('@/layouts/AppSidebar', () => ({ default: () => null })); +vi.mock('@/pages/inbounds/form/InboundFormModal', () => ({ default: () => null })); function seedInbounds() { const rows = [1, 2].map((id) => ({ id, protocol: 'vless', tag: `in-${id}`, + originNodeGuid: `node-${id}`, enable: true, up: 10, down: 20, @@ -72,6 +80,7 @@ describe('inbound websocket merges keep unchanged state', () => { it('still rebuilds exactly the rows whose numbers moved', async () => { const { result } = await renderInbounds(); const before = result.current.dbInbounds; + const countsBefore = result.current.clientCount; act(() => result.current.applyClientStatsEvent({ @@ -86,8 +95,10 @@ describe('inbound websocket merges keep unchanged state', () => { const [first, second] = result.current.dbInbounds; expect(first).not.toBe(before[0]); expect(first.up).toBe(99); + expect(result.current.clientCount[1]).toBe(countsBefore[1]); expect(second).not.toBe(before[1]); expect(second.clientStats?.[0]?.up).toBe(5); + expect(result.current.clientCount[2]).not.toBe(countsBefore[2]); }); it('keeps the client rollup when a traffic push repeats the same online sets', async () => { @@ -107,6 +118,230 @@ describe('inbound websocket merges keep unchanged state', () => { }); }); +it('reuses unaffected rollups and client metadata on large online updates', async () => { + const { queryClient, rows, wrapper } = seedInbounds(); + const clients = Array.from({ length: 4000 }, (_, i) => ({ + email: `client-${i}@x`, + enable: true, + comment: 'shared subscription', + })); + const settings = JSON.stringify({ clients }); + queryClient.setQueryData( + keys.inbounds.slim(), + Array.from({ length: 30 }, (_, i) => ({ + ...rows[i % 2], + id: i + 1, + tag: `large-${i + 1}`, + settings, + })), + ); + const { result } = renderHook(() => useInbounds(), { wrapper }); + await waitFor(() => expect(result.current.clientCount[30]?.clients).toBe(4000)); + const before = result.current.clientCount; + act(() => + result.current.applyTrafficEvent({ + onlineByGuid: { 'node-1': [clients[0].email], 'node-2': [clients[1].email] }, + activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] }, + }), + ); + await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[0].email])); + const initial = result.current.clientCount; + expect(initial[1].active).toBe(before[1].active); + expect(initial[1].online).toEqual([clients[0].email]); + + act(() => + result.current.applyTrafficEvent({ + onlineByGuid: { 'node-1': [clients[2].email], 'node-2': [clients[1].email] }, + activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] }, + }), + ); + await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[2].email])); + expect(result.current.clientCount[1].active).toBe(initial[1].active); + for (let id = 2; id <= 30; id++) { + expect(result.current.clientCount[id]).toBe(initial[id]); + } +}); + +it('loads inbounds whose clientStats is null in the slim response', () => { + const { rows, queryClient, wrapper } = seedInbounds(); + queryClient.setQueryData(keys.inbounds.slim(), [ + { ...rows[0], protocol: 'mixed', settings: '{}', clientStats: null }, + { ...rows[1], settings: '{"clients":[]}', clientStats: null }, + ]); + const { result } = renderHook(() => useInbounds(), { wrapper }); + expect(result.current.fetched).toBe(true); + expect(result.current.dbInbounds.map((row) => row.id)).toEqual([1, 2]); + expect(result.current.clientCount[1]).toBeUndefined(); + expect(result.current.clientCount[2].clients).toBe(0); +}); + +it('withholds large inbound rollups until they match the refetched structure', async () => { + const { queryClient, rows, wrapper } = seedInbounds(); + const withClients = (count: number, remark: string) => ({ + ...rows[0], + remark, + settings: JSON.stringify({ + clients: Array.from({ length: count }, (_, i) => ({ + email: `member-${i}@example.test`, + enable: true, + })), + }), + }); + const seed = withClients(7000, 'initial'); + queryClient.setQueryData(keys.inbounds.slim(), [seed]); + const displayed: { remark: string; fetched: boolean; pending: boolean; count?: number }[] = []; + const { result } = renderHook( + () => { + const data = useInbounds(); + useLayoutEffect(() => { + const row = data.dbInbounds[0]; + if (row) + displayed.push({ + remark: row.remark, + fetched: data.fetched, + pending: data.clientCountsPending, + count: data.clientCount[row.id]?.clients, + }); + }); + return data; + }, + { wrapper }, + ); + await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(7000)); + for (const [count, remark] of [ + [8000, 'large refetch'], + [1, 'small refetch'], + [9000, 'large again'], + ] as const) { + act(() => queryClient.setQueryData(keys.inbounds.slim(), [withClients(count, remark)])); + await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(count)); + expect(displayed.filter((view) => view.remark === remark)).toEqual( + expect.arrayContaining([{ remark, fetched: true, pending: false, count }]), + ); + for (const view of displayed.filter((view) => view.remark === remark)) { + expect(view.fetched).toBe(true); + expect(view.count).toBe(view.pending ? undefined : count); + } + } +}); + +it('keeps the search, node filter and selection through large-list refetch and detail hydration', async () => { + const { queryClient, rows } = seedInbounds(); + const clients = (count: number) => + JSON.stringify({ + clients: Array.from({ length: count }, (_, i) => ({ + email: `member-${i}@example.test`, + enable: true, + })), + }); + const local = { ...rows[0], remark: 'Kept local', settings: clients(7000) }; + const remote = { ...rows[1], remark: 'Kept remote', nodeId: 7 }; + queryClient.setQueryData(keys.inbounds.slim(), [local, remote]); + queryClient.setQueryDefaults(keys.nodes.list(), { staleTime: Infinity }); + queryClient.setQueryData(keys.nodes.list(), [ + { id: 7, name: 'Remote', enable: true, status: 'online' }, + ]); + queryClient.setQueryData(keys.hosts.list(), []); + const get = vi.mocked(HttpUtil.get); + const fallback = get.getMockImplementation(); + get.mockImplementation(async (url, ...args) => + url === '/panel/api/inbounds/get/1' + ? new Msg(true, '', { ...local, remark: 'Kept hydrated', settings: clients(9000) }) + : ((await fallback?.(url, ...args)) ?? new Msg(true, '', [])), + ); + + const view = renderWithProviders( + + + , + { queryClient }, + ); + try { + await screen.findAllByText('7000'); + const search = screen.getByRole('textbox', { name: 'Search' }); + fireEvent.change(search, { target: { value: 'Kept' } }); + fireEvent.mouseDown(screen.getByRole('combobox', { name: 'Nodes' })); + fireEvent.click(await screen.findByText('Local (this panel)')); + const row = () => screen.getByRole('row', { name: /Kept (local|refetched|hydrated)/ }); + fireEvent.click(within(row()).getByRole('checkbox')); + const expectContext = () => { + expect(screen.getByRole('textbox', { name: 'Search' })).toBe(search); + expect((search as HTMLInputElement).value).toBe('Kept'); + expect(screen.queryByText('Kept remote')).toBeNull(); + expect((within(row()).getByRole('checkbox') as HTMLInputElement).checked).toBe(true); + }; + expectContext(); + + act(() => + queryClient.setQueryData(keys.inbounds.slim(), [ + { ...local, remark: 'Kept refetched', settings: clients(8000) }, + remote, + ]), + ); + await screen.findAllByText('8000'); + expectContext(); + + fireEvent.click(within(row()).getByRole('button', { name: 'Edit' })); + await screen.findAllByText('9000'); + expectContext(); + } finally { + view.unmount(); + getSharedWebSocketClient().disconnect(); + if (fallback) get.mockImplementation(fallback); + } +}); + +it('reuses the current rollup cache for subscribed websocket updates after defaults change', async () => { + const { queryClient, wrapper } = seedInbounds(); + const sockets: EventTarget[] = []; + class FixtureSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + readyState = FixtureSocket.CONNECTING; + constructor() { + super(); + sockets.push(this); + } + close() {} + } + const socketClient = getSharedWebSocketClient(); + socketClient.disconnect(); + vi.stubGlobal('WebSocket', FixtureSocket); + const { result, unmount } = renderHook( + () => { + const data = useInbounds(); + useWebSocket({ client_stats: data.applyClientStatsEvent }); + return data; + }, + { wrapper }, + ); + + try { + await waitFor(() => expect(result.current.clientCount[1]?.clients).toBe(1)); + act(() => queryClient.setQueryData(keys.settings.defaults(), { expireDiff: 3 })); + await waitFor(() => expect(result.current.expireDiff).toBe(3 * 86400000)); + const afterDefaults = result.current.clientCount[1]; + const [socket] = sockets; + if (!socket) throw new Error('WebSocket was not connected'); + act(() => + socket.dispatchEvent( + new MessageEvent('message', { + data: JSON.stringify({ + type: 'client_stats', + payload: { inbounds: [{ id: 1, up: 99 }] }, + }), + }), + ), + ); + expect(result.current.dbInbounds[0].up).toBe(99); + expect(result.current.clientCount[1]).toBe(afterDefaults); + } finally { + unmount(); + socketClient.disconnect(); + vi.unstubAllGlobals(); + } +}); + it('does not attribute shared online clients without matching inbound activity', async () => { const { rows, queryClient, wrapper } = seedInbounds(); queryClient.setQueryData( diff --git a/internal/amneziawgnet/relay_e2e_test.go b/internal/amneziawgnet/relay_e2e_test.go index 2d5a5756c..753ff6545 100644 --- a/internal/amneziawgnet/relay_e2e_test.go +++ b/internal/amneziawgnet/relay_e2e_test.go @@ -152,7 +152,7 @@ func TestSocksRelayAgainstRealXray(t *testing.T) { } defer func() { _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() + _ = cmd.Wait() }() waitForPort(t, socksPort) @@ -268,20 +268,10 @@ func TestSocksRelayAgainstRealXray(t *testing.T) { t.Fatalf("UDP echo = %q, want %q (xray log follows)\n%s", gotUDP, udpMsg, xrayLog.String()) } - // Real per-peer stats attribution: stop xray so its log is complete, then - // look for both directions' counters keyed by the peer's real email -- - // the exact proof Finding 3 established manually in Phase 0. - _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() - log := xrayLog.String() - wantUp := fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail) - wantDown := fmt.Sprintf("user>>>%s>>>traffic>>>downlink", wantEmail) - if !strings.Contains(log, wantUp) { - t.Errorf("xray log missing uplink stats counter %q\nfull log:\n%s", wantUp, log) - } - if !strings.Contains(log, wantDown) { - t.Errorf("xray log missing downlink stats counter %q\nfull log:\n%s", wantDown, log) - } + waitForXrayCounters(t, &xrayLog, + fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail), + fmt.Sprintf("user>>>%s>>>traffic>>>downlink", wantEmail), + ) } // TestManagerEnsureAutomaticallyWiresRelay is Phase 3's own real proof: unlike @@ -392,7 +382,7 @@ func TestManagerEnsureAutomaticallyWiresRelay(t *testing.T) { } defer func() { _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() + _ = cmd.Wait() }() waitForPort(t, socksPort) @@ -462,12 +452,23 @@ func TestManagerEnsureAutomaticallyWiresRelay(t *testing.T) { t.Errorf("TCP echo = %q, want %q", buf, tcpMsg) } - _ = cmd.Process.Kill() - _, _ = cmd.Process.Wait() - log := xrayLog.String() - wantUp := fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail) - if !strings.Contains(log, wantUp) { - t.Errorf("xray log missing uplink stats counter %q (Manager.Ensure's automatic relay wiring may not be attributing traffic correctly)\nfull log:\n%s", wantUp, log) + waitForXrayCounters(t, &xrayLog, fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail)) +} + +func waitForXrayCounters(t *testing.T, log *syncBuffer, counters ...string) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for _, counter := range counters { + for { + output := log.String() + if strings.Contains(output, counter) { + break + } + if time.Now().After(deadline) { + t.Fatalf("xray log missing stats counter %q\nfull log:\n%s", counter, output) + } + time.Sleep(10 * time.Millisecond) + } } } diff --git a/internal/web/service/tgbot/tgbot_send_test.go b/internal/web/service/tgbot/tgbot_send_test.go index b86391725..b71112ae8 100644 --- a/internal/web/service/tgbot/tgbot_send_test.go +++ b/internal/web/service/tgbot/tgbot_send_test.go @@ -11,7 +11,6 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/logger" - "github.com/mymmrac/telego" tu "github.com/mymmrac/telego/telegoutil" "github.com/nicksnyder/go-i18n/v2/i18n" ) @@ -55,13 +54,7 @@ func TestEditMessageTgBotSkipsNotModified(t *testing.T) { defer mock.Close() // Point the package-level bot at the mock. - origBot := liveBot() - t.Cleanup(func() { setTestBot(origBot) }) - var err error - bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(mock.URL)) - if err != nil { - t.Fatalf("NewBot: %v", err) - } + swapTestBot(t, mock.URL) // Snapshot warning count before the edit call. before := logger.GetLogs(100, "warning") @@ -87,13 +80,7 @@ func TestEditMessageCallbackTgBotSkipsNotModified(t *testing.T) { })) defer mock.Close() - origBot := liveBot() - t.Cleanup(func() { setTestBot(origBot) }) - var err error - bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(mock.URL)) - if err != nil { - t.Fatalf("NewBot: %v", err) - } + swapTestBot(t, mock.URL) before := logger.GetLogs(100, "warning") diff --git a/internal/web/service/tuic_relay_isolation_test.go b/internal/web/service/tuic_relay_isolation_test.go index bc19cfc3c..f6caa4bdd 100644 --- a/internal/web/service/tuic_relay_isolation_test.go +++ b/internal/web/service/tuic_relay_isolation_test.go @@ -262,6 +262,9 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T) dependent := ordinary dependent.Tag = "dependent-ordinary" dependent.Port = freeLoopbackPort(t) + for dependent.Port == ordinary.Port { + dependent.Port = freeLoopbackPort(t) + } updatedSecond := isolationRelay(t, second.TuicInboundID, "new-second@test") after.InboundConfigs = []xray.InboundConfig{before.InboundConfigs[0], next, updatedSecond, ordinary, dependent} var policy map[string]any @@ -278,6 +281,12 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T) if applied, err := (&XrayService{}).tryHotApply(process, &after); applied || err == nil || !strings.Contains(err.Error(), "SOCKS5 bounds") { t.Fatalf("failed rename result = %t, %v", applied, err) } + // Reserve the deferred port before the relay probes start their own listeners. + reservation, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dependent.Port)) + if err != nil { + t.Fatalf("new inbound started before its dependent routing was applied: %v", err) + } + t.Cleanup(func() { _ = reservation.Close() }) assertIsolationRelay(t, previous, "original@test") assertIsolationRelay(t, second, "old-second@test") ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) @@ -294,11 +303,6 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T) t.Fatalf("new TUIC account escaped its deferred routing policy: %v", err) } assertIsolationRelay(t, ordinary, "other@test") - reservation, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dependent.Port)) - if err != nil { - t.Fatalf("new inbound started before its dependent routing was applied: %v", err) - } - _ = reservation.Close() route, err := api.TestRoute(xray.RouteTestRequest{InboundTag: next.Tag, IP: "203.0.113.1", Port: 6697}) if err != nil || route.Matched { t.Fatalf("routing depending on an uninstalled relay was published: route=%+v err=%v", route, err) @@ -306,6 +310,9 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T) if string(process.GetConfig().RouterConfig) != string(before.RouterConfig) { t.Fatal("snapshot recorded deferred routing as applied") } + if err := reservation.Close(); err != nil { + t.Fatal(err) + } after.InboundConfigs[1] = previous after.InboundConfigs[1].Tag = next.Tag if applied, err := (&XrayService{}).tryHotApply(process, &after); !applied || err != nil { From 0afa11ddffa7958585d320179415d1d5fe410a5c Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 03:26:44 +0330 Subject: [PATCH 14/14] fix(nodes): share lightweight remote inbound catalog refreshes (#7313) Replace full inbound/client-list downloads on cold remote ID lookups with an owner-scoped six-field catalog projected directly from the database. Coalesce concurrent catalog refreshes per remote while preserving independent caller cancellation and rejecting stale ID mappings after topology mutations. Seed reconciliation from the catalog, create missing inbounds directly, preserve prefixed/adopted aliases and invalidate pushed state when remote IDs change. Avoid invalidating catalog generations on unchanged-ID settings pushes. Retain client-membership-aware reconciliation state and legacy full-list fallback only on HTTP 404/405. Cover permissions, query projection, concurrent refresh/cancellation, deletion/recreation, reconciliation request counts and mixed-version node compatibility. Integrated CI and Docs CI passed, including race, node E2E and PostgreSQL catalog projection. Synthetic response-size comparison is not a production latency benchmark. Fixes #7303. --- .github/workflows/ci.yml | 3 + .../docs/en/reference/api/inbounds.mdx | 17 +- docs/public/openapi.json | 86 +++++ frontend/public/openapi.json | 86 +++++ frontend/src/generated/examples.ts | 8 + frontend/src/generated/schemas.ts | 37 ++ frontend/src/generated/types.ts | 9 + frontend/src/generated/zod.ts | 10 + frontend/src/pages/api-docs/endpoints.ts | 10 + internal/nodee2e/node_snapshot_test.go | 21 +- internal/web/controller/api.go | 1 + internal/web/controller/inbound.go | 10 + internal/web/job/ldap_sync_hung_node_test.go | 2 +- .../web/job/node_traffic_isolation_test.go | 7 +- .../job/periodic_traffic_reset_nodes_test.go | 2 +- internal/web/node_contract_test.go | 76 ++++ internal/web/runtime/reconcile_skip_test.go | 8 + internal/web/runtime/remote.go | 140 +++----- .../web/runtime/remote_inbound_catalog.go | 153 ++++++++ .../runtime/remote_inbound_catalog_test.go | 334 ++++++++++++++++++ .../web/runtime/remote_inbound_lookup_test.go | 6 +- internal/web/runtime/remote_reset_test.go | 7 +- .../service/client_create_reconcile_test.go | 2 +- internal/web/service/inbound.go | 11 + .../service/inbound_node_reconcile_test.go | 42 ++- internal/web/service/node_http_fake_test.go | 4 +- tools/openapigen/main.go | 2 +- 27 files changed, 990 insertions(+), 104 deletions(-) create mode 100644 internal/web/runtime/remote_inbound_catalog.go create mode 100644 internal/web/runtime/remote_inbound_catalog_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f8c2c9d3..73f7498be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -155,6 +155,9 @@ jobs: exit 1 fi + - name: PostgreSQL inbound catalog scope and projection + run: go test ./internal/web -run '^TestRemoteInboundCatalogScopeAndProjection$' -count=1 -v + - name: PostgreSQL online attribution regressions run: | set -o pipefail diff --git a/docs/content/docs/en/reference/api/inbounds.mdx b/docs/content/docs/en/reference/api/inbounds.mdx index 165dc5fd8..3f0d9d5ca 100644 --- a/docs/content/docs/en/reference/api/inbounds.mdx +++ b/docs/content/docs/en/reference/api/inbounds.mdx @@ -29,6 +29,11 @@ _openapi: for list pages; fetch /get/:id when you need the full per-client payload (uuid, password, flow, ...). url: '#same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-' + - depth: 2 + title: List inbound metadata for the authenticated user. Returns id, tag, + remark, listen, protocol, and port for remote ID lookup and + reconciliation. + url: '#list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation' - depth: 2 title: Lightweight picker projection of the authenticated user’s inbounds. Returns id, remark, tag, protocol, port, a server-computed @@ -148,6 +153,10 @@ _openapi: Use this for list pages; fetch /get/:id when you need the full per-client payload (uuid, password, flow, ...). id: same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow- + - content: List inbound metadata for the authenticated user. Returns id, tag, + remark, listen, protocol, and port for remote ID lookup and + reconciliation. + id: list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation - content: Lightweight picker projection of the authenticated user’s inbounds. Returns id, remark, tag, protocol, port, a server-computed tlsFlowCapable flag (true for VLESS on TCP with tls or reality, or on @@ -231,7 +240,11 @@ _openapi: decryption. An empty list can remove rules even from an incompatible inbound. Triggers an Xray restart. id: replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-nonempty-lists-require-tcp-with-tlsreality-and-no-active-vless-server-decryption-an-empty-list-can-remove-rules-even-from-an-incompatible-inbound-triggers-an-xray-restart - contents: [] + contents: + - content: Available to panel sessions, admin, node-admin, and node-sync tokens. + The catalog queries only metadata columns. An empty catalog is + returned as an empty array. + heading: list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} @@ -241,7 +254,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index afb1a2f6b..870ef99e3 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -5867,6 +5867,43 @@ ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { @@ -7153,6 +7190,55 @@ } } }, + "/panel/api/inbounds/catalog": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.", + "operationId": "get_panel_api_inbounds_catalog", + "description": "Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RemoteInboundOption" + } + } + } + }, + "example": { + "success": true, + "obj": [ + { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + } + ] + } + } + } + } + } + } + }, "/panel/api/inbounds/options": { "get": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index afb1a2f6b..870ef99e3 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -5867,6 +5867,43 @@ ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { @@ -7153,6 +7190,55 @@ } } }, + "/panel/api/inbounds/catalog": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.", + "operationId": "get_panel_api_inbounds_catalog", + "description": "Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RemoteInboundOption" + } + } + } + }, + "example": { + "success": true, + "obj": [ + { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + } + ] + } + } + } + } + } + } + }, "/panel/api/inbounds/options": { "get": { "tags": [ diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 310051ae7..b8e09aa02 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1567,6 +1567,14 @@ export const EXAMPLES: Record = { ], "target": "old.example.com:443" }, + "RemoteInboundOption": { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + }, "ServerSettings": { "contentPaddingAddition": "", "disableCookies": false, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 542b3178d..378fc8b16 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -5841,6 +5841,43 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "RemoteInboundOption": { + "properties": { + "id": { + "example": 7, + "type": "integer" + }, + "listen": { + "example": "127.0.0.1", + "type": "string" + }, + "port": { + "example": 443, + "type": "integer" + }, + "protocol": { + "example": "vless", + "type": "string" + }, + "remark": { + "example": "VLESS-443", + "type": "string" + }, + "tag": { + "example": "in-443", + "type": "string" + } + }, + "required": [ + "id", + "listen", + "port", + "protocol", + "remark", + "tag" + ], + "type": "object" + }, "ServerSettings": { "description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 62b462e76..4d2bca454 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1318,6 +1318,15 @@ export interface RealityWatchStatus { target: string; } +export interface RemoteInboundOption { + id: number; + listen: string; + port: number; + protocol: Protocol; + remark: string; + tag: string; +} + export interface ServerSettings { contentPaddingAddition?: string; disableCookies: boolean; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index f0a263118..de23c7e02 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1411,6 +1411,16 @@ export const RealityWatchStatusSchema = z.object({ }); export type RealityWatchStatus = z.infer; +export const RemoteInboundOptionSchema = z.object({ + id: z.number().int(), + listen: z.string(), + port: z.number().int(), + protocol: z.lazy(() => ProtocolSchema), + remark: z.string(), + tag: z.string(), +}); +export type RemoteInboundOption = z.infer; + export const ServerSettingsSchema = z.object({ contentPaddingAddition: z.string().optional(), disableCookies: z.boolean(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index a92ac3320..91080469e 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -303,6 +303,16 @@ export const sections: readonly Section[] = [ response: '{\n "success": true,\n "obj": [\n {\n "id": 1,\n "remark": "VLESS-443",\n "settings": {\n "clients": [\n { "email": "alice", "enable": true }\n ],\n "decryption": "none"\n },\n "clientStats": []\n }\n ]\n}', }, + { + method: 'GET', + path: '/panel/api/inbounds/catalog', + summary: + 'List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.', + description: + 'Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.', + responseSchema: 'RemoteInboundOption', + responseSchemaArray: true, + }, { method: 'GET', path: '/panel/api/inbounds/options', diff --git a/internal/nodee2e/node_snapshot_test.go b/internal/nodee2e/node_snapshot_test.go index dcdbf55cf..50fdfa891 100644 --- a/internal/nodee2e/node_snapshot_test.go +++ b/internal/nodee2e/node_snapshot_test.go @@ -45,7 +45,7 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { token := node.mintToken("snapshot-link", "node-sync") master.start() node.start() - var lists, compact, full, unchanged, clientAdds atomic.Int32 + var catalogs, lists, compact, full, unchanged, clientAdds atomic.Int32 target, err := url.Parse(node.url()) if err != nil { t.Fatal(err) @@ -90,6 +90,8 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { } front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { switch req.URL.Path { + case "/panel/api/inbounds/catalog": + catalogs.Add(1) case "/panel/api/inbounds/list": lists.Add(1) case "/panel/api/inbounds/trafficSnapshot": @@ -114,10 +116,25 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil { t.Fatal(err) } + params := map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true} + if version.master == current { + var options []inboundView + obj := master.call(http.MethodPost, "/panel/api/nodes/inbounds", params) + if err := json.Unmarshal(obj, &options); err != nil || len(options) != 1 || options[0].Id != source.Id { + t.Fatalf("read node options: %s, %v", obj, err) + } + var wantLists int32 + if version.node != current { + wantLists = 1 + } + if got := lists.Swap(0); catalogs.Load() != 1 || got != wantLists { + t.Fatalf("node options used catalog=%d and full list=%d, want 1 and %d", catalogs.Load(), got, wantLists) + } + } if version.master == current { node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix-secondary", secondaryPort, nil)) } - master.call(http.MethodPost, "/panel/api/nodes/add", map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}) + master.call(http.MethodPost, "/panel/api/nodes/add", params) eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) { ib, ok := master.inboundOnPort(inboundPort) ready := lists.Load() >= 3 diff --git a/internal/web/controller/api.go b/internal/web/controller/api.go index 879b6e930..bbe7fc371 100644 --- a/internal/web/controller/api.go +++ b/internal/web/controller/api.go @@ -114,6 +114,7 @@ var monitorScopeAllow = map[string]struct{}{ var nodeSyncScopeAllow = map[string]map[string]struct{}{ "/server/status": {http.MethodGet: {}}, "/inbounds/list": {http.MethodGet: {}}, + "/inbounds/catalog": {http.MethodGet: {}}, "/inbounds/trafficSnapshot": {http.MethodGet: {}}, "/inbounds/add": {http.MethodPost: {}}, "/inbounds/del/:id": {http.MethodPost: {}}, diff --git a/internal/web/controller/inbound.go b/internal/web/controller/inbound.go index f89aea5bb..d8354d795 100644 --- a/internal/web/controller/inbound.go +++ b/internal/web/controller/inbound.go @@ -84,6 +84,7 @@ func (a *InboundController) initRouter(g *gin.RouterGroup) { g.GET("/trafficSnapshot", a.getTrafficSnapshot) g.GET("/list/slim", a.getInboundsSlim) g.GET("/options", a.getInboundOptions) + g.GET("/catalog", a.getInboundCatalog) g.GET("/allLinks", a.getAllInboundLinks) g.GET("/get/:id", a.getInbound) g.GET("/:id/fallbacks", a.getFallbacks) @@ -152,6 +153,15 @@ func (a *InboundController) getInboundOptions(c *gin.Context) { jsonObj(c, options, nil) } +func (a *InboundController) getInboundCatalog(c *gin.Context) { + options, err := a.inboundService.GetInboundCatalog(session.GetLoginUser(c).Id) + if err != nil { + jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err) + return + } + jsonObj(c, options, nil) +} + // getAmneziaWGKernelReadiness reports whether this host can run an AmneziaWG // inbound on the kernel module, so the form can disable the toggle and say why. func (a *InboundController) getAmneziaWGKernelReadiness(c *gin.Context) { diff --git a/internal/web/job/ldap_sync_hung_node_test.go b/internal/web/job/ldap_sync_hung_node_test.go index 0c9d2c55e..f89ef01f2 100644 --- a/internal/web/job/ldap_sync_hung_node_test.go +++ b/internal/web/job/ldap_sync_hung_node_test.go @@ -29,7 +29,7 @@ func ldapHungNodeInbound(t *testing.T, emails []string) (*resetGate, *model.Inbo srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.Copy(io.Discard, r.Body) w.Header().Set("Content-Type", "application/json") - if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "inbounds/list") { + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "inbounds/catalog") { _, _ = w.Write([]byte(`{"success":true,"obj":[{"id":1,"tag":"` + tag + `"}]}`)) return } diff --git a/internal/web/job/node_traffic_isolation_test.go b/internal/web/job/node_traffic_isolation_test.go index 68bed06a1..82d74a063 100644 --- a/internal/web/job/node_traffic_isolation_test.go +++ b/internal/web/job/node_traffic_isolation_test.go @@ -39,11 +39,14 @@ func TestNodeTrafficSyncAllowsHealthyNextTickDuringSlowReconcile(t *testing.T) { var slowID int for _, slow := range []bool{true, false} { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + switch { + case slow && strings.HasSuffix(r.URL.Path, "/inbounds/catalog"): slowReconciles.Add(1) slowRequests <- struct{}{} <-release - } else if !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + case slow && strings.HasSuffix(r.URL.Path, "/inbounds/list"): + slowRequests <- struct{}{} + case !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list"): fastRequests <- struct{}{} } w.Header().Set("Content-Type", "application/json") diff --git a/internal/web/job/periodic_traffic_reset_nodes_test.go b/internal/web/job/periodic_traffic_reset_nodes_test.go index 18619fd1b..525a220f6 100644 --- a/internal/web/job/periodic_traffic_reset_nodes_test.go +++ b/internal/web/job/periodic_traffic_reset_nodes_test.go @@ -46,7 +46,7 @@ func resetNode(t *testing.T, gate *resetGate, name, inboundTag string) int { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.Copy(io.Discard, r.Body) - if strings.HasSuffix(r.URL.Path, "/panel/api/inbounds/list") { + if strings.HasSuffix(r.URL.Path, "/panel/api/inbounds/catalog") { w.Header().Set("Content-Type", "application/json") _, _ = fmt.Fprintf(w, `{"success":true,"obj":[{"id":1,"tag":%q}]}`, inboundTag) return diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index f2e13b453..83d7b81ca 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -13,14 +13,17 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" "github.com/robfig/cron/v3" + "gorm.io/gorm" "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" "github.com/mhsanaei/3x-ui/v3/internal/util/crypto" "github.com/mhsanaei/3x-ui/v3/internal/web/global" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" @@ -137,6 +140,79 @@ func seedNodeTraffic(t *testing.T, emails ...string) { const contractTag = "in-51001-tcp" +func TestRemoteInboundCatalogScopeAndProjection(t *testing.T) { + cleanup, err := testpg.IsolatePackage("inbound_catalog") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + node := startContractNode(t) + db := database.GetDB() + var user model.User + if err := db.Order("id ASC").First(&user).Error; err != nil { + t.Fatal(err) + } + owned := masterInbound("owned", true, "private") + owned.UserId, owned.Listen = user.Id, "127.0.0.1" + other := masterInbound("different owner", true, "private-other") + other.UserId, other.Port, other.Tag = user.Id+1, 51002, "in-51002-tcp" + if err := db.Create([]*model.Inbound{owned, other}).Error; err != nil { + t.Fatal(err) + } + var reads, wide atomic.Int32 + if err := db.Callback().Query().After("gorm:query").Register("test:catalog_projection", func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" { + reads.Add(1) + sql := tx.Statement.SQL.String() + if strings.Contains(sql, "*") || strings.Contains(sql, "settings") { + wide.Add(1) + } + } + }); err != nil { + t.Fatal(err) + } + for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeAdmin, model.ApiScopeNodeSync, model.ApiScopeMonitor} { + t.Run(scope, func(t *testing.T) { + node.masterWithToken(t, scope) + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, node.srv.URL+"/panel/api/inbounds/catalog", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer contract-"+scope) + resp, err := node.srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if scope == model.ApiScopeMonitor { + if resp.StatusCode != http.StatusForbidden { + t.Fatalf("monitor catalog status=%d, want forbidden", resp.StatusCode) + } + return + } + var envelope struct { + Success bool + Obj []map[string]any + } + if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusOK || !envelope.Success || len(envelope.Obj) != 1 { + t.Fatalf("catalog status=%d envelope=%+v", resp.StatusCode, envelope) + } + got := envelope.Obj[0] + if len(got) != 6 || got["id"] != float64(owned.Id) || got["tag"] != owned.Tag || + got["remark"] != owned.Remark || got["listen"] != owned.Listen || + got["protocol"] != string(owned.Protocol) || got["port"] != float64(owned.Port) { + t.Fatalf("unexpected catalog fields: %v", got) + } + }) + } + if reads.Load() != 3 || wide.Load() != 0 { + t.Fatalf("catalog queries = %d, wide queries = %d", reads.Load(), wide.Load()) + } +} + func masterInbound(remark string, enable bool, clients ...string) *model.Inbound { entries := make([]string, 0, len(clients)) for i, email := range clients { diff --git a/internal/web/runtime/reconcile_skip_test.go b/internal/web/runtime/reconcile_skip_test.go index 8e225320c..42fc4bd1e 100644 --- a/internal/web/runtime/reconcile_skip_test.go +++ b/internal/web/runtime/reconcile_skip_test.go @@ -17,6 +17,11 @@ import ( func TestReconcileInbound_SkipsUnchanged(t *testing.T) { var pushes atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/panel/api/inbounds/add" { + pushes.Add(1) + _, _ = w.Write([]byte(`{"success":true,"obj":{"id":7,"tag":"in-1"}}`)) + return + } if r.Method == http.MethodPost && (strings.Contains(r.URL.Path, "/panel/api/inbounds/update/") || strings.Contains(r.URL.Path, "/panel/api/inbounds/add")) { pushes.Add(1) @@ -109,6 +114,9 @@ func newCountingNodeServer(t *testing.T, clientsResp string) (*httptest.Server, srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch { + case r.URL.Path == "/panel/api/inbounds/catalog": + _, _ = w.Write([]byte(`{"success":true,"obj":[]}`)) + return case strings.Contains(r.URL.Path, "/panel/api/inbounds/add"): counts.adds.Add(1) case strings.Contains(r.URL.Path, "/panel/api/inbounds/update/"): diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index e3e0830fd..cfdf8c9a1 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -94,6 +94,8 @@ type Remote struct { mu sync.RWMutex remoteIDByTag map[string]int adoptedAliases map[string]string + catalogFlight *inboundCatalogFlight + catalogVersion uint64 // pushedFP holds the fingerprint of the last inbound wire payload successfully // pushed, keyed by panel-side tag, so reconcile can skip re-sending an // unchanged inbound. Guarded by mu; dropped with the Remote on node config change. @@ -123,12 +125,12 @@ type Remote struct { } type RemoteInboundOption struct { - Id int `json:"id"` - Tag string `json:"tag"` - Remark string `json:"remark"` - Listen string `json:"listen"` - Protocol model.Protocol `json:"protocol"` - Port int `json:"port"` + Id int `json:"id" example:"7"` + Tag string `json:"tag" example:"in-443"` + Remark string `json:"remark" example:"VLESS-443"` + Listen string `json:"listen" example:"127.0.0.1"` + Protocol model.Protocol `json:"protocol" example:"vless"` + Port int `json:"port" example:"443"` } func NewRemote(n *model.Node, r NodeEgressResolver) *Remote { @@ -190,7 +192,7 @@ func (r *Remote) nodeSupports(ctx context.Context, capability string) (bool, err caps := r.nodeCaps r.mu.RUnlock() if caps == nil { - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, ""); err != nil { return false, err } r.mu.RLock() @@ -444,7 +446,7 @@ func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) { if id, ok := r.cacheGetTag(tag); ok { return id, nil } - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, tag); err != nil { return 0, err } if id, ok := r.cacheGetTag(tag); ok { @@ -478,24 +480,32 @@ func (r *Remote) cacheGetTag(tag string) (int, bool) { return r.cachedTagID(tag) } +// cachedTagID requires r.mu to be held. func (r *Remote) cachedTagID(tag string) (int, bool) { - if id, ok := r.remoteIDByTag[tag]; ok { + return lookupRemoteTag(r.remoteIDByTag, tag, nodeInboundTagPrefix(r.node.Id)) +} + +func lookupRemoteTag(ids map[string]int, tag, prefix string) (int, bool) { + if id, ok := ids[tag]; ok { return id, true } - prefix := nodeInboundTagPrefix(r.node.Id) if stripped, found := strings.CutPrefix(tag, prefix); found { - tag = stripped - } else { - tag = prefix + tag + id, ok := ids[stripped] + return id, ok } - id, ok := r.remoteIDByTag[tag] + id, ok := ids[prefix+tag] return id, ok } func (r *Remote) cacheSet(tag string, id int) { r.mu.Lock() defer r.mu.Unlock() + previous, known := r.cachedTagID(tag) r.remoteIDByTag[tag] = id + // Settings-only pushes do not supersede the catalog's ID mapping. + if !known || previous != id { + r.catalogVersion++ + } } func (r *Remote) cacheDel(tag string) { @@ -503,19 +513,11 @@ func (r *Remote) cacheDel(tag string) { defer r.mu.Unlock() delete(r.remoteIDByTag, tag) delete(r.pushedFP, tag) -} - -// forgetTag drops every tag form cacheGetTag would match, once the node reports -// none of them, so the next resolve re-reads the node instead of a deleted id. -func (r *Remote) forgetTag(tag string) { - prefix := nodeInboundTagPrefix(r.node.Id) - bare := strings.TrimPrefix(tag, prefix) - r.cacheDel(bare) - r.cacheDel(prefix + bare) + r.catalogVersion++ } func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) { - if err := r.refreshRemoteIDs(ctx); err != nil { + if _, err := r.loadInboundCatalog(ctx, ""); err != nil { return nil, err } r.mu.RLock() @@ -528,52 +530,8 @@ func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) { } func (r *Remote) ListInboundOptions(ctx context.Context) ([]RemoteInboundOption, error) { - env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) - if err != nil { - return nil, err - } - list, err := json_util.DecodeCappedList[RemoteInboundOption](env.Obj, maxNodeInbounds) - if err != nil { - return nil, fmt.Errorf("decode inbound list: %w", err) - } - return list, nil -} - -func (r *Remote) refreshRemoteIDs(ctx context.Context) error { - env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) - if err != nil { - return err - } - list, err := json_util.DecodeCappedList[struct { - Id int `json:"id"` - Tag string `json:"tag"` - }](env.Obj, maxNodeInbounds) - if err != nil { - return fmt.Errorf("decode inbound list: %w", err) - } - next := make(map[string]int, len(list)) - for _, ib := range list { - if ib.Tag == "" { - continue - } - next[ib.Tag] = ib.Id - } - r.mu.Lock() - // A rebuild sees only node-reported tags, so the adopted aliases must be - // re-applied or a later op on an adopted inbound re-creates it as a duplicate. - for centralTag, nodeTag := range r.adoptedAliases { - // A tag the node reports itself is authoritative; the alias only fills - // the gap left for a central tag the node knows under another name. - if _, reported := next[centralTag]; reported { - continue - } - if id, ok := next[nodeTag]; ok { - next[centralTag] = id - } - } - r.remoteIDByTag = next - r.mu.Unlock() - return nil + list, err := r.loadInboundCatalog(ctx, "") + return slices.Clone(list), err } func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error { @@ -652,16 +610,17 @@ func (r *Remote) SetInboundSubSortIndex(ctx context.Context, ib *model.Inbound, // whether a push actually happened. This turns a full-fleet reconcile from "send // every inbound's full settings" into "send only what changed". func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, existsOnNode bool) (bool, error) { + if !existsOnNode { + r.ForgetInbound(ib.Tag) + err := r.AddInbound(ctx, ib) + return err == nil, err + } fp := wireFingerprint(wireInbound(ib, r.node.Id)) - if existsOnNode { - r.mu.RLock() - prev, ok := r.pushedFP[ib.Tag] - r.mu.RUnlock() - if ok && prev.fingerprint == fp { - return false, nil - } - } else { - r.forgetTag(ib.Tag) + r.mu.RLock() + prev, ok := r.pushedFP[ib.Tag] + r.mu.RUnlock() + if ok && prev.fingerprint == fp { + return false, nil } if err := r.UpdateInbound(ctx, ib, ib); err != nil { return false, err @@ -702,14 +661,22 @@ func (r *Remote) ForgetInbound(tag string) { bare := strings.TrimPrefix(tag, prefix) r.mu.Lock() defer r.mu.Unlock() - for _, t := range []string{bare, prefix + bare} { - if alias, ok := r.adoptedAliases[t]; ok { - delete(r.remoteIDByTag, alias) - delete(r.adoptedAliases, t) + forget := func(t string) { + t = strings.TrimPrefix(t, prefix) + for _, form := range []string{t, prefix + t} { + delete(r.remoteIDByTag, form) + delete(r.pushedFP, form) } - delete(r.remoteIDByTag, t) - delete(r.pushedFP, t) } + for central, nodeTag := range r.adoptedAliases { + if strings.TrimPrefix(central, prefix) == bare || strings.TrimPrefix(nodeTag, prefix) == bare { + forget(central) + forget(nodeTag) + delete(r.adoptedAliases, central) + } + } + forget(bare) + r.catalogVersion++ } // AdoptInboundAlias records a deployed alias without mutating either panel. @@ -720,6 +687,7 @@ func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption r.remoteIDByTag[remote.Tag] = remote.Id r.remoteIDByTag[ib.Tag] = remote.Id r.adoptedAliases[ib.Tag] = remote.Tag + r.catalogVersion++ r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -831,7 +799,7 @@ func (r *Remote) AddClientGroup(ctx context.Context, tags []string, client json. var refreshErr error for _, tag := range tags { if id, ok := r.cacheGetTag(tag); !ok || id <= 0 { - refreshErr = r.refreshRemoteIDs(ctx) + _, refreshErr = r.loadInboundCatalog(ctx, "") break } } diff --git a/internal/web/runtime/remote_inbound_catalog.go b/internal/web/runtime/remote_inbound_catalog.go new file mode 100644 index 000000000..5531cc031 --- /dev/null +++ b/internal/web/runtime/remote_inbound_catalog.go @@ -0,0 +1,153 @@ +package runtime + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + + "github.com/mhsanaei/3x-ui/v3/internal/util/json_util" +) + +type inboundCatalogFlight struct { + done chan struct{} + cancel context.CancelFunc + waiters int + options []RemoteInboundOption + err error +} + +// loadInboundCatalog shares a refresh across callers. A lookup rechecks its cache +// under the same lock used to register the flight. +func (r *Remote) loadInboundCatalog(ctx context.Context, tag string) ([]RemoteInboundOption, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.Lock() + if tag != "" { + if _, ok := lookupRemoteTag(r.remoteIDByTag, tag, nodeInboundTagPrefix(r.node.Id)); ok { + r.mu.Unlock() + return nil, nil + } + } + flight := r.catalogFlight + if flight == nil { + // The RPC belongs to the group. Each caller waits on its own context. + requestCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), remoteHTTPTimeout) + flight = &inboundCatalogFlight{done: make(chan struct{}), cancel: cancel} + r.catalogFlight = flight + go r.refreshInboundCatalog(requestCtx, flight, r.catalogVersion) + } + flight.waiters++ + r.mu.Unlock() + + select { + case <-flight.done: + if err := ctx.Err(); err != nil { + return nil, err + } + return flight.options, flight.err + case <-ctx.Done(): + r.mu.Lock() + flight.waiters-- + if r.catalogFlight == flight && flight.waiters == 0 { + r.catalogFlight = nil + flight.cancel() + } + r.mu.Unlock() + return nil, ctx.Err() + } +} + +func (r *Remote) refreshInboundCatalog(ctx context.Context, flight *inboundCatalogFlight, version uint64) { + defer flight.cancel() + defer close(flight.done) + for attempt := 0; ; attempt++ { + options, ids, err := r.fetchInboundCatalog(ctx) + r.mu.Lock() + if r.catalogFlight != flight { + r.mu.Unlock() + return + } + if err == nil && version != r.catalogVersion { + // An inbound mutation completed during the read. Retry once within + // the same budget, so a stale response cannot revive an old ID. + if attempt == 0 { + version = r.catalogVersion + r.mu.Unlock() + continue + } + err = errors.New("remote inbound catalog changed during refresh") + } + if err == nil { + r.installInboundCatalog(ids) + flight.options = options + } + flight.err = err + r.catalogFlight = nil + r.mu.Unlock() + return + } +} + +func (r *Remote) fetchInboundCatalog(ctx context.Context) (list []RemoteInboundOption, ids map[string]int, err error) { + // Fetching runs on the shared worker, outside each caller's panic boundary. + defer func() { + if cause := recover(); cause != nil { + list, ids, err = nil, nil, fmt.Errorf("fetch inbound catalog: panic: %v", cause) + } + }() + env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/catalog", nil) + var status *remoteHTTPError + legacy := errors.As(err, &status) && (status.code == http.StatusNotFound || status.code == http.StatusMethodNotAllowed) + if legacy { + env, err = r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil) + } + if err != nil { + return nil, nil, err + } + if !legacy && !bytes.HasPrefix(bytes.TrimSpace(env.Obj), []byte("[")) { + return nil, nil, errors.New("decode inbound list: catalog must be an array") + } + list, err = json_util.DecodeCappedList[RemoteInboundOption](env.Obj, maxNodeInbounds) + if err != nil { + return nil, nil, fmt.Errorf("decode inbound list: %w", err) + } + ids = make(map[string]int, len(list)) + for _, ib := range list { + if ib.Id <= 0 || ib.Tag == "" { + return nil, nil, errors.New("decode inbound list: entry missing a valid ID or tag") + } + if _, exists := ids[ib.Tag]; exists { + return nil, nil, errors.New("decode inbound list: duplicate tag") + } + ids[ib.Tag] = ib.Id + } + return list, ids, nil +} + +// installInboundCatalog runs with mu held. Explicit node tags outrank inferred aliases. +func (r *Remote) installInboundCatalog(ids map[string]int) { + prefix := nodeInboundTagPrefix(r.node.Id) + aliases := make(map[string]int, len(r.adoptedAliases)) + for central, nodeTag := range r.adoptedAliases { + if _, exists := lookupRemoteTag(ids, central, prefix); exists { + continue + } + if id, ok := lookupRemoteTag(ids, nodeTag, prefix); ok { + aliases[central] = id + } + } + for tag, id := range aliases { + ids[tag] = id + } + for tag := range r.pushedFP { + oldID, known := lookupRemoteTag(r.remoteIDByTag, tag, prefix) + nextID, present := lookupRemoteTag(ids, tag, prefix) + if !present || known && nextID != oldID { + delete(r.pushedFP, tag) + } + } + r.remoteIDByTag = ids +} diff --git a/internal/web/runtime/remote_inbound_catalog_test.go b/internal/web/runtime/remote_inbound_catalog_test.go new file mode 100644 index 000000000..b34e01edd --- /dev/null +++ b/internal/web/runtime/remote_inbound_catalog_test.go @@ -0,0 +1,334 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +type observedCatalogContext struct { + context.Context + waiting chan struct{} + once sync.Once +} + +func (ctx *observedCatalogContext) Done() <-chan struct{} { + ctx.once.Do(func() { close(ctx.waiting) }) + return ctx.Context.Done() +} + +func TestRemoteInboundCatalogCoalescesMissesAcrossCallerCancellation(t *testing.T) { + var modern, legacy atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + var first, cleanup sync.Once + unblock := func() { cleanup.Do(func() { close(release) }) } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + modern.Add(1) + case "/panel/api/inbounds/list": + legacy.Add(1) + default: + http.NotFound(w, req) + return + } + first.Do(func() { close(started) }) + select { + case <-release: + fmt.Fprint(w, `{"success":true,"obj":[{"id":43,"tag":"in-443"}]}`) + case <-req.Context().Done(): + } + })) + t.Cleanup(srv.Close) + t.Cleanup(unblock) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx, finish := context.WithTimeout(context.Background(), 4*time.Second) + defer finish() + leaderCtx, cancel := context.WithCancel(ctx) + defer cancel() + leader := make(chan error, 1) + go func() { + _, err := r.resolveRemoteID(leaderCtx, "in-443") + leader <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog request never started") + } + const followers = 6 + results := make(chan error, followers) + tag := fmt.Sprintf("n%d-in-443", r.node.Id) + for range followers { + waiter := &observedCatalogContext{Context: ctx, waiting: make(chan struct{})} + go func() { + id, err := r.resolveRemoteID(waiter, tag) + if err == nil && id != 43 { + err = fmt.Errorf("resolved ID = %d, want 43", id) + } + results <- err + }() + select { + case <-waiter.waiting: + case <-ctx.Done(): + t.Fatal("follower did not join the lookup") + } + } + cancel() + select { + case err := <-leader: + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled caller got %v", err) + } + case <-ctx.Done(): + t.Fatal("canceled caller still waits on the catalog") + } + unblock() + for range followers { + select { + case err := <-results: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("follower never received the catalog") + } + } + if id, err := r.resolveRemoteID(ctx, tag); err != nil || id != 43 { + t.Fatalf("warm cache = (%d, %v), want 43", id, err) + } + if modern.Load() != 1 || legacy.Load() != 0 { + t.Fatalf("catalog requests = %d, full list requests = %d; want 1 and 0", modern.Load(), legacy.Load()) + } +} + +func TestRemoteInboundCatalogLegacyFallbackSeedsCache(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} { + t.Run(http.StatusText(status), func(t *testing.T) { + var modern, legacy atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + modern.Add(1) + w.WriteHeader(status) + case "/panel/api/inbounds/list": + legacy.Add(1) + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"test","port":443,"settings":"large"}]}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx := context.Background() + options, err := r.ListInboundOptions(ctx) + if err != nil || len(options) != 1 || options[0].Port != 443 { + t.Fatalf("legacy options=%+v err=%v", options, err) + } + if id, err := r.resolveRemoteID(ctx, "test"); err != nil || id != 7 { + t.Fatalf("legacy ID = %d, err=%v", id, err) + } + if modern.Load() != 1 || legacy.Load() != 1 { + t.Fatalf("catalog requests=%d full list requests=%d, want 1 each", modern.Load(), legacy.Load()) + } + }) + } +} + +func TestRemoteInboundCatalogSurvivesSettingsOnlyPushes(t *testing.T) { + var reads atomic.Int32 + started := make(chan chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + reads.Add(1) + resume := make(chan struct{}) + select { + case started <- resume: + case <-req.Context().Done(): + return + } + select { + case <-resume: + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"warm"},{"id":8,"tag":"cold"}]}`) + case <-req.Context().Done(): + } + case "/panel/api/inbounds/update/7": + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + r.cacheSet("warm", 7) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + id, err := r.resolveRemoteID(ctx, "cold") + if err == nil && id != 8 { + err = fmt.Errorf("cold lookup resolved ID %d, want 8", id) + } + done <- err + }() + + for { + select { + case resume := <-started: + before := &model.Inbound{Tag: "warm", Protocol: model.VLESS, Settings: `{"clients":[]}`} + after := *before + after.Settings = fmt.Sprintf(`{"clients":[{"email":"client-%d@example.test"}]}`, reads.Load()) + err := r.UpdateInbound(ctx, before, &after) + close(resume) + if err != nil { + t.Fatal(err) + } + case err := <-done: + if err != nil || reads.Load() != 1 { + t.Fatalf("lookup during settings-only updates: reads=%d, err=%v", reads.Load(), err) + } + return + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } +} + +func TestRemoteInboundCatalogDoesNotRestoreDeletedAlias(t *testing.T) { + var gets atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog", "/panel/api/inbounds/list": + if gets.Add(1) == 1 { + close(started) + <-release + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"adopted"}]}`) + } else { + fmt.Fprint(w, `{"success":true,"obj":[]}`) + } + case "/panel/api/inbounds/del/7": + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + t.Cleanup(unblock) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ib := &model.Inbound{Tag: "central", Protocol: model.VLESS} + r.AdoptInboundAlias(ib, RemoteInboundOption{Id: 7, Tag: "adopted"}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + options, err := r.ListInboundOptions(ctx) + if err == nil && len(options) != 0 { + err = fmt.Errorf("stale catalog returned: %+v", options) + } + done <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog never started") + } + if err := r.DelInbound(ctx, &model.Inbound{Tag: "adopted"}); err != nil { + t.Fatal(err) + } + unblock() + if err := <-done; err != nil { + t.Fatal(err) + } + if _, ok := r.cacheGetTag(ib.Tag); ok || gets.Load() != 2 { + t.Fatalf("deleted alias still cached or stale read was not retried: gets=%d", gets.Load()) + } +} + +func TestRemoteInboundCatalogRefreshDetectsRecreatedInbound(t *testing.T) { + var remoteID, pushedID atomic.Int32 + remoteID.Store(7) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog": + fmt.Fprintf(w, `{"success":true,"obj":[{"id":%d,"tag":"in-443"}]}`, remoteID.Load()) + case "/panel/api/inbounds/update/7": + pushedID.Store(7) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/update/8": + pushedID.Store(8) + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ib := &model.Inbound{Tag: "in-443", Protocol: model.VLESS, Port: 443} + ctx := context.Background() + if err := r.UpdateInbound(ctx, ib, ib); err != nil || pushedID.Load() != 7 { + t.Fatalf("first update used ID %d, err=%v", pushedID.Load(), err) + } + remoteID.Store(8) + if _, err := r.ListInboundOptions(ctx); err != nil { + t.Fatal(err) + } + if pushed, err := r.ReconcileInbound(ctx, ib, true); err != nil || !pushed || pushedID.Load() != 8 { + t.Fatalf("reconcile after recreation: pushed=%t, ID=%d, err=%v", pushed, pushedID.Load(), err) + } +} + +func TestRemoteInboundCatalogCancelsRPCWhenLastWaiterLeaves(t *testing.T) { + var calls atomic.Int32 + started, canceled := make(chan struct{}), make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if calls.Add(1) == 1 { + close(started) + <-req.Context().Done() + close(canceled) + return + } + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"valid"}]}`) + })) + t.Cleanup(srv.Close) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + ctx, finish := context.WithTimeout(context.Background(), 3*time.Second) + defer finish() + lookup, cancel := context.WithCancel(ctx) + defer cancel() + done := make(chan error, 1) + go func() { + _, err := r.resolveRemoteID(lookup, "valid") + done <- err + }() + select { + case <-started: + case <-ctx.Done(): + t.Fatal("catalog never started") + } + cancel() + if err := <-done; !errors.Is(err, context.Canceled) { + t.Fatalf("lookup error=%v, want canceled", err) + } + select { + case <-canceled: + case <-ctx.Done(): + t.Fatal("abandoned catalog request was not canceled") + } + if id, err := r.resolveRemoteID(ctx, "valid"); err != nil || id != 7 || calls.Load() != 2 { + t.Fatalf("fresh lookup ID=%d err=%v calls=%d", id, err, calls.Load()) + } +} diff --git a/internal/web/runtime/remote_inbound_lookup_test.go b/internal/web/runtime/remote_inbound_lookup_test.go index a0504029b..05441f24f 100644 --- a/internal/web/runtime/remote_inbound_lookup_test.go +++ b/internal/web/runtime/remote_inbound_lookup_test.go @@ -23,11 +23,13 @@ func TestInboundLookupFailureDoesNotAcknowledgeMutation(t *testing.T) { {"unavailable", http.StatusServiceUnavailable, "", "HTTP 503"}, {"application error", http.StatusOK, `{"success":false,"msg":"node database unavailable"}`, "node database unavailable"}, {"invalid catalog", http.StatusOK, `{"success":true,"obj":{"id":4}}`, "decode inbound list"}, + {"missing catalog", http.StatusOK, `{"success":true}`, "decode inbound list"}, + {"invalid row", http.StatusOK, `{"success":true,"obj":[{"id":0,"tag":"in-lookup"}]}`, "decode inbound list"}, } { t.Run(tc.name, func(t *testing.T) { var mutations atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodGet || !strings.HasSuffix(req.URL.Path, "/panel/api/inbounds/list") { + if req.Method != http.MethodGet || !strings.HasSuffix(req.URL.Path, "/panel/api/inbounds/catalog") { mutations.Add(1) _, _ = w.Write([]byte(`{"success":true}`)) return @@ -45,7 +47,7 @@ func TestInboundLookupFailureDoesNotAcknowledgeMutation(t *testing.T) { t.Errorf("UpdateInbound error = %v, want %q", err, tc.want) } if got := mutations.Load(); got != 0 { - t.Errorf("mutation requests after failed lookup = %d, want 0", got) + t.Errorf("mutation or fallback requests after failed lookup = %d, want 0", got) } }) } diff --git a/internal/web/runtime/remote_reset_test.go b/internal/web/runtime/remote_reset_test.go index 27159e3e6..722d29bff 100644 --- a/internal/web/runtime/remote_reset_test.go +++ b/internal/web/runtime/remote_reset_test.go @@ -3,6 +3,7 @@ package runtime import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "slices" @@ -62,7 +63,7 @@ func TestRemoteResetInboundTrafficUnknownTagErrors(t *testing.T) { var resetPosted bool srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") - if req.URL.Path == "/panel/api/inbounds/list" { + if req.URL.Path == "/panel/api/inbounds/catalog" { _, _ = w.Write([]byte(`{"success":true,"msg":"ok","obj":[]}`)) return } @@ -73,8 +74,8 @@ func TestRemoteResetInboundTrafficUnknownTagErrors(t *testing.T) { r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) ib := &model.Inbound{Id: 42, Tag: "n1-in-443"} - if err := r.ResetInboundTraffic(context.Background(), ib); err == nil { - t.Fatal("ResetInboundTraffic error = nil, want unknown-tag error") + if err := r.ResetInboundTraffic(context.Background(), ib); !errors.Is(err, errRemoteInboundNotFound) { + t.Fatalf("ResetInboundTraffic error = %v, want unknown-tag error", err) } if resetPosted { t.Fatal("reset request posted to node despite an unresolved tag") diff --git a/internal/web/service/client_create_reconcile_test.go b/internal/web/service/client_create_reconcile_test.go index 87f435e46..e56e722fc 100644 --- a/internal/web/service/client_create_reconcile_test.go +++ b/internal/web/service/client_create_reconcile_test.go @@ -33,7 +33,7 @@ type groupedCreatePeer struct { func (p *groupedCreatePeer) serve(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch { - case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + case strings.HasSuffix(r.URL.Path, "/inbounds/catalog"), strings.HasSuffix(r.URL.Path, "/inbounds/list"): p.mu.Lock() catalog := make([]runtime.RemoteInboundOption, 0, len(p.tags)) for tag, id := range p.tags { diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 59bc2cabe..03fe9cd14 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -400,6 +400,17 @@ type InboundOption struct { ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"` } +// GetInboundCatalog selects the fields needed for remote inbound lookup and reconciliation. +func (s *InboundService) GetInboundCatalog(userID int) ([]runtime.RemoteInboundOption, error) { + catalog := make([]runtime.RemoteInboundOption, 0) + err := database.GetDB().Model(&model.Inbound{}). + Select("id", "tag", "remark", "listen", "protocol", "port"). + Where("user_id = ?", userID). + Order("id ASC"). + Find(&catalog).Error + return catalog, err +} + func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) { db := database.GetDB() var rows []struct { diff --git a/internal/web/service/inbound_node_reconcile_test.go b/internal/web/service/inbound_node_reconcile_test.go index 2075f1fc1..0e62543da 100644 --- a/internal/web/service/inbound_node_reconcile_test.go +++ b/internal/web/service/inbound_node_reconcile_test.go @@ -12,6 +12,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "github.com/mhsanaei/3x-ui/v3/internal/database" @@ -263,7 +264,7 @@ func TestReconcileNode_AdoptsCompatibleOriginInboundWithoutRemoteMutation(t *tes _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "msg": "", "obj": obj}) } mux := http.NewServeMux() - mux.HandleFunc("/panel/api/inbounds/list", func(w http.ResponseWriter, _ *http.Request) { + mux.HandleFunc("/panel/api/inbounds/catalog", func(w http.ResponseWriter, _ *http.Request) { writeOK(w, []map[string]any{{"id": 41, "tag": "already-deployed", "listen": "", "port": 8443, "protocol": "vless"}}) }) mux.HandleFunc("/panel/api/inbounds/", func(w http.ResponseWriter, _ *http.Request) { @@ -301,6 +302,45 @@ func TestReconcileNode_AdoptsCompatibleOriginInboundWithoutRemoteMutation(t *tes } } +func TestReconcileNodeUsesOneCatalogForUpdatesCreatesAndDeletes(t *testing.T) { + setupConflictDB(t) + var reads, fullLists, adds, updates, deletes atomic.Int32 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/panel/api/inbounds/catalog", "/panel/api/inbounds/list": + if req.URL.Path == "/panel/api/inbounds/catalog" { + reads.Add(1) + } else { + fullLists.Add(1) + } + fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"existing"},{"id":6,"tag":"removed"}]}`) + case "/panel/api/inbounds/add": + adds.Add(1) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/update/7": + updates.Add(1) + fmt.Fprint(w, `{"success":true}`) + case "/panel/api/inbounds/del/6": + deletes.Add(1) + fmt.Fprint(w, `{"success":true}`) + default: + http.NotFound(w, req) + } + })) + t.Cleanup(ts.Close) + node := reconcileTestNode(t, ts, "catalog-node", "all", nil) + for i, tag := range []string{"existing", "missing-a", "missing-b"} { + seedInboundConflictNode(t, tag, "", 12000+i, model.VLESS, `{"network":"tcp"}`, `{"clients":[]}`, &node.Id) + } + svc := InboundService{} + if err := svc.ReconcileNode(context.Background(), runtime.NewRemote(node, nil), node); err != nil { + t.Fatal(err) + } + if reads.Load() != 1 || fullLists.Load() != 0 || adds.Load() != 2 || updates.Load() != 1 || deletes.Load() != 1 { + t.Fatalf("catalog=%d full list=%d adds=%d updates=%d deletes=%d", reads.Load(), fullLists.Load(), adds.Load(), updates.Load(), deletes.Load()) + } +} + func TestReconcileNode_AmbiguousCompatibleInboundsAreNotSwept(t *testing.T) { setupConflictDB(t) diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go index aaf21b930..aaf1655b4 100644 --- a/internal/web/service/node_http_fake_test.go +++ b/internal/web/service/node_http_fake_test.go @@ -27,7 +27,7 @@ type fakeNodeHTTP struct { pendingClientAcks int clientAdds []ClientCreatePayload clientAddEvents chan ClientCreatePayload - // hold makes every non-list request block until the master gives up. + // hold makes requests outside inbound discovery block until the master gives up. hold bool release chan struct{} } @@ -43,7 +43,7 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { f.mu.Lock() w.Header().Set(wirecodec.CapsHeader, f.caps) f.mu.Unlock() - if strings.HasSuffix(r.URL.Path, "/inbounds/list") { + if strings.HasSuffix(r.URL.Path, "/inbounds/catalog") || strings.HasSuffix(r.URL.Path, "/inbounds/list") { f.mu.Lock() f.hits["list"]++ type ent struct { diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index 2633d92c0..04362843f 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -97,7 +97,7 @@ func run(root, outDir string) error { }, { Path: resolveRel(root, "internal/web/runtime"), - StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1"), + StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1", "RemoteInboundOption"), }, { Path: resolveRel(root, "internal/web/service"),