-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
connection.go
79 lines (63 loc) · 1.73 KB
/
connection.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
package transport
import (
"context"
"net"
"sync"
"time"
"golang.org/x/xerrors"
"github.com/gotd/td/bin"
)
// Conn is transport connection.
type Conn interface {
Send(ctx context.Context, b *bin.Buffer) error
Recv(ctx context.Context, b *bin.Buffer) error
Close() error
}
var _ Conn = (*connection)(nil)
// connection is MTProto connection.
type connection struct {
conn net.Conn
codec Codec
readMux sync.Mutex
writeMux sync.Mutex
}
// Send sends message from buffer using MTProto connection.
func (c *connection) Send(ctx context.Context, b *bin.Buffer) error {
// Serializing access to deadlines.
c.writeMux.Lock()
defer c.writeMux.Unlock()
if err := c.conn.SetWriteDeadline(time.Time{}); err != nil {
return xerrors.Errorf("reset write deadline: %w", err)
}
if deadline, ok := ctx.Deadline(); ok {
if err := c.conn.SetWriteDeadline(deadline); err != nil {
return xerrors.Errorf("set write deadline: %w", err)
}
}
if err := c.codec.Write(c.conn, b); err != nil {
return xerrors.Errorf("write: %w", err)
}
return nil
}
// Recv reads message to buffer using MTProto connection.
func (c *connection) Recv(ctx context.Context, b *bin.Buffer) error {
// Serializing access to deadlines.
c.readMux.Lock()
defer c.readMux.Unlock()
if err := c.conn.SetReadDeadline(time.Time{}); err != nil {
return xerrors.Errorf("reset read deadline: %w", err)
}
if deadline, ok := ctx.Deadline(); ok {
if err := c.conn.SetReadDeadline(deadline); err != nil {
return xerrors.Errorf("set read deadline: %w", err)
}
}
if err := c.codec.Read(c.conn, b); err != nil {
return xerrors.Errorf("read: %w", err)
}
return nil
}
// Close closes MTProto connection.
func (c *connection) Close() error {
return c.conn.Close()
}