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.

307 lines
7.1 KiB

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