conn.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 [32]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. dialer := xDialer{}
  48. return dialer.Dial(network, address)
  49. }
  50. // DialTimeout acts like Dial but takes timeouts for establishing the
  51. // connection to the server, writing a command and reading a reply.
  52. func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
  53. netDialer := net.Dialer{Timeout: connectTimeout}
  54. dialer := xDialer{
  55. NetDial: netDialer.Dial,
  56. ReadTimeout: readTimeout,
  57. WriteTimeout: writeTimeout,
  58. }
  59. return dialer.Dial(network, address)
  60. }
  61. // A Dialer specifies options for connecting to a Redis server.
  62. type xDialer struct {
  63. // NetDial specifies the dial function for creating TCP connections. If
  64. // NetDial is nil, then net.Dial is used.
  65. NetDial func(network, addr string) (net.Conn, error)
  66. // ReadTimeout specifies the timeout for reading a single command
  67. // reply. If ReadTimeout is zero, then no timeout is used.
  68. ReadTimeout time.Duration
  69. // WriteTimeout specifies the timeout for writing a single command. If
  70. // WriteTimeout is zero, then no timeout is used.
  71. WriteTimeout time.Duration
  72. }
  73. // Dial connects to the Redis server at address on the named network.
  74. func (d *xDialer) Dial(network, address string) (Conn, error) {
  75. dial := d.NetDial
  76. if dial == nil {
  77. dial = net.Dial
  78. }
  79. netConn, err := dial(network, address)
  80. if err != nil {
  81. return nil, err
  82. }
  83. return &conn{
  84. conn: netConn,
  85. bw: bufio.NewWriter(netConn),
  86. br: bufio.NewReader(netConn),
  87. readTimeout: d.ReadTimeout,
  88. writeTimeout: d.WriteTimeout,
  89. }, nil
  90. }
  91. // NewConn returns a new Redigo connection for the given net connection.
  92. func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn {
  93. return &conn{
  94. conn: netConn,
  95. bw: bufio.NewWriter(netConn),
  96. br: bufio.NewReader(netConn),
  97. readTimeout: readTimeout,
  98. writeTimeout: writeTimeout,
  99. }
  100. }
  101. func (c *conn) Close() error {
  102. c.mu.Lock()
  103. err := c.err
  104. if c.err == nil {
  105. c.err = errors.New("redigo: closed")
  106. err = c.conn.Close()
  107. }
  108. c.mu.Unlock()
  109. return err
  110. }
  111. func (c *conn) fatal(err error) error {
  112. c.mu.Lock()
  113. if c.err == nil {
  114. c.err = err
  115. // Close connection to force errors on subsequent calls and to unblock
  116. // other reader or writer.
  117. c.conn.Close()
  118. }
  119. c.mu.Unlock()
  120. return err
  121. }
  122. func (c *conn) Err() error {
  123. c.mu.Lock()
  124. err := c.err
  125. c.mu.Unlock()
  126. return err
  127. }
  128. func (c *conn) writeLen(prefix byte, n int) error {
  129. c.lenScratch[len(c.lenScratch)-1] = '\n'
  130. c.lenScratch[len(c.lenScratch)-2] = '\r'
  131. i := len(c.lenScratch) - 3
  132. for {
  133. c.lenScratch[i] = byte('0' + n%10)
  134. i -= 1
  135. n = n / 10
  136. if n == 0 {
  137. break
  138. }
  139. }
  140. c.lenScratch[i] = prefix
  141. _, err := c.bw.Write(c.lenScratch[i:])
  142. return err
  143. }
  144. func (c *conn) writeString(s string) error {
  145. c.writeLen('$', len(s))
  146. c.bw.WriteString(s)
  147. _, err := c.bw.WriteString("\r\n")
  148. return err
  149. }
  150. func (c *conn) writeBytes(p []byte) error {
  151. c.writeLen('$', len(p))
  152. c.bw.Write(p)
  153. _, err := c.bw.WriteString("\r\n")
  154. return err
  155. }
  156. func (c *conn) writeInt64(n int64) error {
  157. return c.writeBytes(strconv.AppendInt(c.numScratch[:0], n, 10))
  158. }
  159. func (c *conn) writeFloat64(n float64) error {
  160. return c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64))
  161. }
  162. func (c *conn) writeCommand(cmd string, args []interface{}) (err error) {
  163. c.writeLen('*', 1+len(args))
  164. err = c.writeString(cmd)
  165. for _, arg := range args {
  166. if err != nil {
  167. break
  168. }
  169. switch arg := arg.(type) {
  170. case string:
  171. err = c.writeString(arg)
  172. case []byte:
  173. err = c.writeBytes(arg)
  174. case int:
  175. err = c.writeInt64(int64(arg))
  176. case int64:
  177. err = c.writeInt64(arg)
  178. case float64:
  179. err = c.writeFloat64(arg)
  180. case bool:
  181. if arg {
  182. err = c.writeString("1")
  183. } else {
  184. err = c.writeString("0")
  185. }
  186. case nil:
  187. err = c.writeString("")
  188. default:
  189. var buf bytes.Buffer
  190. fmt.Fprint(&buf, arg)
  191. err = c.writeBytes(buf.Bytes())
  192. }
  193. }
  194. return err
  195. }
  196. type protocolError string
  197. func (pe protocolError) Error() string {
  198. return fmt.Sprintf("redigo: %s (possible server error or unsupported concurrent read by application)", string(pe))
  199. }
  200. func (c *conn) readLine() ([]byte, error) {
  201. p, err := c.br.ReadSlice('\n')
  202. if err == bufio.ErrBufferFull {
  203. return nil, protocolError("long response line")
  204. }
  205. if err != nil {
  206. return nil, err
  207. }
  208. i := len(p) - 2
  209. if i < 0 || p[i] != '\r' {
  210. return nil, protocolError("bad response line terminator")
  211. }
  212. return p[:i], nil
  213. }
  214. // parseLen parses bulk string and array lengths.
  215. func parseLen(p []byte) (int, error) {
  216. if len(p) == 0 {
  217. return -1, protocolError("malformed length")
  218. }
  219. if p[0] == '-' && len(p) == 2 && p[1] == '1' {
  220. // handle $-1 and $-1 null replies.
  221. return -1, nil
  222. }
  223. var n int
  224. for _, b := range p {
  225. n *= 10
  226. if b < '0' || b > '9' {
  227. return -1, protocolError("illegal bytes in length")
  228. }
  229. n += int(b - '0')
  230. }
  231. return n, nil
  232. }
  233. // parseInt parses an integer reply.
  234. func parseInt(p []byte) (interface{}, error) {
  235. if len(p) == 0 {
  236. return 0, protocolError("malformed integer")
  237. }
  238. var negate bool
  239. if p[0] == '-' {
  240. negate = true
  241. p = p[1:]
  242. if len(p) == 0 {
  243. return 0, protocolError("malformed integer")
  244. }
  245. }
  246. var n int64
  247. for _, b := range p {
  248. n *= 10
  249. if b < '0' || b > '9' {
  250. return 0, protocolError("illegal bytes in length")
  251. }
  252. n += int64(b - '0')
  253. }
  254. if negate {
  255. n = -n
  256. }
  257. return n, nil
  258. }
  259. var (
  260. okReply interface{} = "OK"
  261. pongReply interface{} = "PONG"
  262. )
  263. func (c *conn) readReply() (interface{}, error) {
  264. line, err := c.readLine()
  265. if err != nil {
  266. return nil, err
  267. }
  268. if len(line) == 0 {
  269. return nil, protocolError("short response line")
  270. }
  271. switch line[0] {
  272. case '+':
  273. switch {
  274. case len(line) == 3 && line[1] == 'O' && line[2] == 'K':
  275. // Avoid allocation for frequent "+OK" response.
  276. return okReply, nil
  277. case len(line) == 5 && line[1] == 'P' && line[2] == 'O' && line[3] == 'N' && line[4] == 'G':
  278. // Avoid allocation in PING command benchmarks :)
  279. return pongReply, nil
  280. default:
  281. return string(line[1:]), nil
  282. }
  283. case '-':
  284. return Error(string(line[1:])), nil
  285. case ':':
  286. return parseInt(line[1:])
  287. case '$':
  288. n, err := parseLen(line[1:])
  289. if n < 0 || err != nil {
  290. return nil, err
  291. }
  292. p := make([]byte, n)
  293. _, err = io.ReadFull(c.br, p)
  294. if err != nil {
  295. return nil, err
  296. }
  297. if line, err := c.readLine(); err != nil {
  298. return nil, err
  299. } else if len(line) != 0 {
  300. return nil, protocolError("bad bulk string format")
  301. }
  302. return p, nil
  303. case '*':
  304. n, err := parseLen(line[1:])
  305. if n < 0 || err != nil {
  306. return nil, err
  307. }
  308. r := make([]interface{}, n)
  309. for i := range r {
  310. r[i], err = c.readReply()
  311. if err != nil {
  312. return nil, err
  313. }
  314. }
  315. return r, nil
  316. }
  317. return nil, protocolError("unexpected response line")
  318. }
  319. func (c *conn) Send(cmd string, args ...interface{}) error {
  320. c.mu.Lock()
  321. c.pending += 1
  322. c.mu.Unlock()
  323. if c.writeTimeout != 0 {
  324. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  325. }
  326. if err := c.writeCommand(cmd, args); err != nil {
  327. return c.fatal(err)
  328. }
  329. return nil
  330. }
  331. func (c *conn) Flush() error {
  332. if c.writeTimeout != 0 {
  333. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  334. }
  335. if err := c.bw.Flush(); err != nil {
  336. return c.fatal(err)
  337. }
  338. return nil
  339. }
  340. func (c *conn) Receive() (reply interface{}, err error) {
  341. if c.readTimeout != 0 {
  342. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  343. }
  344. if reply, err = c.readReply(); err != nil {
  345. return nil, c.fatal(err)
  346. }
  347. // When using pub/sub, the number of receives can be greater than the
  348. // number of sends. To enable normal use of the connection after
  349. // unsubscribing from all channels, we do not decrement pending to a
  350. // negative value.
  351. //
  352. // The pending field is decremented after the reply is read to handle the
  353. // case where Receive is called before Send.
  354. c.mu.Lock()
  355. if c.pending > 0 {
  356. c.pending -= 1
  357. }
  358. c.mu.Unlock()
  359. if err, ok := reply.(Error); ok {
  360. return nil, err
  361. }
  362. return
  363. }
  364. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  365. c.mu.Lock()
  366. pending := c.pending
  367. c.pending = 0
  368. c.mu.Unlock()
  369. if cmd == "" && pending == 0 {
  370. return nil, nil
  371. }
  372. if c.writeTimeout != 0 {
  373. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  374. }
  375. if cmd != "" {
  376. c.writeCommand(cmd, args)
  377. }
  378. if err := c.bw.Flush(); err != nil {
  379. return nil, c.fatal(err)
  380. }
  381. if c.readTimeout != 0 {
  382. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  383. }
  384. if cmd == "" {
  385. reply := make([]interface{}, pending)
  386. for i := range reply {
  387. r, e := c.readReply()
  388. if e != nil {
  389. return nil, c.fatal(e)
  390. }
  391. reply[i] = r
  392. }
  393. return reply, nil
  394. }
  395. var err error
  396. var reply interface{}
  397. for i := 0; i <= pending; i++ {
  398. var e error
  399. if reply, e = c.readReply(); e != nil {
  400. return nil, c.fatal(e)
  401. }
  402. if e, ok := reply.(Error); ok && err == nil {
  403. err = e
  404. }
  405. }
  406. return reply, err
  407. }