-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx.go
364 lines (324 loc) · 7.37 KB
/
tx.go
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package edb
import (
"fmt"
"runtime/debug"
"sync/atomic"
"time"
"go.etcd.io/bbolt"
)
var (
ReaderCount atomic.Int64
WriterCount atomic.Int64
)
type Txish interface {
DBTx() *Tx
}
type Tx struct {
db *DB
btx *bbolt.Tx
managed bool
closed bool
startTime time.Time
stack []byte
verbosity int
written bool
commitDespiteErr bool
reindexing bool
memo map[string]any
indexKeyBufs [][]byte
valueBufs [][]byte
indexValueBufs [][]byte
changeHandler func(tx *Tx, chg *Change)
changeOptions map[*Table]ChangeFlags
}
func (db *DB) newTx(btx *bbolt.Tx, managed bool, memo map[string]any, stack []byte) *Tx {
db.lastSize.Store(btx.Size())
if btx.Writable() {
WriterCount.Add(1)
} else {
ReaderCount.Add(1)
}
if debugTrackTxns && stack == nil {
stack = debug.Stack()
}
tx := &Tx{
db: db,
btx: btx,
managed: managed,
memo: memo,
startTime: time.Now(),
stack: stack,
}
if db.verbose {
tx.verbosity = 1
}
if debugTrackTxns {
db.addTx(tx)
}
return tx
}
// DBTx implements Txish
func (tx *Tx) DBTx() *Tx {
return tx
}
func (tx *Tx) DB() *DB {
return tx.db
}
func (tx *Tx) isVerboseLoggingEnabled() bool {
return tx.verbosity > 0
}
func (tx *Tx) BeginVerbose() {
tx.verbosity++
}
func (tx *Tx) EndVerbose() {
tx.verbosity--
}
func (tx *Tx) Schema() *Schema {
return tx.db.schema
}
func (tx *Tx) OnChange(opts map[*Table]ChangeFlags, f func(tx *Tx, chg *Change)) {
tx.changeOptions = opts
tx.changeHandler = f
}
// Tx currently implements Check-Mutate phases for writable transactions:
//
// Phase 1, Check: before any modifications are made. Runs inside bdb.Batch.
// Returning an error won't cause the entire batch to fail.
//
// Phase 2, Mutate: from the first mutation. Runs inside bdb.Batch.
// The entire transaction will be retried in case of error.
//
// TODO: split Mutate phase into Mutate and Post-Mutate phases:
//
// Phase 1, Check (initial phase): inside bdb.Batch, error does not fail batch.
//
// Phase 2, Mutate (initiated by any mutation call): inside bdb.Batch,
// error fails batch.
//
// Phase 3, Read (initiated by explicit call like Commit): mutations committed,
// outside bdb.Batch, a new read-only tx is opened on demand.
//
// Check-Mutate-Read would allow to avoid holding the batch during rendering.
//
// A read-only transaction would be a natural extension of Check-Mutate-Read
// with Check and Mutate phases skipped.
func (db *DB) Tx(writable bool, f func(tx *Tx) error) error {
if writable {
var funcErr error
var tx *Tx
// var calls int
var memo map[string]any
// debug.PrintStack()
// log.Printf("Tx.BATCH.BEGIN")
pending := true
db.PendingWriterCount.Add(1)
var stack []byte
if debugTrackTxns {
stack = debug.Stack()
}
err := db.bdb.Batch(func(btx *bbolt.Tx) error {
if pending {
pending = false
db.PendingWriterCount.Add(-1)
}
if funcErr != nil {
// don't retry failed transactions
return funcErr
}
// calls++
// if calls > 1 {
// log.Printf("Tx.REPEAT: calls = %d, memo = %v, prev err = %v", calls, memo, funcErr)
// } else {
// log.Printf("Tx.START")
// }
tx = db.newTx(btx, true, memo, stack)
defer tx.Close()
funcErr = safelyCall(f, tx)
memo = tx.memo
// log.Printf("Tx.END: calls = %d, memo = %v, w = %v, cde = %v, err = %v", calls, memo, tx.written, tx.commitDespiteErr, funcErr)
if funcErr != nil && (!tx.written || tx.commitDespiteErr) {
return nil
} else {
return funcErr
}
})
// log.Printf("Tx.BATCH.END")
tx.Close()
if err == nil && funcErr != nil {
err = funcErr
}
return err
} else {
return db.bdb.View(func(btx *bbolt.Tx) error {
tx := db.newTx(btx, true, nil, nil)
defer tx.Close()
return f(tx)
})
}
}
type panicked struct {
reason interface{}
stack string
}
func (p panicked) Error() string {
return fmt.Sprintf("panic: %v\n\n%s", p.reason, p.stack)
}
func safelyCall(fn func(*Tx) error, tx *Tx) (err error) {
defer func() {
if p := recover(); p != nil {
err = panicked{p, string(debug.Stack())}
}
}()
return fn(tx)
}
func (db *DB) BeginRead() *Tx {
btx, err := db.bdb.Begin(false)
if err != nil {
panic(fmt.Errorf("failed to start reading: %w", err))
}
return db.newTx(btx, false, nil, nil)
}
func (db *DB) Read(f func(tx *Tx)) {
tx := db.BeginRead()
defer tx.Close()
f(tx)
}
func (db *DB) ReadErr(f func(tx *Tx) error) error {
tx := db.BeginRead()
defer tx.Close()
return f(tx)
}
func (db *DB) Write(f func(tx *Tx)) {
tx := db.BeginUpdate()
defer tx.Close()
f(tx)
err := tx.Commit()
if err != nil {
panic(fmt.Errorf("commit: %w", err))
}
}
func (db *DB) BeginUpdate() *Tx {
btx, err := db.bdb.Begin(true)
if err != nil {
panic(fmt.Errorf("db.Begin(true) failed: %w", err))
}
return db.newTx(btx, false, nil, nil)
}
func (tx *Tx) IsWritable() bool {
return tx.btx.Writable()
}
func (tx *Tx) CommitDespiteError() {
tx.commitDespiteErr = true
}
func (tx *Tx) markWritten() {
tx.written = true
}
func (tx *Tx) prepareToRead() {
if tx.btx == nil {
}
}
func (tx *Tx) addValueBuf(buf []byte) {
if tx.valueBufs == nil {
tx.valueBufs = arrayOfBytesPool.Get().([][]byte)
}
tx.valueBufs = append(tx.valueBufs, buf)
}
func (tx *Tx) addIndexValueBuf(buf []byte) {
if tx.indexValueBufs == nil {
tx.indexValueBufs = arrayOfBytesPool.Get().([][]byte)
}
tx.indexValueBufs = append(tx.indexValueBufs, buf)
}
func (tx *Tx) addIndexKeyBuf(buf []byte) {
if tx.indexKeyBufs == nil {
tx.indexKeyBufs = arrayOfBytesPool.Get().([][]byte)
}
tx.indexKeyBufs = append(tx.indexKeyBufs, buf)
}
func (tx *Tx) Close() {
if tx.closed {
return
}
tx.closed = true
if debugTrackTxns {
tx.db.removeTx(tx)
}
if tx.btx.Writable() {
WriterCount.Add(-1)
tx.db.WriteCount.Add(1)
} else {
ReaderCount.Add(-1)
tx.db.ReadCount.Add(1)
}
if !tx.managed {
// The only error Rollback returns is ErrTxClosed, and it just signals that
// we've ran Commit (which is the normal flow).
err := tx.btx.Rollback()
if err != nil && err != bbolt.ErrTxClosed {
panic(err) // not expected to happen unless Bolt API changes
}
}
tx.release()
}
func (tx *Tx) release() {
if true {
return
}
if tx.valueBufs != nil {
for i, buf := range tx.valueBufs {
valueBytesPool.Put(buf[:0])
tx.valueBufs[i] = nil
}
arrayOfBytesPool.Put(tx.valueBufs[:0])
tx.valueBufs = nil
}
if tx.indexValueBufs != nil {
for i, buf := range tx.indexValueBufs {
indexValueBytesPool.Put(buf[:0])
tx.indexValueBufs[i] = nil
}
arrayOfBytesPool.Put(tx.indexValueBufs[:0])
tx.indexValueBufs = nil
}
if tx.indexKeyBufs != nil {
for i, buf := range tx.indexKeyBufs {
keyBytesPool.Put(buf[:0])
tx.indexKeyBufs[i] = nil
}
arrayOfBytesPool.Put(tx.indexKeyBufs[:0])
tx.indexKeyBufs = nil
}
}
func (tx *Tx) Commit() error {
return tx.btx.Commit()
}
func (tx *Tx) GetMemo(key string) (any, bool) {
v, found := tx.memo[key]
return v, found
}
func (tx *Tx) Memo(key string, f func() (any, error)) (any, error) {
v, found := tx.memo[key]
if found {
if e, ok := v.(error); ok {
return nil, e
}
return v, nil
}
if tx.memo == nil {
tx.memo = make(map[string]any)
}
v, err := f()
if err != nil {
tx.memo[key] = err
} else {
tx.memo[key] = v
}
return v, err
}
func Memo[T any](txish Txish, key string, f func() (T, error)) (T, error) {
tx := txish.DBTx()
v, err := tx.Memo(key, func() (any, error) {
return f()
})
return v.(T), err
}