inbound_mtproto_txfail_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package service
  2. import (
  3. "errors"
  4. "testing"
  5. "gorm.io/gorm"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  9. )
  10. // A local MTProto inbound edit must not push to the managed sidecar from inside
  11. // the serialized write transaction: that blocks the single traffic-writer
  12. // goroutine on process/network I/O, and a later step failing the transaction
  13. // would leave the sidecar ahead of the rolled-back database. The push belongs in
  14. // the post-commit hook, exactly as the xray branch already does it.
  15. func TestUpdateInboundLocalMtprotoDefersPushUntilCommit(t *testing.T) {
  16. setupConflictDB(t)
  17. mgr := runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }})
  18. fake := &fakeNodeRuntime{}
  19. mgr.SetLocalRuntimeOverride(fake)
  20. runtime.SetManager(mgr)
  21. t.Cleanup(func() { runtime.SetManager(nil) })
  22. seedInboundConflict(t, "mt-txfail", "", 46150, model.MTProto, "",
  23. `{"clients":[{"email":"mtx","secret":"`+mtprotoTestSecretA+`","enable":true}]}`)
  24. seeded := loadInboundByTag(t, "mt-txfail")
  25. seedClientTraffic(t, seeded.Id, "mtx", true)
  26. db := database.GetDB()
  27. const cbName = "b1-05:fail-inbound-update"
  28. if err := db.Callback().Update().After("gorm:update").Register(cbName, func(tx *gorm.DB) {
  29. if tx.Statement != nil && tx.Statement.Table == "inbounds" {
  30. tx.AddError(errors.New("injected transaction failure"))
  31. }
  32. }); err != nil {
  33. t.Fatalf("register callback: %v", err)
  34. }
  35. t.Cleanup(func() { _ = db.Callback().Update().Remove(cbName) })
  36. update := *loadInboundByTag(t, "mt-txfail")
  37. update.Remark = "edited"
  38. if _, _, err := (&InboundService{}).UpdateInbound(&update); err == nil {
  39. t.Fatal("UpdateInbound: expected the injected transaction failure")
  40. }
  41. if n := fake.updateInbound.Load(); n != 0 {
  42. t.Fatalf("the MTProto sidecar push ran %d time(s) inside the failed transaction; it must be deferred until the commit succeeds", n)
  43. }
  44. }