-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathenforcer_transactional.go
More file actions
176 lines (152 loc) · 5.44 KB
/
enforcer_transactional.go
File metadata and controls
176 lines (152 loc) · 5.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright 2025 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package casbin
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/casbin/casbin/v3/persist"
"github.com/google/uuid"
)
// TransactionalEnforcer extends Enforcer with transaction support.
// It provides atomic policy operations through transactions.
type TransactionalEnforcer struct {
*Enforcer // Embedded enforcer for all standard functionality
activeTransactions sync.Map // Stores active transactions.
modelVersion int64 // Model version number for optimistic locking.
commitLock sync.Mutex // Protects commit and rollback operations.
}
// NewTransactionalEnforcer creates a new TransactionalEnforcer.
// It accepts the same parameters as NewEnforcer.
func NewTransactionalEnforcer(params ...interface{}) (*TransactionalEnforcer, error) {
enforcer, err := NewEnforcer(params...)
if err != nil {
return nil, err
}
return &TransactionalEnforcer{
Enforcer: enforcer,
}, nil
}
// BeginTransaction starts a new transaction.
// Returns an error if a transaction is already in progress or if the adapter doesn't support transactions.
func (te *TransactionalEnforcer) BeginTransaction(ctx context.Context) (*Transaction, error) {
// Check if adapter supports transactions.
txAdapter, ok := te.adapter.(persist.TransactionalAdapter)
if !ok {
return nil, errors.New("adapter does not support transactions")
}
// Start database transaction.
txContext, err := txAdapter.BeginTransaction(ctx)
if err != nil {
return nil, err
}
// Create transaction buffer with current model snapshot.
buffer := NewTransactionBuffer(te.model)
tx := &Transaction{
id: uuid.New().String(),
enforcer: te,
buffer: buffer,
txContext: txContext,
ctx: ctx,
baseVersion: atomic.LoadInt64(&te.modelVersion),
startTime: time.Now(),
}
te.activeTransactions.Store(tx.id, tx)
return tx, nil
}
// GetTransaction returns a transaction by its ID, or nil if not found.
func (te *TransactionalEnforcer) GetTransaction(id string) *Transaction {
if tx, ok := te.activeTransactions.Load(id); ok {
return tx.(*Transaction)
}
return nil
}
// IsTransactionActive returns true if the transaction with the given ID is active.
func (te *TransactionalEnforcer) IsTransactionActive(id string) bool {
if tx := te.GetTransaction(id); tx != nil {
return tx.IsActive()
}
return false
}
// WithTransaction executes a function within a transaction.
// If the function returns an error, the transaction is rolled back.
// Otherwise, it's committed automatically.
func (te *TransactionalEnforcer) WithTransaction(ctx context.Context, fn func(*Transaction) error) error {
tx, err := te.BeginTransaction(ctx)
if err != nil {
return err
}
defer func() {
if r := recover(); r != nil {
_ = tx.Rollback()
panic(r)
}
}()
err = fn(tx)
if err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}
// BeginTransactionWithContext starts a new Casbin transaction using an existing TransactionContext.
// This enables Casbin operations to participate in an externally-managed database transaction
// (e.g. a GORM transaction). Casbin will apply buffered policy operations through
// txContext.GetAdapter() but will NOT call txContext.Commit() or txContext.Rollback() —
// the caller is solely responsible for committing or rolling back the external transaction.
func (te *TransactionalEnforcer) BeginTransactionWithContext(ctx context.Context, txContext persist.TransactionContext) (*Transaction, error) {
buffer := NewTransactionBuffer(te.model)
tx := &Transaction{
id: uuid.New().String(),
enforcer: te,
buffer: buffer,
txContext: txContext,
ctx: ctx,
baseVersion: atomic.LoadInt64(&te.modelVersion),
startTime: time.Now(),
isExternal: true,
}
te.activeTransactions.Store(tx.id, tx)
return tx, nil
}
// WithExternalTransaction executes fn within the scope of an existing, externally-managed
// database transaction. txContext must wrap the external transaction and provide a
// Casbin adapter (via GetAdapter) that writes through it.
//
// On success, Casbin applies the buffered policy operations to the database using the
// external transaction and updates the in-memory model. The database transaction itself
// is NOT committed by Casbin — the caller must commit (or roll back) it.
//
// On failure (fn returns an error or a panic occurs), Casbin does NOT roll back the
// external transaction; the caller is responsible for that as well.
func (te *TransactionalEnforcer) WithExternalTransaction(ctx context.Context, txContext persist.TransactionContext, fn func(*Transaction) error) error {
tx, err := te.BeginTransactionWithContext(ctx, txContext)
if err != nil {
return err
}
defer func() {
if r := recover(); r != nil {
_ = tx.Rollback()
panic(r)
}
}()
err = fn(tx)
if err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}