conn.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. c, err := net.Dial(network, address)
  48. if err != nil {
  49. return nil, err
  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, err
  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. c.mu.Lock()
  80. err := c.err
  81. if c.err == nil {
  82. c.err = errors.New("redigo: closed")
  83. err = c.conn.Close()
  84. }
  85. c.mu.Unlock()
  86. return err
  87. }
  88. func (c *conn) fatal(err error) error {
  89. c.mu.Lock()
  90. if c.err == nil {
  91. c.err = err
  92. // Close connection to force errors on subsequent calls and to unblock
  93. // other reader or writer.
  94. c.conn.Close()
  95. }
  96. c.mu.Unlock()
  97. return err
  98. }
  99. func (c *conn) Err() error {
  100. c.mu.Lock()
  101. err := c.err
  102. c.mu.Unlock()
  103. return err
  104. }
  105. func (c *conn) writeLen(prefix byte, n int) error {
  106. c.lenScratch[len(c.lenScratch)-1] = '\n'
  107. c.lenScratch[len(c.lenScratch)-2] = '\r'
  108. i := len(c.lenScratch) - 3
  109. for {
  110. c.lenScratch[i] = byte('0' + n%10)
  111. i -= 1
  112. n = n / 10
  113. if n == 0 {
  114. break
  115. }
  116. }
  117. c.lenScratch[i] = prefix
  118. _, err := c.bw.Write(c.lenScratch[i:])
  119. return err
  120. }
  121. func (c *conn) writeString(s string) error {
  122. c.writeLen('$', len(s))
  123. c.bw.WriteString(s)
  124. _, err := c.bw.WriteString("\r\n")
  125. return err
  126. }
  127. func (c *conn) writeBytes(p []byte) error {
  128. c.writeLen('$', len(p))
  129. c.bw.Write(p)
  130. _, err := c.bw.WriteString("\r\n")
  131. return err
  132. }
  133. func (c *conn) writeInt64(n int64) error {
  134. return c.writeBytes(strconv.AppendInt(c.numScratch[:0], n, 10))
  135. }
  136. func (c *conn) writeFloat64(n float64) error {
  137. return c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64))
  138. }
  139. func (c *conn) writeCommand(cmd string, args []interface{}) (err error) {
  140. c.writeLen('*', 1+len(args))
  141. err = c.writeString(cmd)
  142. for _, arg := range args {
  143. if err != nil {
  144. break
  145. }
  146. switch arg := arg.(type) {
  147. case string:
  148. err = c.writeString(arg)
  149. case []byte:
  150. err = c.writeBytes(arg)
  151. case int:
  152. err = c.writeInt64(int64(arg))
  153. case int64:
  154. err = c.writeInt64(arg)
  155. case float64:
  156. err = c.writeFloat64(arg)
  157. case bool:
  158. if arg {
  159. err = c.writeString("1")
  160. } else {
  161. err = c.writeString("0")
  162. }
  163. case nil:
  164. err = c.writeString("")
  165. default:
  166. var buf bytes.Buffer
  167. fmt.Fprint(&buf, arg)
  168. err = c.writeBytes(buf.Bytes())
  169. }
  170. }
  171. return err
  172. }
  173. func (c *conn) readLine() ([]byte, error) {
  174. p, err := c.br.ReadSlice('\n')
  175. if err == bufio.ErrBufferFull {
  176. return nil, errors.New("redigo: long response line")
  177. }
  178. if err != nil {
  179. return nil, err
  180. }
  181. i := len(p) - 2
  182. if i < 0 || p[i] != '\r' {
  183. return nil, errors.New("redigo: bad response line terminator")
  184. }
  185. return p[:i], nil
  186. }
  187. // parseLen parses bulk and multi-bulk lengths.
  188. func parseLen(p []byte) (int, error) {
  189. if len(p) == 0 {
  190. return -1, errors.New("redigo: malformed length")
  191. }
  192. if p[0] == '-' && len(p) == 2 && p[1] == '1' {
  193. // handle $-1 and $-1 null replies.
  194. return -1, nil
  195. }
  196. var n int
  197. for _, b := range p {
  198. n *= 10
  199. if b < '0' || b > '9' {
  200. return -1, errors.New("redigo: illegal bytes in length")
  201. }
  202. n += int(b - '0')
  203. }
  204. return n, nil
  205. }
  206. // parseInt parses an integer reply.
  207. func parseInt(p []byte) (interface{}, error) {
  208. if len(p) == 0 {
  209. return 0, errors.New("redigo: malformed integer")
  210. }
  211. var negate bool
  212. if p[0] == '-' {
  213. negate = true
  214. p = p[1:]
  215. if len(p) == 0 {
  216. return 0, errors.New("redigo: malformed integer")
  217. }
  218. }
  219. var n int64
  220. for _, b := range p {
  221. n *= 10
  222. if b < '0' || b > '9' {
  223. return 0, errors.New("redigo: illegal bytes in length")
  224. }
  225. n += int64(b - '0')
  226. }
  227. if negate {
  228. n = -n
  229. }
  230. return n, nil
  231. }
  232. var (
  233. okReply interface{} = "OK"
  234. pongReply interface{} = "PONG"
  235. )
  236. func (c *conn) readReply() (interface{}, error) {
  237. line, err := c.readLine()
  238. if err != nil {
  239. return nil, err
  240. }
  241. if len(line) == 0 {
  242. return nil, errors.New("redigo: short response line")
  243. }
  244. switch line[0] {
  245. case '+':
  246. switch {
  247. case len(line) == 3 && line[1] == 'O' && line[2] == 'K':
  248. // Avoid allocation for frequent "+OK" response.
  249. return okReply, nil
  250. case len(line) == 5 && line[1] == 'P' && line[2] == 'O' && line[3] == 'N' && line[4] == 'G':
  251. // Avoid allocation in PING command benchmarks :)
  252. return pongReply, nil
  253. default:
  254. return string(line[1:]), nil
  255. }
  256. case '-':
  257. return Error(string(line[1:])), nil
  258. case ':':
  259. return parseInt(line[1:])
  260. case '$':
  261. n, err := parseLen(line[1:])
  262. if n < 0 {
  263. return nil, err
  264. }
  265. p := make([]byte, n)
  266. _, err = io.ReadFull(c.br, p)
  267. if err != nil {
  268. return nil, err
  269. }
  270. if line, err := c.readLine(); err != nil {
  271. return nil, err
  272. } else if len(line) != 0 {
  273. return nil, errors.New("redigo: bad bulk format")
  274. }
  275. return p, nil
  276. case '*':
  277. n, err := parseLen(line[1:])
  278. if n < 0 {
  279. return nil, err
  280. }
  281. r := make([]interface{}, n)
  282. for i := range r {
  283. r[i], err = c.readReply()
  284. if err != nil {
  285. return nil, err
  286. }
  287. }
  288. return r, nil
  289. }
  290. return nil, errors.New("redigo: unexpected response line")
  291. }
  292. func (c *conn) Send(cmd string, args ...interface{}) error {
  293. c.mu.Lock()
  294. c.pending += 1
  295. c.mu.Unlock()
  296. if c.writeTimeout != 0 {
  297. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  298. }
  299. if err := c.writeCommand(cmd, args); err != nil {
  300. return c.fatal(err)
  301. }
  302. return nil
  303. }
  304. func (c *conn) Flush() error {
  305. if c.writeTimeout != 0 {
  306. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  307. }
  308. if err := c.bw.Flush(); err != nil {
  309. return c.fatal(err)
  310. }
  311. return nil
  312. }
  313. func (c *conn) Receive() (reply interface{}, err error) {
  314. c.mu.Lock()
  315. // There can be more receives than sends when using pub/sub. To allow
  316. // normal use of the connection after unsubscribe from all channels, do not
  317. // decrement pending to a negative value.
  318. if c.pending > 0 {
  319. c.pending -= 1
  320. }
  321. c.mu.Unlock()
  322. if c.readTimeout != 0 {
  323. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  324. }
  325. if reply, err = c.readReply(); err != nil {
  326. return nil, c.fatal(err)
  327. }
  328. if err, ok := reply.(Error); ok {
  329. return nil, err
  330. }
  331. return
  332. }
  333. func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
  334. if c.writeTimeout != 0 {
  335. c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
  336. }
  337. if cmd != "" {
  338. c.writeCommand(cmd, args)
  339. }
  340. if err := c.bw.Flush(); err != nil {
  341. return nil, c.fatal(err)
  342. }
  343. c.mu.Lock()
  344. pending := c.pending
  345. c.pending = 0
  346. c.mu.Unlock()
  347. if c.readTimeout != 0 {
  348. c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
  349. }
  350. if cmd == "" {
  351. reply := make([]interface{}, pending)
  352. for i := range reply {
  353. r, e := c.readReply()
  354. if e != nil {
  355. return nil, c.fatal(e)
  356. }
  357. reply[i] = r
  358. }
  359. return reply, nil
  360. }
  361. var err error
  362. var reply interface{}
  363. for i := 0; i <= pending; i++ {
  364. var e error
  365. if reply, e = c.readReply(); e != nil {
  366. return nil, c.fatal(e)
  367. }
  368. if e, ok := reply.(Error); ok && err == nil {
  369. err = e
  370. }
  371. }
  372. return reply, err
  373. }