Skip to content

Commit

Permalink
feat: limit transaction concurrency (#226)
Browse files Browse the repository at this point in the history
  • Loading branch information
sylarXu authored Feb 19, 2024
1 parent b48be9f commit 1f2965a
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"fmt"
"runtime"
"strings"
"sync/atomic"

"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
Expand Down Expand Up @@ -81,6 +82,7 @@ type Adapter struct {
dbSpecified bool
db *gorm.DB
isFiltered bool
isTransaction atomic.Bool
}

// finalizer is the destructor for Adapter.
Expand Down Expand Up @@ -664,16 +666,23 @@ func (a *Adapter) AddPolicies(sec string, ptype string, rules [][]string) error
}

// Transaction perform a set of operations within a transaction
// will return error while operation failed and transaction in concurrent environment
func (a *Adapter) Transaction(e casbin.IEnforcer, fc func(casbin.IEnforcer) error, opts ...*sql.TxOptions) error {
var err error
oriAdapter := a.db

// fail fast while transaction in concurrent environment
if !a.isTransaction.CompareAndSwap(false, true) {
return errors.New("cannot start a transaction within another transaction")
}
// reload policy from database to sync with the transaction
defer func() {
e.SetAdapter(&Adapter{db: oriAdapter})
err = e.LoadPolicy()
if err != nil {
panic(err)
}
a.isTransaction.Store(false)
}()
copyDB := *a.db
tx := copyDB.Begin(opts...)
Expand Down

0 comments on commit 1f2965a

Please sign in to comment.