-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwrite.go
92 lines (75 loc) · 1.94 KB
/
write.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
package gomessagestore
import (
"context"
"fmt"
"regexp"
)
type writer struct {
atPosition *int64
}
// WriteOption provides optional arguments to the Write function
type WriteOption func(w *writer)
func checkWriteOptions(opts ...WriteOption) *writer {
w := &writer{}
for _, option := range opts {
option(w)
}
return w
}
// Write writes a Message to the message store.
func (ms *msgStore) Write(ctx context.Context, message Message, opts ...WriteOption) error {
envelope, err := Message.ToEnvelope(message)
if err != nil {
ms.
log.
WithError(err).
Error("Write: Validation Error")
return err
}
errMsg := `ERROR: Wrong expected version: .* \(SQLSTATE P0001\)`
writeOptions := checkWriteOptions(opts...)
if writeOptions.atPosition != nil {
err = ms.repo.WriteMessageWithExpectedPosition(ctx, envelope, *writeOptions.atPosition)
if err != nil {
if matched, _ := regexp.Match(errMsg, []byte(err.Error())); matched {
err = ErrExpectedVersionFailed
}
}
} else {
err = ms.repo.WriteMessage(ctx, envelope)
}
if err != nil {
ms.
log.
WithError(err).
Error("Write: Error writing message")
return err
}
return nil
}
// AtPosition allows for writing messages using an expected position
func AtPosition(position int64) WriteOption {
return func(w *writer) {
w.atPosition = &position
}
}
// AtPositionMatcher is a gomock.Matcher interface that matches an AtPosition function
type AtPositionMatcher struct {
Position int64
}
// String gives us a representation of our AtPositionMatcher
func (a AtPositionMatcher) String() string {
return fmt.Sprintf("%d", a.Position)
}
// Matches checks agains a AtPosition/gms.WriteOption function
func (a AtPositionMatcher) Matches(unknown interface{}) bool {
if writeOption, ok := unknown.(WriteOption); ok {
w := &writer{} // nil atPosition to start
writeOption(w)
if w.atPosition == nil {
return false
}
return *w.atPosition == a.Position
}
return false
}