redis/internal/pool/conn.go

128 lines
2.1 KiB
Go
Raw Permalink Normal View History

package pool
import (
2020-06-09 16:29:53 +03:00
"bufio"
"context"
"net"
"sync/atomic"
"time"
2016-07-02 15:52:10 +03:00
2023-01-23 09:48:54 +03:00
"github.com/redis/go-redis/v9/internal/proto"
)
2016-03-12 13:41:02 +03:00
var noDeadline = time.Time{}
type Conn struct {
2020-06-09 16:29:53 +03:00
usedAt int64 // atomic
netConn net.Conn
rd *proto.Reader
2020-06-09 16:29:53 +03:00
bw *bufio.Writer
wr *proto.Writer
2019-03-25 14:02:31 +03:00
Inited bool
pooled bool
createdAt time.Time
}
func NewConn(netConn net.Conn) *Conn {
cn := &Conn{
2019-03-25 14:02:31 +03:00
netConn: netConn,
createdAt: time.Now(),
}
2018-08-17 13:56:37 +03:00
cn.rd = proto.NewReader(netConn)
2020-06-09 16:29:53 +03:00
cn.bw = bufio.NewWriter(netConn)
cn.wr = proto.NewWriter(cn.bw)
cn.SetUsedAt(time.Now())
return cn
}
func (cn *Conn) UsedAt() time.Time {
unix := atomic.LoadInt64(&cn.usedAt)
return time.Unix(unix, 0)
}
func (cn *Conn) SetUsedAt(tm time.Time) {
atomic.StoreInt64(&cn.usedAt, tm.Unix())
}
func (cn *Conn) SetNetConn(netConn net.Conn) {
cn.netConn = netConn
2018-08-15 11:53:15 +03:00
cn.rd.Reset(netConn)
2020-06-09 16:29:53 +03:00
cn.bw.Reset(netConn)
}
func (cn *Conn) Write(b []byte) (int, error) {
return cn.netConn.Write(b)
}
func (cn *Conn) RemoteAddr() net.Addr {
2020-09-28 15:35:57 +03:00
if cn.netConn != nil {
return cn.netConn.RemoteAddr()
}
return nil
}
func (cn *Conn) WithReader(
ctx context.Context, timeout time.Duration, fn func(rd *proto.Reader) error,
) error {
2022-10-05 10:36:12 +03:00
if timeout >= 0 {
if err := cn.netConn.SetReadDeadline(cn.deadline(ctx, timeout)); err != nil {
return err
}
2021-03-20 11:01:48 +03:00
}
return fn(cn.rd)
2018-08-06 13:59:15 +03:00
}
func (cn *Conn) WithWriter(
ctx context.Context, timeout time.Duration, fn func(wr *proto.Writer) error,
) error {
2022-10-05 10:36:12 +03:00
if timeout >= 0 {
if err := cn.netConn.SetWriteDeadline(cn.deadline(ctx, timeout)); err != nil {
return err
}
2021-03-20 11:01:48 +03:00
}
2021-03-20 11:01:48 +03:00
if cn.bw.Buffered() > 0 {
cn.bw.Reset(cn.netConn)
}
2020-07-09 10:39:46 +03:00
2021-03-20 11:01:48 +03:00
if err := fn(cn.wr); err != nil {
return err
2021-03-20 11:01:48 +03:00
}
return cn.bw.Flush()
2018-08-15 11:53:15 +03:00
}
2016-03-15 15:04:35 +03:00
func (cn *Conn) Close() error {
return cn.netConn.Close()
}
func (cn *Conn) deadline(ctx context.Context, timeout time.Duration) time.Time {
tm := time.Now()
cn.SetUsedAt(tm)
if timeout > 0 {
tm = tm.Add(timeout)
}
2019-06-09 12:29:23 +03:00
if ctx != nil {
deadline, ok := ctx.Deadline()
if ok {
if timeout == 0 {
return deadline
}
2019-06-14 16:00:03 +03:00
if deadline.Before(tm) {
return deadline
}
return tm
}
}
if timeout > 0 {
return tm
}
return noDeadline
}