-
Notifications
You must be signed in to change notification settings - Fork 0
/
dial.go
69 lines (61 loc) · 1.76 KB
/
dial.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
package spectral
import (
"context"
"errors"
"fmt"
"net"
"time"
"github.com/cooldogedev/spectral/internal/frame"
)
func Dial(ctx context.Context, address string) (Connection, error) {
addr, err := net.ResolveUDPAddr("udp", address)
if err != nil {
return nil, err
}
conn, err := net.ListenUDP("udp", nil)
if err != nil {
return nil, err
}
uConn, err := newUDPConn(conn, false)
if err != nil {
_ = conn.Close()
return nil, err
}
c := newClientConnection(uConn, addr, context.Background())
c.logger.Log("connection_request", "addr", address)
if err := c.writeControl(&frame.ConnectionRequest{}, true); err != nil {
_ = c.CloseWithError(frame.ConnectionCloseInternal, "failed to send connection request")
return nil, err
}
go uConn.Read(func(dgram *datagram) (err error) {
defer dgram.reset()
_, sequenceID, frames, err := frame.Unpack(dgram.b)
if err != nil {
c.logger.Log("unpack_err", "err", err.Error())
return err
}
select {
case <-c.ctx.Done():
return context.Cause(c.ctx)
default:
c.packets <- &receivedPacket{sequenceID, frames, time.Now()}
return
}
})
select {
case <-ctx.Done():
c.logger.Log("connection_request_timeout")
_ = c.CloseWithError(frame.ConnectionCloseInternal, fmt.Sprintf("dialer context: %v", context.Cause(ctx).Error()))
return nil, context.Cause(ctx)
case response := <-c.response:
if response.Response == frame.ConnectionResponseFailed {
c.logger.Log("connection_request_fail")
_ = c.CloseWithError(frame.ConnectionCloseInternal, "failed to open connection")
return nil, errors.New("failed to open connection")
}
c.connectionID.Store(int64(response.ConnectionID))
c.logger.SetConnectionID(response.ConnectionID)
c.logger.Log("connection_request_success")
return c, nil
}
}