File: transaction_buffer.go

package info (click to toggle)
golang-github-casbin-casbin 2.127.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,540 kB
  • sloc: makefile: 14
file content (131 lines) | stat: -rw-r--r-- 4,392 bytes parent folder | download
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
// 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 (
	"sync"

	"github.com/casbin/casbin/v2/model"
	"github.com/casbin/casbin/v2/persist"
)

// TransactionBuffer holds all policy changes made within a transaction.
// It maintains a list of operations and a snapshot of the model state
// at the beginning of the transaction.
type TransactionBuffer struct {
	operations    []persist.PolicyOperation // Buffered operations
	modelSnapshot model.Model               // Model state at transaction start
	mutex         sync.RWMutex              // Protects concurrent access
}

// NewTransactionBuffer creates a new transaction buffer with a model snapshot.
// The snapshot represents the state of the model at the beginning of the transaction.
func NewTransactionBuffer(baseModel model.Model) *TransactionBuffer {
	return &TransactionBuffer{
		operations:    make([]persist.PolicyOperation, 0),
		modelSnapshot: baseModel.Copy(),
	}
}

// AddOperation adds a policy operation to the buffer.
// This operation will be applied when the transaction is committed.
func (tb *TransactionBuffer) AddOperation(op persist.PolicyOperation) {
	tb.mutex.Lock()
	defer tb.mutex.Unlock()
	tb.operations = append(tb.operations, op)
}

// GetOperations returns all buffered operations.
// Returns a copy to prevent external modifications.
func (tb *TransactionBuffer) GetOperations() []persist.PolicyOperation {
	tb.mutex.RLock()
	defer tb.mutex.RUnlock()

	// Return a copy to prevent external modifications.
	result := make([]persist.PolicyOperation, len(tb.operations))
	copy(result, tb.operations)
	return result
}

// Clear removes all buffered operations.
// This is typically called after a successful commit or rollback.
func (tb *TransactionBuffer) Clear() {
	tb.mutex.Lock()
	defer tb.mutex.Unlock()
	tb.operations = tb.operations[:0]
}

// GetModelSnapshot returns the model snapshot taken at transaction start.
// This represents the original state before any transaction operations.
func (tb *TransactionBuffer) GetModelSnapshot() model.Model {
	tb.mutex.RLock()
	defer tb.mutex.RUnlock()
	return tb.modelSnapshot.Copy()
}

// ApplyOperationsToModel applies all buffered operations to a model and returns the result.
// This simulates what the model would look like after all operations are applied.
// It's used for validation and preview purposes within the transaction.
func (tb *TransactionBuffer) ApplyOperationsToModel(baseModel model.Model) (model.Model, error) {
	tb.mutex.RLock()
	defer tb.mutex.RUnlock()

	resultModel := baseModel.Copy()

	for _, op := range tb.operations {
		switch op.Type {
		case persist.OperationAdd:
			for _, rule := range op.Rules {
				if err := resultModel.AddPolicy(op.Section, op.PolicyType, rule); err != nil {
					return nil, err
				}
			}
		case persist.OperationRemove:
			for _, rule := range op.Rules {
				if _, err := resultModel.RemovePolicy(op.Section, op.PolicyType, rule); err != nil {
					return nil, err
				}
			}
		case persist.OperationUpdate:
			// For update operations, remove old rules and add new ones.
			for i, oldRule := range op.OldRules {
				if i < len(op.Rules) {
					if _, err := resultModel.RemovePolicy(op.Section, op.PolicyType, oldRule); err != nil {
						return nil, err
					}
					if err := resultModel.AddPolicy(op.Section, op.PolicyType, op.Rules[i]); err != nil {
						return nil, err
					}
				}
			}
		}
	}

	return resultModel, nil
}

// HasOperations returns true if there are any buffered operations.
func (tb *TransactionBuffer) HasOperations() bool {
	tb.mutex.RLock()
	defer tb.mutex.RUnlock()
	return len(tb.operations) > 0
}

// OperationCount returns the number of buffered operations.
func (tb *TransactionBuffer) OperationCount() int {
	tb.mutex.RLock()
	defer tb.mutex.RUnlock()
	return len(tb.operations)
}