Skip to content

Commit

Permalink
rewise client timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Oct 24, 2024
1 parent 01e0982 commit 6498379
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
15 changes: 7 additions & 8 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ type Client struct {
Timeout time.Duration

// Dialer allows for customizing the way connections are established.
// If set, it overrides the Addr field and uses the provided dialer to
// create connections for DNS queries.
// If set, Addr and Timeout will be ignore.
Dialer Dialer
}

Expand All @@ -48,18 +47,18 @@ func (c *Client) exchange(ctx context.Context, req, resp *Message) error {
return err
}

_, err = conn.Write(req.Raw)
if err != nil {
return nil
}

if c.Timeout > 0 {
if c.Timeout > 0 && c.Dialer == nil {
err = conn.SetDeadline(time.Now().Add(c.Timeout))
if err != nil {
return err
}
}

_, err = conn.Write(req.Raw)
if err != nil {
return nil
}

resp.Raw = resp.Raw[:cap(resp.Raw)]
n, err := conn.Read(resp.Raw)
if err != nil {
Expand Down
7 changes: 7 additions & 0 deletions client_dialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ type UDPDialer struct {
// Addr specifies the remote UDP address that the dialer will connect to.
Addr *net.UDPAddr

// Timeout specifies the maximum duration for a query to complete.
// If a query exceeds this duration, it will result in a timeout error.
Timeout time.Duration

// MaxConns limits the maximum number of UDP connections that can be created
// and reused. Once this limit is reached, no new connections will be made.
MaxConns uint16
Expand All @@ -43,6 +47,9 @@ func (d *UDPDialer) get() (net.Conn, error) {

c := d.conns[cheaprandn(uint32(d.MaxConns))]
c.mu.Lock()
if d.Timeout > 0 {
c.SetDeadline(time.Now().Add(d.Timeout))
}

return c, nil
}
Expand Down

0 comments on commit 6498379

Please sign in to comment.