conn.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. // Shared
  29. mu sync.Mutex
  30. pending int
  31. err error
  32. conn net.Conn
  33. // Read
  34. readTimeout time.Duration
  35. br *bufio.Reader
  36. // Write
  37. writeTimeout time.Duration
  38. bw *bufio.Writer
  39. // Scratch space for formatting argument length.
  40. // '*' or '$', length, "\r\n"
  41. lenScratch [1 + 19 + 2]byte
  42. // Scratch space for formatting integers.
  43. intScratch [20]byte
  44. }
  45. // Dial connects to the Redis server at the given network and address.
  46. func Dial(network, address string) (Conn, error) {
  47. c, err := net.Dial(network, address)
  48. if err != nil {
  49. return nil, errors.New("Could not connect to Redis server: " + err.Error())
  50. }
  51. return NewConn(c, 0, 0), nil
  52. }
  53. // DialTimeout acts like Dial but takes timeouts for establishing the
  54. // connection to the server, writing a command and reading a reply.
  55. func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
  56. var c net.Conn
  57. var err error
  58. if connectTimeout > 0 {
  59. c, err = net.DialTimeout(network, address, connectTimeout)
  60. } else {
  61. c, err = net.Dial(network, address)
  62. }
  63. if err != nil {
  64. return nil, errors.New("Could not connect to Redis server: " + err.Error())
  65. }
  66. return NewConn(c, readTimeout, writeTimeout), nil
  67. }
  68. // NewConn returns a new Redigo connection for the given net connection.
  69. func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn {
  70. return &conn{
  71. conn: netConn,
  72. bw: bufio.NewWriter(netConn),
  73. br: bufio.NewReader(netConn),
  74. readTimeout: readTimeout,
  75. writeTimeout: writeTimeout,
  76. }
  77. }
  78. func (c *conn) Close() error {
  79. err := c.conn.Close()
  80. if err != nil {
  81. c.fatal(err)
  82. } else {
  83. c.fatal(errors.New("redigo: closed"))
  84. }
  85. return err
  86. }
  87. func (c *conn) fatal(err error) error {
  88. c.mu.Lock()
  89. if c.err == nil {
  90. c.err = err
  91. }
  92. c.mu.Unlock()
  93. return err
  94. }
  95. func (c *conn) Err() error {
  96. c.mu.Lock()
  97. err := c.err
  98. c.mu.Unlock()
  99. return err
  100. }
  101. func (c *conn) writeLen(prefix byte, n int) error {
  102. c.lenScratch[0] = prefix
  103. s := strconv.AppendInt(c.lenScratch[:1], int64(n), 10)
  104. s = append(s, "\r\n"...)
  105. _, err := c.bw.Write(s)
  106. return err
  107. }
  108. func (c *conn) writeString(s string) error {
  109. c.writeLen('$', len(s))
  110. c.bw.WriteString(s)
  111. _, err := c.bw.WriteString("\r\n")
  112. return err
  113. }
  114. func (c *conn) writeBytes(p []byte) error {
  115. c.writeLen('$', len(p))
  116. c.bw.Write(p)
  117. _, err := c.bw.WriteString("\r\n")
  118. return err
  119. }
  120. func (c *conn) writeInt64(n int64) error {
  121. return c.writeBytes(strconv.AppendInt(c.intScratch[0:0], n, 10))
  122. }
  123. func (c *conn) writeCommand(cmd string, args []interface{}) (err error) {
  124. c.writeLen('*', 1+len(args))
  125. err = c.writeString(cmd)
  126. for _, arg := range args {
  127. if err != nil {
  128. break
  129. }
  130. switch arg := arg.(type) {
  131. case string:
  132. err = c.writeString(arg)
  133. case []byte:
  134. err = c.writeBytes(arg)
  135. case int:
  136. err = c.writeInt64(int64(arg))
  137. case int64:
  138. err = c.writeInt64(arg)
  139. case bool:
  140. if arg {
  141. err = c.writeString("1")
  142. } else {
  143. err = c.writeString("0")
  144. }
  145. case nil:
  146. err = c.writeString("")
  147. default:
  148. var buf bytes.Buffer
  149. fmt.Fprint(&buf, arg)
  150. err = c.writeBytes(buf.Bytes())
  151. }
  152. }
  153. return err
  154. }
  155. func (c *conn) readLine() ([]byte, error) {
  156. p, err := c.br.ReadSlice('\n')
  157. if err == bufio.ErrBufferFull {
  158. return nil, errors.New("redigo: long response line")
  159. }
  160. if err != nil {
  161. return nil, err
  162. }
  163. i := len(p) - 2
  164. if i < 0 || p[i] != '\r' {
  165. return nil, errors.New("redigo: bad response line terminator")
  166. }
  167. return p[:i], nil
  168. }
  169. func (c *conn) readReply() (interface{}, error) {
  170. line, err := c.readLine()
  171. if err != nil {
  172. return nil, err
  173. }
  174. if len(line) == 0 {
  175. return nil, errors.New("redigo: short response line")
  176. }
  177. switch line[0] {
  178. case '+':
  179. return string(line[1:]), nil
  180. case '-':
  181. return Error(string(line[1:])), nil
  182. case ':':
  183. n, err := strconv.ParseInt(string(line[1:]), 10, 64)
  184. if err != nil {
  185. return nil, err
  186. }
  187. return n, nil
  188. case '$':
  189. n, err := strconv.Atoi(string(line[1:]))
  190. if err != nil || n < 0 {
  191. return nil, err
  192. }
  193. p := make([]byte, n)
  194. _, err = io.ReadFull(c.br, p)
  195. if err != nil {
  196. return nil, err
  197. }
  198. line, err := c.readLine()
  199. if err != nil {
  200. return nil, err
  201. }
  202. if len(line) != 0 {
  203. return nil, errors.New("redigo: bad bulk format")
  204. }
  205. return p, nil
  206. case '*':
  207. n, err := strconv.Atoi(string(line[1:]))
  208. if err != nil || n < 0 {
  209. return nil, err
  210. }
  211. r := make([]interface{}, n)
  212. for i := range r {
  213. r[i], err = c.readReply()
  214. if err != nil {
  215. return nil, err
  216. }
  217. }
  218. return r, nil
  219. }
  220. return nil, errors.New("redigo: unpexected response line")
  221. }
  222. func (c *conn) Send(cmd string, args ...interface{}) error {
  223. c.mu.Lock()
  224. c.pending += 1
  225. c.mu.Unlock()
  226. if c.writeTimeout != 0 {
  227. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  228. }
  229. if err := c.writeCommand(cmd, args); err != nil {
  230. return c.fatal(err)
  231. }
  232. return nil
  233. }
  234. func (c *conn) Flush() error {
  235. if c.writeTimeout != 0 {
  236. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  237. }
  238. if err := c.bw.Flush(); err != nil {
  239. return c.fatal(err)
  240. }
  241. return nil
  242. }
  243. func (c *conn) Receive() (reply interface{}, err error) {
  244. c.mu.Lock()
  245. // There can be more receives than sends when using pub/sub. To allow
  246. // normal use of the connection after unsubscribe from all channels, do not
  247. // decrement pending to a negative value.
  248. if c.pending > 0 {
  249. c.pending -= 1
  250. }
  251. c.mu.Unlock()
  252. if c.readTimeout != 0 {
  253. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  254. }
  255. if reply, err = c.readReply(); err != nil {
  256. return nil, c.fatal(err)
  257. }
  258. if err, ok := reply.(Error); ok {
  259. return nil, err
  260. }
  261. return
  262. }
  263. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  264. if c.writeTimeout != 0 {
  265. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  266. }
  267. if cmd != "" {
  268. c.writeCommand(cmd, args)
  269. }
  270. if err := c.bw.Flush(); err != nil {
  271. return nil, c.fatal(err)
  272. }
  273. c.mu.Lock()
  274. pending := c.pending
  275. c.pending = 0
  276. c.mu.Unlock()
  277. if c.readTimeout != 0 {
  278. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  279. }
  280. if cmd == "" {
  281. reply := make([]interface{}, pending)
  282. for i := range reply {
  283. if r, e := c.readReply(); e != nil {
  284. return nil, c.fatal(e)
  285. } else {
  286. reply[i] = r
  287. }
  288. }
  289. return reply, nil
  290. }
  291. var err error
  292. var reply interface{}
  293. for i := 0; i <= pending; i++ {
  294. var e error
  295. if reply, e = c.readReply(); e != nil {
  296. return nil, c.fatal(e)
  297. }
  298. if e, ok := reply.(Error); ok && err == nil {
  299. err = e
  300. }
  301. }
  302. return reply, err
  303. }