conn.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // Copyright 2012 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis
  15. import (
  16. "bufio"
  17. "bytes"
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "strconv"
  23. "sync"
  24. "time"
  25. )
  26. // conn is the low-level implementation of Conn
  27. type conn struct {
  28. conn net.Conn
  29. // Read
  30. readTimeout time.Duration
  31. br *bufio.Reader
  32. scratch []byte
  33. // Write
  34. writeTimeout time.Duration
  35. bw *bufio.Writer
  36. // Shared
  37. mu sync.Mutex
  38. pending int
  39. err error
  40. }
  41. // Dial connects to the Redis server at the given network and address.
  42. func Dial(network, address string) (Conn, error) {
  43. c, err := net.Dial(network, address)
  44. if err != nil {
  45. return nil, errors.New("Could not connect to Redis server: " + err.Error())
  46. }
  47. return NewConn(c, 0, 0), nil
  48. }
  49. // DialTimeout acts like Dial but takes timeouts for establishing the
  50. // connection to the server, write a command and reading a reply.
  51. func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
  52. var c net.Conn
  53. var err error
  54. if connectTimeout > 0 {
  55. c, err = net.DialTimeout(network, address, connectTimeout)
  56. } else {
  57. c, err = net.Dial(network, address)
  58. }
  59. if err != nil {
  60. return nil, errors.New("Could not connect to Redis server: " + err.Error())
  61. }
  62. return NewConn(c, readTimeout, writeTimeout), nil
  63. }
  64. // NewConn returns a new Redigo connection for the given net connection.
  65. func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn {
  66. return &conn{
  67. conn: netConn,
  68. bw: bufio.NewWriter(netConn),
  69. br: bufio.NewReader(netConn),
  70. readTimeout: readTimeout,
  71. writeTimeout: writeTimeout,
  72. }
  73. }
  74. func (c *conn) Close() error {
  75. err := c.conn.Close()
  76. if err != nil {
  77. c.fatal(err)
  78. } else {
  79. c.fatal(errors.New("redigo: closed"))
  80. }
  81. return err
  82. }
  83. func (c *conn) fatal(err error) error {
  84. c.mu.Lock()
  85. if c.err == nil {
  86. c.err = err
  87. }
  88. c.mu.Unlock()
  89. return err
  90. }
  91. func (c *conn) Err() error {
  92. c.mu.Lock()
  93. err := c.err
  94. c.mu.Unlock()
  95. return err
  96. }
  97. func (c *conn) writeN(prefix byte, n int) error {
  98. c.scratch = append(c.scratch[0:0], prefix)
  99. c.scratch = strconv.AppendInt(c.scratch, int64(n), 10)
  100. c.scratch = append(c.scratch, "\r\n"...)
  101. _, err := c.bw.Write(c.scratch)
  102. return err
  103. }
  104. func (c *conn) writeString(s string) error {
  105. c.writeN('$', len(s))
  106. c.bw.WriteString(s)
  107. _, err := c.bw.WriteString("\r\n")
  108. return err
  109. }
  110. func (c *conn) writeBytes(p []byte) error {
  111. c.writeN('$', len(p))
  112. c.bw.Write(p)
  113. _, err := c.bw.WriteString("\r\n")
  114. return err
  115. }
  116. func (c *conn) writeCommand(cmd string, args []interface{}) (err error) {
  117. c.writeN('*', 1+len(args))
  118. err = c.writeString(cmd)
  119. for _, arg := range args {
  120. if err != nil {
  121. break
  122. }
  123. switch arg := arg.(type) {
  124. case string:
  125. err = c.writeString(arg)
  126. case []byte:
  127. err = c.writeBytes(arg)
  128. case bool:
  129. if arg {
  130. err = c.writeString("1")
  131. } else {
  132. err = c.writeString("0")
  133. }
  134. case nil:
  135. err = c.writeString("")
  136. default:
  137. var buf bytes.Buffer
  138. fmt.Fprint(&buf, arg)
  139. err = c.writeBytes(buf.Bytes())
  140. }
  141. }
  142. return err
  143. }
  144. func (c *conn) readLine() ([]byte, error) {
  145. p, err := c.br.ReadSlice('\n')
  146. if err == bufio.ErrBufferFull {
  147. return nil, errors.New("redigo: long response line")
  148. }
  149. if err != nil {
  150. return nil, err
  151. }
  152. i := len(p) - 2
  153. if i < 0 || p[i] != '\r' {
  154. return nil, errors.New("redigo: bad response line terminator")
  155. }
  156. return p[:i], nil
  157. }
  158. func (c *conn) readReply() (interface{}, error) {
  159. line, err := c.readLine()
  160. if err != nil {
  161. return nil, err
  162. }
  163. if len(line) == 0 {
  164. return nil, errors.New("redigo: short response line")
  165. }
  166. switch line[0] {
  167. case '+':
  168. return string(line[1:]), nil
  169. case '-':
  170. return Error(string(line[1:])), nil
  171. case ':':
  172. n, err := strconv.ParseInt(string(line[1:]), 10, 64)
  173. if err != nil {
  174. return nil, err
  175. }
  176. return n, nil
  177. case '$':
  178. n, err := strconv.Atoi(string(line[1:]))
  179. if err != nil || n < 0 {
  180. return nil, err
  181. }
  182. p := make([]byte, n)
  183. _, err = io.ReadFull(c.br, p)
  184. if err != nil {
  185. return nil, err
  186. }
  187. line, err := c.readLine()
  188. if err != nil {
  189. return nil, err
  190. }
  191. if len(line) != 0 {
  192. return nil, errors.New("redigo: bad bulk format")
  193. }
  194. return p, nil
  195. case '*':
  196. n, err := strconv.Atoi(string(line[1:]))
  197. if err != nil || n < 0 {
  198. return nil, err
  199. }
  200. r := make([]interface{}, n)
  201. for i := range r {
  202. r[i], err = c.readReply()
  203. if err != nil {
  204. return nil, err
  205. }
  206. }
  207. return r, nil
  208. }
  209. return nil, errors.New("redigo: unpexected response line")
  210. }
  211. func (c *conn) Send(cmd string, args ...interface{}) error {
  212. if c.writeTimeout != 0 {
  213. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  214. }
  215. if err := c.writeCommand(cmd, args); err != nil {
  216. return c.fatal(err)
  217. }
  218. c.mu.Lock()
  219. c.pending += 1
  220. c.mu.Unlock()
  221. return nil
  222. }
  223. func (c *conn) Flush() error {
  224. if c.writeTimeout != 0 {
  225. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  226. }
  227. if err := c.bw.Flush(); err != nil {
  228. return c.fatal(err)
  229. }
  230. return nil
  231. }
  232. func (c *conn) Receive() (reply interface{}, err error) {
  233. c.mu.Lock()
  234. // There can be more receives than sends when using pub/sub. To allow
  235. // normal use of the connection after unsubscribe from all channels, do not
  236. // decrement pending to a negative value.
  237. if c.pending > 0 {
  238. c.pending -= 1
  239. }
  240. c.mu.Unlock()
  241. if c.readTimeout != 0 {
  242. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  243. }
  244. if reply, err = c.readReply(); err != nil {
  245. return nil, c.fatal(err)
  246. }
  247. if err, ok := reply.(Error); ok {
  248. return nil, err
  249. }
  250. return
  251. }
  252. func (c *conn) Do(cmd string, args ...interface{}) (reply interface{}, err error) {
  253. // Send
  254. if c.writeTimeout != 0 {
  255. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  256. }
  257. c.writeCommand(cmd, args)
  258. if err = c.bw.Flush(); err != nil {
  259. return nil, c.fatal(err)
  260. }
  261. c.mu.Lock()
  262. pending := c.pending
  263. c.pending = 0
  264. c.mu.Unlock()
  265. // Receive
  266. for ; pending >= 0; pending-- {
  267. var e error
  268. if reply, e = c.readReply(); e != nil {
  269. return nil, c.fatal(e)
  270. }
  271. if e, ok := reply.(Error); ok && err == nil {
  272. err = e
  273. }
  274. }
  275. return
  276. }