From b2d7a9bb08d04d158a6d6bbe5e2dafd88f23fe85 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 11:40:21 +0330 Subject: [PATCH 1/5] 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 2/5] 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 3/5] 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 4/5] 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 5/5] 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",