/
subscriptions.go
100 lines (83 loc) · 1.85 KB
/
subscriptions.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
package esdb
import (
"context"
"fmt"
"sync"
"sync/atomic"
api "github.com/EventStore/EventStore-Client-Go/v2/protos/streams"
)
type request struct {
channel chan *SubscriptionEvent
}
type Subscription struct {
client *Client
id string
inner api.Streams_ReadClient
cancel context.CancelFunc
once *sync.Once
closed *int32
}
func NewSubscription(client *Client, cancel context.CancelFunc, inner api.Streams_ReadClient, id string) *Subscription {
once := new(sync.Once)
closed := new(int32)
atomic.StoreInt32(closed, 0)
return &Subscription{
client: client,
id: id,
inner: inner,
once: once,
closed: closed,
cancel: cancel,
}
}
func (sub *Subscription) Id() string {
return sub.id
}
func (sub *Subscription) Close() error {
sub.once.Do(func() {
atomic.StoreInt32(sub.closed, 1)
sub.cancel()
})
return nil
}
func (sub *Subscription) Recv() *SubscriptionEvent {
if atomic.LoadInt32(sub.closed) != 0 {
return &SubscriptionEvent{
SubscriptionDropped: &SubscriptionDropped{
Error: fmt.Errorf("subscription has been dropped"),
},
}
}
result, err := sub.inner.Recv()
if err != nil {
sub.client.grpcClient.logger.error("subscription has dropped. Reason: %v", err)
dropped := SubscriptionDropped{
Error: err,
}
atomic.StoreInt32(sub.closed, 1)
return &SubscriptionEvent{
SubscriptionDropped: &dropped,
}
}
switch result.Content.(type) {
case *api.ReadResp_Checkpoint_:
{
checkpoint := result.GetCheckpoint()
position := Position{
Commit: checkpoint.CommitPosition,
Prepare: checkpoint.PreparePosition,
}
return &SubscriptionEvent{
CheckPointReached: &position,
}
}
case *api.ReadResp_Event:
{
resolvedEvent := getResolvedEventFromProto(result.GetEvent())
return &SubscriptionEvent{
EventAppeared: &resolvedEvent,
}
}
}
panic("unreachable code")
}