conn.go 8.5 KB

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