-
Notifications
You must be signed in to change notification settings - Fork 0
/
coordinator.go
57 lines (51 loc) · 1.49 KB
/
coordinator.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
package gosql2pc
import (
"context"
"errors"
"fmt"
)
// ErrCommitFailed is returned when a participant fails to commit
var ErrCommitFailed = errors.New("commit failed")
// Params is the input for Do
type Params struct {
// LogFn is a function that can be used for logging errors. Leave empty for no logging
LogFn func(msg string, args ...any)
Participants []Participant
}
// Do runs the distributed transaction
func Do(ctx context.Context, params Params) error {
log := getLog(params)
defer func() {
for i := range params.Participants {
if err := params.Participants[i].rollback(); err != nil {
log("rollback failed: %s", err)
}
}
}()
// prepare all participants
// TODO: this potentially could be done in parallel
for i := range params.Participants {
if err := params.Participants[i].prepare(ctx); err != nil {
return err
}
}
// commit all participants
// TODO: this potentially could be done in parallel
for i := range params.Participants {
if err := params.Participants[i].commit(); err != nil {
log("commit failed: %s", err)
// since we have committed this participant, we need to rollback all other participants
// this may leave an inconsistent state
return fmt.Errorf("%w: %s", ErrCommitFailed, err.Error())
}
}
return nil
}
var defaultLog func(msg string, args ...any) = func(msg string, args ...any) {}
var defaultPrefix = "gosql2pc-"
func getLog(p Params) func(msg string, args ...any) {
if p.LogFn != nil {
return p.LogFn
}
return defaultLog
}