This repository was archived by the owner on May 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction_writer.go
77 lines (62 loc) · 1.61 KB
/
transaction_writer.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
package rabbitmq
import (
"log"
"sync"
"github.com/smartystreets/messaging/v2"
)
type TransactionWriter struct {
mutex *sync.Mutex
controller Controller
channel Channel
closed bool
}
func transactionWriter(controller Controller) *TransactionWriter {
return &TransactionWriter{
mutex: &sync.Mutex{},
controller: controller,
}
}
func (this *TransactionWriter) Write(message messaging.Dispatch) error {
if !this.ensureChannel() {
return messaging.ErrWriterClosed
}
// FUTURE: if error on publish, don't publish anything else
// until we reset the channel during commit
// opening a new channel is what marks it as able to continue
dispatch := toAMQPDispatch(message, utcNow())
return this.channel.PublishMessage(message.Destination, message.Partition, dispatch)
}
func (this *TransactionWriter) Commit() error {
if this.channel == nil {
return nil
}
err := this.channel.CommitTransaction()
if err == nil {
return nil
}
log.Println("[WARN] Transaction failed, closing channel: [", err, "]")
_ = this.channel.Close()
this.channel = nil
return err
}
func (this *TransactionWriter) Close() {
this.mutex.Lock()
this.closed = true
this.mutex.Unlock()
}
func (this *TransactionWriter) ensureChannel() bool {
if this.channel != nil {
return true
}
this.mutex.Lock()
defer this.mutex.Unlock()
this.channel = this.controller.openChannel(this.isActive)
if this.channel == nil {
return false
}
_ = this.channel.ConfigureChannelAsTransactional()
return true
}
func (this *TransactionWriter) isActive() bool {
return !this.closed // must be called from within the safety of a mutex
}