-
Notifications
You must be signed in to change notification settings - Fork 51
/
provider.go
280 lines (219 loc) · 5.48 KB
/
provider.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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package flatend
import (
"errors"
"fmt"
"github.com/lithdew/kademlia"
"github.com/lithdew/monte"
"io"
"sync"
)
type Stream struct {
ID uint32
Header *ServiceResponsePacket
Reader *pipeReader
Writer *pipeWriter
received uint64
wg sync.WaitGroup
once sync.Once
}
type Provider struct {
id *kademlia.ID
conn *monte.Conn
services map[string]struct{}
lock sync.Mutex // protects all stream-related structures
counter uint32 // total number of outgoing streams
streams map[uint32]*Stream // maps stream ids to stream instances
}
func (p *Provider) NextStream() *Stream {
reader, writer := createWrappedPipe()
p.lock.Lock()
defer p.lock.Unlock()
id := p.counter
p.counter += 2
stream := &Stream{
ID: id,
Reader: reader,
Writer: writer,
}
stream.wg.Add(1)
p.streams[id] = stream
return stream
}
func (p *Provider) GetStream(id uint32) (*Stream, bool) {
p.lock.Lock()
defer p.lock.Unlock()
stream, exists := p.streams[id]
return stream, exists
}
func (p *Provider) RegisterStream(header ServiceRequestPacket) (*Stream, bool) {
reader, writer := createWrappedPipe()
p.lock.Lock()
defer p.lock.Unlock()
stream, exists := p.streams[header.ID]
if exists {
return stream, false
}
stream = &Stream{
ID: header.ID,
Reader: reader,
Writer: writer,
}
stream.wg.Add(1)
p.streams[header.ID] = stream
return stream, true
}
func (p *Provider) CloseStreamWithError(stream *Stream, err error) {
p.lock.Lock()
defer p.lock.Unlock()
_ = stream.Reader.CloseWithError(err)
_ = stream.Writer.CloseWithError(err)
stream.once.Do(stream.wg.Done)
delete(p.streams, stream.ID)
}
func (p *Provider) Close() {
p.lock.Lock()
defer p.lock.Unlock()
for id, stream := range p.streams {
err := fmt.Errorf("provider connection closed: %w", io.EOF)
_ = stream.Reader.CloseWithError(err)
_ = stream.Writer.CloseWithError(err)
stream.once.Do(stream.wg.Done)
delete(p.streams, id)
}
}
var ErrProviderNotAvailable = errors.New("provider unable to provide service")
func (p *Provider) Push(services []string, headers map[string]string, body io.ReadCloser) (*Stream, error) {
buf := make([]byte, ChunkSize)
stream := p.NextStream()
header := ServiceRequestPacket{
ID: stream.ID,
Headers: headers,
Services: services,
}
err := p.conn.Send(header.AppendTo([]byte{OpcodeServiceRequest}))
if err != nil {
err = fmt.Errorf("failed to send stream header: %s: %w", err, ErrProviderNotAvailable)
p.CloseStreamWithError(stream, err)
return nil, err
}
for {
nn, err := body.Read(buf[:ChunkSize])
if err != nil && err != io.EOF {
err = fmt.Errorf("failed reading body: %w", err)
p.CloseStreamWithError(stream, err)
return nil, err
}
payload := DataPacket{
ID: stream.ID,
Data: buf[:nn],
}
if err := p.conn.Send(payload.AppendTo([]byte{OpcodeData})); err != nil {
err = fmt.Errorf("failed writing body chunk as a data packet to peer: %w", err)
p.CloseStreamWithError(stream, err)
return nil, err
}
if err == io.EOF && nn == 0 {
break
}
}
stream.wg.Wait()
if stream.Header == nil {
return nil, fmt.Errorf("no response headers were returned: %w", io.EOF)
}
if !stream.Header.Handled {
return nil, fmt.Errorf("provider unable to service: %s", services)
}
return stream, nil
}
func (p *Provider) Addr() string {
if p.id != nil {
return Addr(p.id.Host, p.id.Port)
} else {
return "<anon>"
}
}
func (p *Provider) Services() []string {
services := make([]string, 0, len(p.services))
for service := range p.services {
services = append(services, service)
}
return services
}
type Providers struct {
sync.Mutex
services map[string]map[*monte.Conn]struct{}
providers map[*monte.Conn]*Provider
}
func NewProviders() *Providers {
return &Providers{
services: make(map[string]map[*monte.Conn]struct{}),
providers: make(map[*monte.Conn]*Provider),
}
}
func (p *Providers) findProvider(conn *monte.Conn) *Provider {
p.Lock()
defer p.Unlock()
return p.providers[conn]
}
func (p *Providers) getProviders(services ...string) []*Provider {
p.Lock()
defer p.Unlock()
var conns []*monte.Conn
for _, service := range services {
for conn := range p.services[service] {
conns = append(conns, conn)
}
}
if conns == nil {
return nil
}
providers := make([]*Provider, 0, len(conns))
for _, conn := range conns {
providers = append(providers, p.providers[conn])
}
return providers
}
func (p *Providers) register(conn *monte.Conn, id *kademlia.ID, services []string, outgoing bool) (*Provider, bool) {
p.Lock()
defer p.Unlock()
provider, exists := p.providers[conn]
if !exists {
provider = &Provider{
services: make(map[string]struct{}),
streams: make(map[uint32]*Stream),
}
if outgoing {
provider.counter = 1
} else {
provider.counter = 0
}
p.providers[conn] = provider
}
provider.id = id
provider.conn = conn
for _, service := range services {
provider.services[service] = struct{}{}
if _, exists := p.services[service]; !exists {
p.services[service] = make(map[*monte.Conn]struct{})
}
p.services[service][conn] = struct{}{}
}
return provider, exists
}
func (p *Providers) deregister(conn *monte.Conn) *Provider {
p.Lock()
defer p.Unlock()
provider, exists := p.providers[conn]
if !exists {
return nil
}
delete(p.providers, conn)
for service := range provider.services {
delete(p.services[service], conn)
if len(p.services[service]) == 0 {
delete(p.services, service)
}
}
provider.Close()
return provider
}