conn.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 and floats.
  43. numScratch [40]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.numScratch[:0], n, 10))
  122. }
  123. func (c *conn) writeFloat64(n float64) error {
  124. return c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64))
  125. }
  126. func (c *conn) writeCommand(cmd string, args []interface{}) (err error) {
  127. c.writeLen('*', 1+len(args))
  128. err = c.writeString(cmd)
  129. for _, arg := range args {
  130. if err != nil {
  131. break
  132. }
  133. switch arg := arg.(type) {
  134. case string:
  135. err = c.writeString(arg)
  136. case []byte:
  137. err = c.writeBytes(arg)
  138. case int:
  139. err = c.writeInt64(int64(arg))
  140. case int64:
  141. err = c.writeInt64(arg)
  142. case float64:
  143. err = c.writeFloat64(arg)
  144. case bool:
  145. if arg {
  146. err = c.writeString("1")
  147. } else {
  148. err = c.writeString("0")
  149. }
  150. case nil:
  151. err = c.writeString("")
  152. default:
  153. var buf bytes.Buffer
  154. fmt.Fprint(&buf, arg)
  155. err = c.writeBytes(buf.Bytes())
  156. }
  157. }
  158. return err
  159. }
  160. func (c *conn) readLine() ([]byte, error) {
  161. p, err := c.br.ReadSlice('\n')
  162. if err == bufio.ErrBufferFull {
  163. return nil, errors.New("redigo: long response line")
  164. }
  165. if err != nil {
  166. return nil, err
  167. }
  168. i := len(p) - 2
  169. if i < 0 || p[i] != '\r' {
  170. return nil, errors.New("redigo: bad response line terminator")
  171. }
  172. return p[:i], nil
  173. }
  174. func (c *conn) readReply() (interface{}, error) {
  175. line, err := c.readLine()
  176. if err != nil {
  177. return nil, err
  178. }
  179. if len(line) == 0 {
  180. return nil, errors.New("redigo: short response line")
  181. }
  182. switch line[0] {
  183. case '+':
  184. return string(line[1:]), nil
  185. case '-':
  186. return Error(string(line[1:])), nil
  187. case ':':
  188. n, err := strconv.ParseInt(string(line[1:]), 10, 64)
  189. if err != nil {
  190. return nil, err
  191. }
  192. return n, nil
  193. case '$':
  194. n, err := strconv.Atoi(string(line[1:]))
  195. if err != nil || n < 0 {
  196. return nil, err
  197. }
  198. p := make([]byte, n)
  199. _, err = io.ReadFull(c.br, p)
  200. if err != nil {
  201. return nil, err
  202. }
  203. line, err := c.readLine()
  204. if err != nil {
  205. return nil, err
  206. }
  207. if len(line) != 0 {
  208. return nil, errors.New("redigo: bad bulk format")
  209. }
  210. return p, nil
  211. case '*':
  212. n, err := strconv.Atoi(string(line[1:]))
  213. if err != nil || n < 0 {
  214. return nil, err
  215. }
  216. r := make([]interface{}, n)
  217. for i := range r {
  218. r[i], err = c.readReply()
  219. if err != nil {
  220. return nil, err
  221. }
  222. }
  223. return r, nil
  224. }
  225. return nil, errors.New("redigo: unexpected response line")
  226. }
  227. func (c *conn) Send(cmd string, args ...interface{}) error {
  228. c.mu.Lock()
  229. c.pending += 1
  230. c.mu.Unlock()
  231. if c.writeTimeout != 0 {
  232. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  233. }
  234. if err := c.writeCommand(cmd, args); err != nil {
  235. return c.fatal(err)
  236. }
  237. return nil
  238. }
  239. func (c *conn) Flush() error {
  240. if c.writeTimeout != 0 {
  241. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  242. }
  243. if err := c.bw.Flush(); err != nil {
  244. return c.fatal(err)
  245. }
  246. return nil
  247. }
  248. func (c *conn) Receive() (reply interface{}, err error) {
  249. c.mu.Lock()
  250. // There can be more receives than sends when using pub/sub. To allow
  251. // normal use of the connection after unsubscribe from all channels, do not
  252. // decrement pending to a negative value.
  253. if c.pending > 0 {
  254. c.pending -= 1
  255. }
  256. c.mu.Unlock()
  257. if c.readTimeout != 0 {
  258. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  259. }
  260. if reply, err = c.readReply(); err != nil {
  261. return nil, c.fatal(err)
  262. }
  263. if err, ok := reply.(Error); ok {
  264. return nil, err
  265. }
  266. return
  267. }
  268. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  269. if c.writeTimeout != 0 {
  270. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  271. }
  272. if cmd != "" {
  273. c.writeCommand(cmd, args)
  274. }
  275. if err := c.bw.Flush(); err != nil {
  276. return nil, c.fatal(err)
  277. }
  278. c.mu.Lock()
  279. pending := c.pending
  280. c.pending = 0
  281. c.mu.Unlock()
  282. if c.readTimeout != 0 {
  283. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  284. }
  285. if cmd == "" {
  286. reply := make([]interface{}, pending)
  287. for i := range reply {
  288. if r, e := c.readReply(); e != nil {
  289. return nil, c.fatal(e)
  290. } else {
  291. reply[i] = r
  292. }
  293. }
  294. return reply, nil
  295. }
  296. var err error
  297. var reply interface{}
  298. for i := 0; i <= pending; i++ {
  299. var e error
  300. if reply, e = c.readReply(); e != nil {
  301. return nil, c.fatal(e)
  302. }
  303. if e, ok := reply.(Error); ok && err == nil {
  304. err = e
  305. }
  306. }
  307. return reply, err
  308. }