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.

305 lines
6.9 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. if _, ok := reqres.Request.(tmsp.RequestFlush); ok {
  95. err = app.bufWriter.Flush()
  96. if err != nil {
  97. app.StopForError(err)
  98. return
  99. }
  100. }
  101. }
  102. }
  103. }
  104. func (app *remoteAppConn) recvResponseRoutine() {
  105. r := bufio.NewReader(app.conn) // Buffer reads
  106. for {
  107. var res tmsp.Response
  108. var n int
  109. var err error
  110. wire.ReadBinaryPtrLengthPrefixed(&res, r, maxResponseSize, &n, &err)
  111. if err != nil {
  112. app.StopForError(err)
  113. return
  114. }
  115. switch res := res.(type) {
  116. case tmsp.ResponseException:
  117. app.StopForError(errors.New(res.Error))
  118. default:
  119. err := app.didRecvResponse(res)
  120. if err != nil {
  121. app.StopForError(err)
  122. }
  123. }
  124. }
  125. }
  126. func (app *remoteAppConn) willSendReq(reqres *reqRes) {
  127. app.mtx.Lock()
  128. defer app.mtx.Unlock()
  129. app.reqSent.PushBack(reqres)
  130. }
  131. func (app *remoteAppConn) didRecvResponse(res tmsp.Response) error {
  132. app.mtx.Lock()
  133. defer app.mtx.Unlock()
  134. // Special logic for events which have no corresponding requests.
  135. if _, ok := res.(tmsp.ResponseEvent); ok && app.resCb != nil {
  136. app.resCb(nil, res)
  137. return nil
  138. }
  139. // Get the first reqRes
  140. next := app.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. app.reqSent.Remove(next) // Pop first item from linked list
  152. // Callback if there is a listener
  153. if app.resCb != nil {
  154. app.resCb(reqres.Request, res)
  155. }
  156. return nil
  157. }
  158. //----------------------------------------
  159. func (app *remoteAppConn) EchoAsync(msg string) {
  160. app.queueRequest(tmsp.RequestEcho{msg})
  161. }
  162. func (app *remoteAppConn) FlushAsync() {
  163. app.queueRequest(tmsp.RequestFlush{})
  164. }
  165. func (app *remoteAppConn) SetOptionAsync(key string, value string) {
  166. app.queueRequest(tmsp.RequestSetOption{key, value})
  167. }
  168. func (app *remoteAppConn) AppendTxAsync(tx []byte) {
  169. app.queueRequest(tmsp.RequestAppendTx{tx})
  170. }
  171. func (app *remoteAppConn) CheckTxAsync(tx []byte) {
  172. app.queueRequest(tmsp.RequestCheckTx{tx})
  173. }
  174. func (app *remoteAppConn) GetHashAsync() {
  175. app.queueRequest(tmsp.RequestGetHash{})
  176. }
  177. func (app *remoteAppConn) AddListenerAsync(key string) {
  178. app.queueRequest(tmsp.RequestAddListener{key})
  179. }
  180. func (app *remoteAppConn) RemListenerAsync(key string) {
  181. app.queueRequest(tmsp.RequestRemListener{key})
  182. }
  183. //----------------------------------------
  184. func (app *remoteAppConn) InfoSync() (info []string, err error) {
  185. reqres := app.queueRequest(tmsp.RequestInfo{})
  186. app.FlushSync()
  187. if app.err != nil {
  188. return nil, app.err
  189. }
  190. return reqres.Response.(tmsp.ResponseInfo).Data, nil
  191. }
  192. func (app *remoteAppConn) FlushSync() error {
  193. app.queueRequest(tmsp.RequestFlush{}).Wait()
  194. return app.err
  195. }
  196. func (app *remoteAppConn) GetHashSync() (hash []byte, err error) {
  197. reqres := app.queueRequest(tmsp.RequestGetHash{})
  198. app.FlushSync()
  199. if app.err != nil {
  200. return nil, app.err
  201. }
  202. return reqres.Response.(tmsp.ResponseGetHash).Hash, nil
  203. }
  204. //----------------------------------------
  205. func (app *remoteAppConn) queueRequest(req tmsp.Request) *reqRes {
  206. reqres := newReqRes(req)
  207. // TODO: set app.err if reqQueue times out
  208. app.reqQueue <- reqres
  209. // Maybe auto-flush, or unset auto-flush
  210. switch req.(type) {
  211. case tmsp.RequestFlush:
  212. app.flushTimer.Unset()
  213. default:
  214. app.flushTimer.Set()
  215. }
  216. return reqres
  217. }
  218. //----------------------------------------
  219. func resMatchesReq(req tmsp.Request, res tmsp.Response) (ok bool) {
  220. switch req.(type) {
  221. case tmsp.RequestEcho:
  222. _, ok = res.(tmsp.ResponseEcho)
  223. case tmsp.RequestFlush:
  224. _, ok = res.(tmsp.ResponseFlush)
  225. case tmsp.RequestInfo:
  226. _, ok = res.(tmsp.ResponseInfo)
  227. case tmsp.RequestSetOption:
  228. _, ok = res.(tmsp.ResponseSetOption)
  229. case tmsp.RequestAppendTx:
  230. _, ok = res.(tmsp.ResponseAppendTx)
  231. case tmsp.RequestCheckTx:
  232. _, ok = res.(tmsp.ResponseCheckTx)
  233. case tmsp.RequestGetHash:
  234. _, ok = res.(tmsp.ResponseGetHash)
  235. case tmsp.RequestAddListener:
  236. _, ok = res.(tmsp.ResponseAddListener)
  237. case tmsp.RequestRemListener:
  238. _, ok = res.(tmsp.ResponseRemListener)
  239. default:
  240. return false
  241. }
  242. return
  243. }
  244. type reqRes struct {
  245. tmsp.Request
  246. *sync.WaitGroup
  247. tmsp.Response // Not set atomically, so be sure to use WaitGroup.
  248. }
  249. func newReqRes(req tmsp.Request) *reqRes {
  250. return &reqRes{
  251. Request: req,
  252. WaitGroup: waitGroup1(),
  253. Response: nil,
  254. }
  255. }
  256. func waitGroup1() (wg *sync.WaitGroup) {
  257. wg = &sync.WaitGroup{}
  258. wg.Add(1)
  259. return
  260. }