-
Notifications
You must be signed in to change notification settings - Fork 1
/
dtc.go
108 lines (89 loc) · 1.97 KB
/
dtc.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
package sqle
import (
"context"
"database/sql"
)
// DTC Distributed Transaction Coordinator
type DTC struct {
ctx context.Context
opts *sql.TxOptions
sessions []*session
}
// session represents a transaction session.
type session struct {
committed bool
client *Client
tx *Tx
exec []func(context.Context, Connector) error
revert []func(context.Context, Connector) error
}
// NewDTC creates a new instance of DTC.
func NewDTC(ctx context.Context, opts *sql.TxOptions) *DTC {
return &DTC{
ctx: ctx,
opts: opts,
}
}
// Prepare adds a new transaction session to the DTC.
func (d *DTC) Prepare(client *Client, exec func(ctx context.Context, conn Connector) error, revert func(ctx context.Context, conn Connector) error) {
for _, s := range d.sessions {
if s.client == client {
s.exec = append(s.exec, exec)
s.revert = append(s.revert, revert)
return
}
}
s := &session{
committed: false,
client: client,
exec: []func(ctx context.Context, c Connector) error{
exec,
},
revert: []func(ctx context.Context, c Connector) error{
revert,
},
}
d.sessions = append(d.sessions, s)
}
// Commit commits all the prepared transactions in the DTC.
func (d *DTC) Commit() error {
for _, s := range d.sessions {
tx, err := s.client.BeginTx(d.ctx, d.opts)
if err != nil {
return err
}
s.tx = tx
for _, exec := range s.exec {
err = exec(d.ctx, tx)
if err != nil {
return err
}
}
}
for _, s := range d.sessions {
err := s.tx.Commit()
if err != nil {
return err
}
s.committed = true
}
return nil
}
// Rollback rolls back all the prepared transactions in the DTC.
func (d *DTC) Rollback() []error {
var errs []error
for _, s := range d.sessions {
if s.committed {
for _, revert := range s.revert {
if err := revert(d.ctx, s.client); err != nil {
errs = append(errs, err)
}
}
} else {
if err := s.tx.Rollback(); err != nil {
errs = append(errs, err)
}
}
}
return errs
}