Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: initialize transactionMu correctly and ensure the transitivity of transactionMu #236

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ func NewAdapterByDBUseTableName(db *gorm.DB, prefix string, tableName string) (*
a := &Adapter{
tablePrefix: prefix,
tableName: tableName,
transactionMu : &sync.Mutex{},
}

a.db = db.Scopes(a.casbinRuleTable()).Session(&gorm.Session{Context: db.Statement.Context})
Expand Down Expand Up @@ -262,6 +263,7 @@ func NewFilteredAdapterByDB(db *gorm.DB, prefix string, tableName string) (*Adap
tablePrefix: prefix,
tableName: tableName,
isFiltered: true,
transactionMu : &sync.Mutex{},
}
adapter.db = db.Scopes(adapter.casbinRuleTable()).Session(&gorm.Session{Context: db.Statement.Context})

Expand Down Expand Up @@ -690,31 +692,22 @@ func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error

// Transaction perform a set of operations within a transaction
func (a *Adapter) Transaction(e casbin.IEnforcer, fc func(casbin.IEnforcer) error, opts ...*sql.TxOptions) error {
// ensure the transactionMu is initialized
if a.transactionMu == nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to keep the nil check and return error while transactionMu is nil.

for a.muInitialize.CompareAndSwap(false, true) {
kingzytgit marked this conversation as resolved.
Show resolved Hide resolved
if a.transactionMu == nil {
a.transactionMu = &sync.Mutex{}
}
a.muInitialize.Store(false)
}
}
// lock the transactionMu to ensure the transaction is thread-safe
a.transactionMu.Lock()
defer a.transactionMu.Unlock()
var err error
oriAdapter := a.db
// reload policy from database to sync with the transaction
defer func() {
e.SetAdapter(&Adapter{db: oriAdapter})
e.SetAdapter(&Adapter{db: oriAdapter, transactionMu: a.transactionMu})
err = e.LoadPolicy()
if err != nil {
panic(err)
}
}()
copyDB := *a.db
tx := copyDB.Begin(opts...)
b := &Adapter{db: tx}
b := &Adapter{db: tx, transactionMu: a.transactionMu}
// copy enforcer to set the new adapter with transaction tx
copyEnforcer := e
copyEnforcer.SetAdapter(b)
Expand Down
Loading