-
-
Notifications
You must be signed in to change notification settings - Fork 614
/
client.go
162 lines (154 loc) · 3.64 KB
/
client.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
package udp
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"sync"
"time"
)
type Client struct {
mu sync.Mutex
connId ConnectionId
connIdIssued time.Time
Dispatcher *Dispatcher
Writer io.Writer
}
func (cl *Client) Announce(
ctx context.Context, req AnnounceRequest, peers AnnounceResponsePeers, opts Options,
) (
respHdr AnnounceResponseHeader, err error,
) {
respBody, err := cl.request(ctx, ActionAnnounce, append(mustMarshal(req), opts.Encode()...))
if err != nil {
return
}
r := bytes.NewBuffer(respBody)
err = Read(r, &respHdr)
if err != nil {
err = fmt.Errorf("reading response header: %w", err)
return
}
err = peers.UnmarshalBinary(r.Bytes())
if err != nil {
err = fmt.Errorf("reading response peers: %w", err)
}
return
}
func (cl *Client) Scrape(
ctx context.Context, ihs []InfoHash,
) (
out ScrapeResponse, err error,
) {
// There's no way to pass options in a scrape, since we don't when the request body ends.
respBody, err := cl.request(ctx, ActionScrape, mustMarshal(ScrapeRequest(ihs)))
if err != nil {
return
}
r := bytes.NewBuffer(respBody)
for r.Len() != 0 {
var item ScrapeInfohashResult
err = Read(r, &item)
if err != nil {
return
}
out = append(out, item)
}
if len(out) > len(ihs) {
err = fmt.Errorf("got %v results but expected %v", len(out), len(ihs))
return
}
return
}
func (cl *Client) connect(ctx context.Context) (err error) {
// We could get fancier here and use RWMutex, and even fire off the connection asynchronously
// and provide a grace period while it resolves.
cl.mu.Lock()
defer cl.mu.Unlock()
if !cl.connIdIssued.IsZero() && time.Since(cl.connIdIssued) < time.Minute {
return nil
}
respBody, err := cl.request(ctx, ActionConnect, nil)
if err != nil {
return err
}
var connResp ConnectionResponse
err = binary.Read(bytes.NewReader(respBody), binary.BigEndian, &connResp)
if err != nil {
return
}
cl.connId = connResp.ConnectionId
cl.connIdIssued = time.Now()
return
}
func (cl *Client) connIdForRequest(ctx context.Context, action Action) (id ConnectionId, err error) {
if action == ActionConnect {
id = ConnectRequestConnectionId
return
}
err = cl.connect(ctx)
if err != nil {
return
}
id = cl.connId
return
}
func (cl *Client) requestWriter(ctx context.Context, action Action, body []byte, tId TransactionId) (err error) {
var buf bytes.Buffer
for n := 0; ; n++ {
var connId ConnectionId
connId, err = cl.connIdForRequest(ctx, action)
if err != nil {
return
}
buf.Reset()
err = binary.Write(&buf, binary.BigEndian, RequestHeader{
ConnectionId: connId,
Action: action,
TransactionId: tId,
})
if err != nil {
panic(err)
}
buf.Write(body)
_, err = cl.Writer.Write(buf.Bytes())
if err != nil {
return
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(timeout(n)):
}
}
}
func (cl *Client) request(ctx context.Context, action Action, body []byte) (respBody []byte, err error) {
respChan := make(chan DispatchedResponse, 1)
t := cl.Dispatcher.NewTransaction(func(dr DispatchedResponse) {
respChan <- dr
})
defer t.End()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
writeErr := make(chan error, 1)
go func() {
writeErr <- cl.requestWriter(ctx, action, body, t.Id())
}()
select {
case dr := <-respChan:
if dr.Header.Action == action {
respBody = dr.Body
} else if dr.Header.Action == ActionError {
err = errors.New(string(dr.Body))
} else {
err = fmt.Errorf("unexpected response action %v", dr.Header.Action)
}
case err = <-writeErr:
err = fmt.Errorf("write error: %w", err)
case <-ctx.Done():
err = ctx.Err()
}
return
}