You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

330 lines
7.9 KiB

  1. package tmspcli
  2. import (
  3. "bufio"
  4. "container/list"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "reflect"
  9. "sync"
  10. . "github.com/tendermint/go-common"
  11. "github.com/tendermint/go-wire"
  12. tmsp "github.com/tendermint/tmsp/types"
  13. )
  14. const maxResponseSize = 1048576 // 1MB TODO make configurable
  15. const flushThrottleMS = 20 // Don't wait longer than...
  16. type Callback func(tmsp.Request, tmsp.Response)
  17. // This is goroutine-safe, but users should beware that
  18. // the application in general is not meant to be interfaced
  19. // with concurrent callers.
  20. type TMSPClient struct {
  21. QuitService
  22. sync.Mutex // [EB]: is this even used?
  23. reqQueue chan *reqRes
  24. flushTimer *ThrottleTimer
  25. mtx sync.Mutex
  26. conn net.Conn
  27. bufWriter *bufio.Writer
  28. err error
  29. reqSent *list.List
  30. resCb func(tmsp.Request, tmsp.Response)
  31. }
  32. func NewTMSPClient(conn net.Conn, bufferSize int) *TMSPClient {
  33. cli := &TMSPClient{
  34. reqQueue: make(chan *reqRes, bufferSize),
  35. flushTimer: NewThrottleTimer("TMSPClient", flushThrottleMS),
  36. conn: conn,
  37. bufWriter: bufio.NewWriter(conn),
  38. reqSent: list.New(),
  39. resCb: nil,
  40. }
  41. cli.QuitService = *NewQuitService(nil, "TMSPClient", cli)
  42. cli.Start() // Just start it, it's confusing for callers to remember to start.
  43. return cli
  44. }
  45. func (cli *TMSPClient) OnStart() error {
  46. cli.QuitService.OnStart()
  47. go cli.sendRequestsRoutine()
  48. go cli.recvResponseRoutine()
  49. return nil
  50. }
  51. func (cli *TMSPClient) OnStop() {
  52. cli.QuitService.OnStop()
  53. cli.conn.Close()
  54. }
  55. // NOTE: callback may get internally generated flush responses.
  56. func (cli *TMSPClient) SetResponseCallback(resCb Callback) {
  57. cli.mtx.Lock()
  58. defer cli.mtx.Unlock()
  59. cli.resCb = resCb
  60. }
  61. func (cli *TMSPClient) StopForError(err error) {
  62. cli.mtx.Lock()
  63. // log.Error("Stopping TMSPClient for error.", "error", err)
  64. if cli.err == nil {
  65. cli.err = err
  66. }
  67. cli.mtx.Unlock()
  68. cli.Stop()
  69. }
  70. func (cli *TMSPClient) Error() error {
  71. cli.mtx.Lock()
  72. defer cli.mtx.Unlock()
  73. return cli.err
  74. }
  75. //----------------------------------------
  76. func (cli *TMSPClient) sendRequestsRoutine() {
  77. for {
  78. var n int
  79. var err error
  80. select {
  81. case <-cli.flushTimer.Ch:
  82. select {
  83. case cli.reqQueue <- newReqRes(tmsp.RequestFlush{}):
  84. default:
  85. // Probably will fill the buffer, or retry later.
  86. }
  87. case <-cli.QuitService.Quit:
  88. return
  89. case reqres := <-cli.reqQueue:
  90. cli.willSendReq(reqres)
  91. wire.WriteBinaryLengthPrefixed(struct{ tmsp.Request }{reqres.Request}, cli.bufWriter, &n, &err) // Length prefix
  92. if err != nil {
  93. cli.StopForError(err)
  94. return
  95. }
  96. // log.Debug("Sent request", "requestType", reflect.TypeOf(reqres.Request), "request", reqres.Request)
  97. if _, ok := reqres.Request.(tmsp.RequestFlush); ok {
  98. err = cli.bufWriter.Flush()
  99. if err != nil {
  100. cli.StopForError(err)
  101. return
  102. }
  103. }
  104. }
  105. }
  106. }
  107. func (cli *TMSPClient) recvResponseRoutine() {
  108. r := bufio.NewReader(cli.conn) // Buffer reads
  109. for {
  110. var res tmsp.Response
  111. var n int
  112. var err error
  113. wire.ReadBinaryPtrLengthPrefixed(&res, r, maxResponseSize, &n, &err)
  114. if err != nil {
  115. cli.StopForError(err)
  116. return
  117. }
  118. switch res := res.(type) {
  119. case tmsp.ResponseException:
  120. // XXX After setting cli.err, release waiters (e.g. reqres.Done())
  121. cli.StopForError(errors.New(res.Error))
  122. default:
  123. // log.Debug("Received response", "responseType", reflect.TypeOf(res), "response", res)
  124. err := cli.didRecvResponse(res)
  125. if err != nil {
  126. cli.StopForError(err)
  127. }
  128. }
  129. }
  130. }
  131. func (cli *TMSPClient) willSendReq(reqres *reqRes) {
  132. cli.mtx.Lock()
  133. defer cli.mtx.Unlock()
  134. cli.reqSent.PushBack(reqres)
  135. }
  136. func (cli *TMSPClient) didRecvResponse(res tmsp.Response) error {
  137. cli.mtx.Lock()
  138. defer cli.mtx.Unlock()
  139. // Get the first reqRes
  140. next := cli.reqSent.Front()
  141. if next == nil {
  142. return fmt.Errorf("Unexpected result type %v when nothing expected", reflect.TypeOf(res))
  143. }
  144. reqres := next.Value.(*reqRes)
  145. if !resMatchesReq(reqres.Request, res) {
  146. return fmt.Errorf("Unexpected result type %v when response to %v expected",
  147. reflect.TypeOf(res), reflect.TypeOf(reqres.Request))
  148. }
  149. reqres.Response = res // Set response
  150. reqres.Done() // Release waiters
  151. cli.reqSent.Remove(next) // Pop first item from linked list
  152. // Callback if there is a listener
  153. if cli.resCb != nil {
  154. cli.resCb(reqres.Request, res)
  155. }
  156. return nil
  157. }
  158. //----------------------------------------
  159. func (cli *TMSPClient) EchoAsync(msg string) {
  160. cli.queueRequest(tmsp.RequestEcho{msg})
  161. }
  162. func (cli *TMSPClient) FlushAsync() {
  163. cli.queueRequest(tmsp.RequestFlush{})
  164. }
  165. func (cli *TMSPClient) SetOptionAsync(key string, value string) {
  166. cli.queueRequest(tmsp.RequestSetOption{key, value})
  167. }
  168. func (cli *TMSPClient) AppendTxAsync(tx []byte) {
  169. cli.queueRequest(tmsp.RequestAppendTx{tx})
  170. }
  171. func (cli *TMSPClient) CheckTxAsync(tx []byte) {
  172. cli.queueRequest(tmsp.RequestCheckTx{tx})
  173. }
  174. func (cli *TMSPClient) GetHashAsync() {
  175. cli.queueRequest(tmsp.RequestGetHash{})
  176. }
  177. func (cli *TMSPClient) QueryAsync(query []byte) {
  178. cli.queueRequest(tmsp.RequestQuery{query})
  179. }
  180. //----------------------------------------
  181. func (cli *TMSPClient) InfoSync() (info string, err error) {
  182. reqres := cli.queueRequest(tmsp.RequestInfo{})
  183. cli.FlushSync()
  184. if cli.err != nil {
  185. return "", cli.err
  186. }
  187. return reqres.Response.(tmsp.ResponseInfo).Info, nil
  188. }
  189. func (cli *TMSPClient) FlushSync() error {
  190. cli.queueRequest(tmsp.RequestFlush{}).Wait()
  191. return cli.err
  192. }
  193. func (cli *TMSPClient) AppendTxSync(tx []byte) (code tmsp.RetCode, result []byte, log string, err error) {
  194. reqres := cli.queueRequest(tmsp.RequestAppendTx{tx})
  195. cli.FlushSync()
  196. if cli.err != nil {
  197. return tmsp.RetCodeInternalError, nil, "", cli.err
  198. }
  199. res := reqres.Response.(tmsp.ResponseAppendTx)
  200. return res.Code, res.Result, res.Log, nil
  201. }
  202. func (cli *TMSPClient) CheckTxSync(tx []byte) (code tmsp.RetCode, result []byte, log string, err error) {
  203. reqres := cli.queueRequest(tmsp.RequestCheckTx{tx})
  204. cli.FlushSync()
  205. if cli.err != nil {
  206. return tmsp.RetCodeInternalError, nil, "", cli.err
  207. }
  208. res := reqres.Response.(tmsp.ResponseCheckTx)
  209. return res.Code, res.Result, res.Log, nil
  210. }
  211. func (cli *TMSPClient) GetHashSync() (hash []byte, log string, err error) {
  212. reqres := cli.queueRequest(tmsp.RequestGetHash{})
  213. cli.FlushSync()
  214. if cli.err != nil {
  215. return nil, "", cli.err
  216. }
  217. res := reqres.Response.(tmsp.ResponseGetHash)
  218. return res.Hash, res.Log, nil
  219. }
  220. func (cli *TMSPClient) QuerySync(query []byte) (result []byte, log string, err error) {
  221. reqres := cli.queueRequest(tmsp.RequestQuery{query})
  222. cli.FlushSync()
  223. if cli.err != nil {
  224. return nil, "", cli.err
  225. }
  226. res := reqres.Response.(tmsp.ResponseQuery)
  227. return res.Result, res.Log, nil
  228. }
  229. //----------------------------------------
  230. func (cli *TMSPClient) queueRequest(req tmsp.Request) *reqRes {
  231. reqres := newReqRes(req)
  232. // TODO: set cli.err if reqQueue times out
  233. cli.reqQueue <- reqres
  234. // Maybe auto-flush, or unset auto-flush
  235. switch req.(type) {
  236. case tmsp.RequestFlush:
  237. cli.flushTimer.Unset()
  238. default:
  239. cli.flushTimer.Set()
  240. }
  241. return reqres
  242. }
  243. //----------------------------------------
  244. func resMatchesReq(req tmsp.Request, res tmsp.Response) (ok bool) {
  245. switch req.(type) {
  246. case tmsp.RequestEcho:
  247. _, ok = res.(tmsp.ResponseEcho)
  248. case tmsp.RequestFlush:
  249. _, ok = res.(tmsp.ResponseFlush)
  250. case tmsp.RequestInfo:
  251. _, ok = res.(tmsp.ResponseInfo)
  252. case tmsp.RequestSetOption:
  253. _, ok = res.(tmsp.ResponseSetOption)
  254. case tmsp.RequestAppendTx:
  255. _, ok = res.(tmsp.ResponseAppendTx)
  256. case tmsp.RequestCheckTx:
  257. _, ok = res.(tmsp.ResponseCheckTx)
  258. case tmsp.RequestGetHash:
  259. _, ok = res.(tmsp.ResponseGetHash)
  260. case tmsp.RequestQuery:
  261. _, ok = res.(tmsp.ResponseQuery)
  262. default:
  263. return false
  264. }
  265. return
  266. }
  267. type reqRes struct {
  268. tmsp.Request
  269. *sync.WaitGroup
  270. tmsp.Response // Not set atomically, so be sure to use WaitGroup.
  271. }
  272. func newReqRes(req tmsp.Request) *reqRes {
  273. return &reqRes{
  274. Request: req,
  275. WaitGroup: waitGroup1(),
  276. Response: nil,
  277. }
  278. }
  279. func waitGroup1() (wg *sync.WaitGroup) {
  280. wg = &sync.WaitGroup{}
  281. wg.Add(1)
  282. return
  283. }