-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathstream_writer.go
More file actions
240 lines (215 loc) · 5.44 KB
/
Copy pathstream_writer.go
File metadata and controls
240 lines (215 loc) · 5.44 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package remote
import (
"context"
"crypto/tls"
"errors"
"io"
"log/slog"
"net"
"time"
"github.com/anthdm/hollywood/actor"
"storj.io/drpc/drpcconn"
"storj.io/drpc/drpcmanager"
"storj.io/drpc/drpcwire"
)
const (
connIdleTimeout = time.Minute * 10
streamWriterBatchSize = 1024
)
type streamWriter struct {
writeToAddr string
rawconn net.Conn
conn *drpcconn.Conn
stream DRPCRemote_ReceiveStream
engine *actor.Engine
routerPID *actor.PID
pid *actor.PID
inbox actor.Inboxer
serializer Serializer
tlsConfig *tls.Config
buffSize int
}
func newStreamWriter(e *actor.Engine, rpid *actor.PID, address string, tlsConfig *tls.Config, buffSize int) *streamWriter {
return &streamWriter{
writeToAddr: address,
engine: e,
routerPID: rpid,
inbox: actor.NewInbox(streamWriterBatchSize),
pid: actor.NewPID(e.Address(), "stream"+"/"+address),
serializer: ProtoSerializer{},
tlsConfig: tlsConfig,
buffSize: buffSize,
}
}
func (s *streamWriter) PID() *actor.PID { return s.pid }
func (s *streamWriter) Send(_ *actor.PID, msg any, sender *actor.PID) {
s.inbox.Send(actor.Envelope{Msg: msg, Sender: sender})
}
func (s *streamWriter) Invoke(msgs []actor.Envelope) {
// Lazy intitialize the connection with the the target remote.
if s.conn == nil {
s.init()
if s.conn == nil {
return
}
}
var (
typeLookup = make(map[string]int32)
typeNames = make([]string, 0)
senderLookup = make(map[uint64]int32)
senders = make([]*actor.PID, 0)
targetLookup = make(map[uint64]int32)
targets = make([]*actor.PID, 0)
messages = make([]*Message, len(msgs))
)
for i := range len(msgs) {
var (
stream = msgs[i].Msg.(*streamDeliver)
typeID int32
senderID int32
targetID int32
)
typeID, typeNames = lookupTypeName(typeLookup, s.serializer.TypeName(stream.msg), typeNames)
senderID, senders = lookupPIDs(senderLookup, stream.sender, senders)
targetID, targets = lookupPIDs(targetLookup, stream.target, targets)
b, err := s.serializer.Serialize(stream.msg)
if err != nil {
slog.Error("serialize", "err", err)
continue
}
messages[i] = &Message{
Data: b,
TypeNameIndex: typeID,
SenderIndex: senderID,
TargetIndex: targetID,
}
}
env := &Envelope{
Senders: senders,
Targets: targets,
TypeNames: typeNames,
Messages: messages,
}
if err := s.stream.Send(env); err != nil {
if errors.Is(err, io.EOF) {
_ = s.conn.Close()
return
}
slog.Error("stream writer failed sending message",
"err", err,
)
}
// refresh the connection deadline.
err := s.rawconn.SetDeadline(time.Now().Add(connIdleTimeout))
if err != nil {
slog.Error("failed to set context deadline", "err", err)
}
}
func (s *streamWriter) init() {
var (
rawconn net.Conn
err error
delay time.Duration = time.Millisecond * 500
maxRetries = 3
)
for i := range maxRetries {
// Here we try to connect to the remote address.
switch s.tlsConfig {
case nil:
rawconn, err = net.Dial("tcp", s.writeToAddr)
if err != nil {
d := time.Duration(delay * time.Duration(i*2))
slog.Error("net.Dial", "err", err, "remote", s.writeToAddr, "retry", i, "max", maxRetries, "delay", d)
time.Sleep(d)
continue
}
default:
slog.Debug("remote using TLS for writing")
rawconn, err = tls.Dial("tcp", s.writeToAddr, s.tlsConfig)
if err != nil {
d := time.Duration(delay * time.Duration(i*2))
slog.Error("tls.Dial", "err", err, "remote", s.writeToAddr, "retry", i, "max", maxRetries, "delay", d)
time.Sleep(d)
continue
}
}
break
}
// We could not reach the remote after retrying N times. Hence, shutdown the stream writer.
// and notify RemoteUnreachableEvent.
if rawconn == nil {
s.Shutdown()
return
}
s.rawconn = rawconn
err = rawconn.SetDeadline(time.Now().Add(connIdleTimeout))
if err != nil {
slog.Error("failed to set deadline on raw connection", "err", err)
return
}
conn := drpcconn.NewWithOptions(rawconn, drpcconn.Options{
Manager: drpcmanager.Options{
Reader: drpcwire.ReaderOptions{
MaximumBufferSize: s.buffSize,
},
},
})
client := NewDRPCRemoteClient(conn)
stream, err := client.Receive(context.Background())
if err != nil {
slog.Error("receive", "err", err, "remote", s.writeToAddr)
s.Shutdown()
return
}
s.stream = stream
s.conn = conn
slog.Debug("connected",
"remote", s.writeToAddr,
)
go func() {
<-s.conn.Closed()
slog.Debug("lost connection",
"remote", s.writeToAddr,
)
s.Shutdown()
}()
}
// TODO: is there a way that stream router can listen to event stream
// instead of sending the event itself?
func (s *streamWriter) Shutdown() {
evt := actor.RemoteUnreachableEvent{ListenAddr: s.writeToAddr}
s.engine.Send(s.routerPID, evt)
s.engine.BroadcastEvent(evt)
if s.stream != nil {
s.stream.Close()
}
s.inbox.Stop()
s.engine.Registry.Remove(s.PID())
}
func (s *streamWriter) Start() {
s.inbox.Start(s)
}
func lookupPIDs(m map[uint64]int32, pid *actor.PID, pids []*actor.PID) (int32, []*actor.PID) {
if pid == nil {
return 0, pids
}
max := int32(len(m))
key := pid.LookupKey()
id, ok := m[key]
if !ok {
m[key] = max
id = max
pids = append(pids, pid)
}
return id, pids
}
func lookupTypeName(m map[string]int32, name string, types []string) (int32, []string) {
max := int32(len(m))
id, ok := m[name]
if !ok {
m[name] = max
id = max
types = append(types, name)
}
return id, types
}