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.

586 lines
15 KiB

abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
9 years ago
9 years ago
9 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
abci: Flush socket requests and responses immediately. (#6997) The main effect of this change is to flush the socket client and server message encoding buffers immediately once the message is fully and correctly encoded. This allows us to remove the timer and some other special cases, without changing the observed behaviour of the system. -- Background The socket protocol client and server each use a buffered writer to encode request and response messages onto the underlying connection. This reduces the possibility of a single message being split across multiple writes, but has the side-effect that a request may remain buffered for some time. The implementation worked around this by keeping a ticker that occasionally triggers a flush, and by flushing the writer in response to an explicit request baked into the client/server protocol (see also #6994). These workarounds are both unnecessary: Once a message has been dequeued for sending and fully encoded in wire format, there is no real use keeping all or part of it buffered locally. Moreover, using an asynchronous process to flush the buffer makes the round-trip performance of the request unpredictable. -- Benchmarks Code: https://play.golang.org/p/0ChUOxJOiHt I found no pre-existing performance benchmarks to justify the flush pattern, but a natural question is whether this will significantly harm client/server performance. To test this, I implemented a simple benchmark that transfers randomly-sized byte buffers from a no-op "client" to a no-op "server" over a Unix-domain socket, using a buffered writer, both with and without explicit flushes after each write. As the following data show, flushing every time (FLUSH=true) does reduce raw throughput, but not by a significant amount except for very small request sizes, where the transfer time is already trivial (1.9μs). Given that the client is calibrated for 1MiB transactions, the overhead is not meaningful. The percentage in each section is the speedup for flushing only when the buffer is full, relative to flushing every block. The benchmark uses the default buffer size (4096 bytes), which is the same value used by the socket client and server implementation: FLUSH NBLOCKS MAX AVG TOTAL ELAPSED TIME/BLOCK false 3957471 512 255 1011165416 2.00018873s 505ns true 1068568 512 255 273064368 2.000217051s 1.871µs (73%) false 536096 4096 2048 1098066401 2.000229108s 3.731µs true 477911 4096 2047 978746731 2.000177825s 4.185µs (10.8%) false 124595 16384 8181 1019340160 2.000235086s 16.053µs true 120995 16384 8179 989703064 2.000329349s 16.532µs (2.9%) false 2114 1048576 525693 1111316541 2.000479928s 946.3µs true 2083 1048576 526379 1096449173 2.001817137s 961.025µs (1.5%) Note also that the FLUSH=false baseline is actually faster than the production code, which flushes more often than is required by the buffer filling up. Moreover, the timer slows down the overall transaction rate of the client and server, indepenedent of how fast the socket transfer is, so the loss on a real workload is probably much less.
3 years ago
8 years ago
  1. package abciclient
  2. import (
  3. "bufio"
  4. "container/list"
  5. "context"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. "reflect"
  11. "sync"
  12. "time"
  13. "github.com/tendermint/tendermint/abci/types"
  14. "github.com/tendermint/tendermint/libs/log"
  15. tmnet "github.com/tendermint/tendermint/libs/net"
  16. "github.com/tendermint/tendermint/libs/service"
  17. )
  18. const (
  19. // reqQueueSize is the max number of queued async requests.
  20. // (memory: 256MB max assuming 1MB transactions)
  21. reqQueueSize = 256
  22. )
  23. type reqResWithContext struct {
  24. R *ReqRes
  25. C context.Context // if context.Err is not nil, reqRes will be thrown away (ignored)
  26. }
  27. // This is goroutine-safe, but users should beware that the application in
  28. // general is not meant to be interfaced with concurrent callers.
  29. type socketClient struct {
  30. service.BaseService
  31. logger log.Logger
  32. addr string
  33. mustConnect bool
  34. conn net.Conn
  35. reqQueue chan *reqResWithContext
  36. mtx sync.Mutex
  37. err error
  38. reqSent *list.List // list of requests sent, waiting for response
  39. resCb func(*types.Request, *types.Response) // called on all requests, if set.
  40. }
  41. var _ Client = (*socketClient)(nil)
  42. // NewSocketClient creates a new socket client, which connects to a given
  43. // address. If mustConnect is true, the client will return an error upon start
  44. // if it fails to connect.
  45. func NewSocketClient(logger log.Logger, addr string, mustConnect bool) Client {
  46. cli := &socketClient{
  47. logger: logger,
  48. reqQueue: make(chan *reqResWithContext, reqQueueSize),
  49. mustConnect: mustConnect,
  50. addr: addr,
  51. reqSent: list.New(),
  52. resCb: nil,
  53. }
  54. cli.BaseService = *service.NewBaseService(logger, "socketClient", cli)
  55. return cli
  56. }
  57. // OnStart implements Service by connecting to the server and spawning reading
  58. // and writing goroutines.
  59. func (cli *socketClient) OnStart(ctx context.Context) error {
  60. var (
  61. err error
  62. conn net.Conn
  63. )
  64. for {
  65. conn, err = tmnet.Connect(cli.addr)
  66. if err != nil {
  67. if cli.mustConnect {
  68. return err
  69. }
  70. cli.logger.Error(fmt.Sprintf("abci.socketClient failed to connect to %v. Retrying after %vs...",
  71. cli.addr, dialRetryIntervalSeconds), "err", err)
  72. time.Sleep(time.Second * dialRetryIntervalSeconds)
  73. continue
  74. }
  75. cli.conn = conn
  76. go cli.sendRequestsRoutine(ctx, conn)
  77. go cli.recvResponseRoutine(ctx, conn)
  78. return nil
  79. }
  80. }
  81. // OnStop implements Service by closing connection and flushing all queues.
  82. func (cli *socketClient) OnStop() {
  83. if cli.conn != nil {
  84. cli.conn.Close()
  85. }
  86. cli.drainQueue()
  87. }
  88. // Error returns an error if the client was stopped abruptly.
  89. func (cli *socketClient) Error() error {
  90. cli.mtx.Lock()
  91. defer cli.mtx.Unlock()
  92. return cli.err
  93. }
  94. // SetResponseCallback sets a callback, which will be executed for each
  95. // non-error & non-empty response from the server.
  96. //
  97. // NOTE: callback may get internally generated flush responses.
  98. func (cli *socketClient) SetResponseCallback(resCb Callback) {
  99. cli.mtx.Lock()
  100. defer cli.mtx.Unlock()
  101. cli.resCb = resCb
  102. }
  103. //----------------------------------------
  104. func (cli *socketClient) sendRequestsRoutine(ctx context.Context, conn io.Writer) {
  105. bw := bufio.NewWriter(conn)
  106. for {
  107. select {
  108. case <-ctx.Done():
  109. return
  110. case reqres := <-cli.reqQueue:
  111. if ctx.Err() != nil {
  112. return
  113. }
  114. if reqres.C.Err() != nil {
  115. cli.logger.Debug("Request's context is done", "req", reqres.R, "err", reqres.C.Err())
  116. continue
  117. }
  118. cli.willSendReq(reqres.R)
  119. if err := types.WriteMessage(reqres.R.Request, bw); err != nil {
  120. cli.stopForError(fmt.Errorf("write to buffer: %w", err))
  121. return
  122. }
  123. if err := bw.Flush(); err != nil {
  124. cli.stopForError(fmt.Errorf("flush buffer: %w", err))
  125. return
  126. }
  127. }
  128. }
  129. }
  130. func (cli *socketClient) recvResponseRoutine(ctx context.Context, conn io.Reader) {
  131. r := bufio.NewReader(conn)
  132. for {
  133. if ctx.Err() != nil {
  134. return
  135. }
  136. var res = &types.Response{}
  137. err := types.ReadMessage(r, res)
  138. if err != nil {
  139. cli.stopForError(fmt.Errorf("read message: %w", err))
  140. return
  141. }
  142. // cli.logger.Debug("Received response", "responseType", reflect.TypeOf(res), "response", res)
  143. switch r := res.Value.(type) {
  144. case *types.Response_Exception: // app responded with error
  145. // XXX After setting cli.err, release waiters (e.g. reqres.Done())
  146. cli.stopForError(errors.New(r.Exception.Error))
  147. return
  148. default:
  149. err := cli.didRecvResponse(res)
  150. if err != nil {
  151. cli.stopForError(err)
  152. return
  153. }
  154. }
  155. }
  156. }
  157. func (cli *socketClient) willSendReq(reqres *ReqRes) {
  158. cli.mtx.Lock()
  159. defer cli.mtx.Unlock()
  160. cli.reqSent.PushBack(reqres)
  161. }
  162. func (cli *socketClient) didRecvResponse(res *types.Response) error {
  163. cli.mtx.Lock()
  164. defer cli.mtx.Unlock()
  165. // Get the first ReqRes.
  166. next := cli.reqSent.Front()
  167. if next == nil {
  168. return fmt.Errorf("unexpected %v when nothing expected", reflect.TypeOf(res.Value))
  169. }
  170. reqres := next.Value.(*ReqRes)
  171. if !resMatchesReq(reqres.Request, res) {
  172. return fmt.Errorf("unexpected %v when response to %v expected",
  173. reflect.TypeOf(res.Value), reflect.TypeOf(reqres.Request.Value))
  174. }
  175. reqres.Response = res
  176. reqres.Done() // release waiters
  177. cli.reqSent.Remove(next) // pop first item from linked list
  178. // Notify client listener if set (global callback).
  179. if cli.resCb != nil {
  180. cli.resCb(reqres.Request, res)
  181. }
  182. // Notify reqRes listener if set (request specific callback).
  183. //
  184. // NOTE: It is possible this callback isn't set on the reqres object. At this
  185. // point, in which case it will be called after, when it is set.
  186. reqres.InvokeCallback()
  187. return nil
  188. }
  189. //----------------------------------------
  190. func (cli *socketClient) FlushAsync(ctx context.Context) (*ReqRes, error) {
  191. return cli.queueRequestAsync(ctx, types.ToRequestFlush())
  192. }
  193. func (cli *socketClient) DeliverTxAsync(ctx context.Context, req types.RequestDeliverTx) (*ReqRes, error) {
  194. return cli.queueRequestAsync(ctx, types.ToRequestDeliverTx(req))
  195. }
  196. func (cli *socketClient) CheckTxAsync(ctx context.Context, req types.RequestCheckTx) (*ReqRes, error) {
  197. return cli.queueRequestAsync(ctx, types.ToRequestCheckTx(req))
  198. }
  199. //----------------------------------------
  200. func (cli *socketClient) Flush(ctx context.Context) error {
  201. reqRes, err := cli.queueRequest(ctx, types.ToRequestFlush(), true)
  202. if err != nil {
  203. return queueErr(err)
  204. }
  205. if err := cli.Error(); err != nil {
  206. return err
  207. }
  208. gotResp := make(chan struct{})
  209. go func() {
  210. // NOTE: if we don't flush the queue, its possible to get stuck here
  211. reqRes.Wait()
  212. close(gotResp)
  213. }()
  214. select {
  215. case <-gotResp:
  216. return cli.Error()
  217. case <-ctx.Done():
  218. return ctx.Err()
  219. }
  220. }
  221. func (cli *socketClient) Echo(ctx context.Context, msg string) (*types.ResponseEcho, error) {
  222. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestEcho(msg))
  223. if err != nil {
  224. return nil, err
  225. }
  226. return reqres.Response.GetEcho(), nil
  227. }
  228. func (cli *socketClient) Info(
  229. ctx context.Context,
  230. req types.RequestInfo,
  231. ) (*types.ResponseInfo, error) {
  232. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestInfo(req))
  233. if err != nil {
  234. return nil, err
  235. }
  236. return reqres.Response.GetInfo(), nil
  237. }
  238. func (cli *socketClient) DeliverTx(
  239. ctx context.Context,
  240. req types.RequestDeliverTx,
  241. ) (*types.ResponseDeliverTx, error) {
  242. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestDeliverTx(req))
  243. if err != nil {
  244. return nil, err
  245. }
  246. return reqres.Response.GetDeliverTx(), nil
  247. }
  248. func (cli *socketClient) CheckTx(
  249. ctx context.Context,
  250. req types.RequestCheckTx,
  251. ) (*types.ResponseCheckTx, error) {
  252. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestCheckTx(req))
  253. if err != nil {
  254. return nil, err
  255. }
  256. return reqres.Response.GetCheckTx(), nil
  257. }
  258. func (cli *socketClient) Query(
  259. ctx context.Context,
  260. req types.RequestQuery,
  261. ) (*types.ResponseQuery, error) {
  262. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestQuery(req))
  263. if err != nil {
  264. return nil, err
  265. }
  266. return reqres.Response.GetQuery(), nil
  267. }
  268. func (cli *socketClient) Commit(ctx context.Context) (*types.ResponseCommit, error) {
  269. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestCommit())
  270. if err != nil {
  271. return nil, err
  272. }
  273. return reqres.Response.GetCommit(), nil
  274. }
  275. func (cli *socketClient) InitChain(
  276. ctx context.Context,
  277. req types.RequestInitChain,
  278. ) (*types.ResponseInitChain, error) {
  279. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestInitChain(req))
  280. if err != nil {
  281. return nil, err
  282. }
  283. return reqres.Response.GetInitChain(), nil
  284. }
  285. func (cli *socketClient) BeginBlock(
  286. ctx context.Context,
  287. req types.RequestBeginBlock,
  288. ) (*types.ResponseBeginBlock, error) {
  289. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestBeginBlock(req))
  290. if err != nil {
  291. return nil, err
  292. }
  293. return reqres.Response.GetBeginBlock(), nil
  294. }
  295. func (cli *socketClient) EndBlock(
  296. ctx context.Context,
  297. req types.RequestEndBlock,
  298. ) (*types.ResponseEndBlock, error) {
  299. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestEndBlock(req))
  300. if err != nil {
  301. return nil, err
  302. }
  303. return reqres.Response.GetEndBlock(), nil
  304. }
  305. func (cli *socketClient) ListSnapshots(
  306. ctx context.Context,
  307. req types.RequestListSnapshots,
  308. ) (*types.ResponseListSnapshots, error) {
  309. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestListSnapshots(req))
  310. if err != nil {
  311. return nil, err
  312. }
  313. return reqres.Response.GetListSnapshots(), nil
  314. }
  315. func (cli *socketClient) OfferSnapshot(
  316. ctx context.Context,
  317. req types.RequestOfferSnapshot,
  318. ) (*types.ResponseOfferSnapshot, error) {
  319. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestOfferSnapshot(req))
  320. if err != nil {
  321. return nil, err
  322. }
  323. return reqres.Response.GetOfferSnapshot(), nil
  324. }
  325. func (cli *socketClient) LoadSnapshotChunk(
  326. ctx context.Context,
  327. req types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) {
  328. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestLoadSnapshotChunk(req))
  329. if err != nil {
  330. return nil, err
  331. }
  332. return reqres.Response.GetLoadSnapshotChunk(), nil
  333. }
  334. func (cli *socketClient) ApplySnapshotChunk(
  335. ctx context.Context,
  336. req types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) {
  337. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestApplySnapshotChunk(req))
  338. if err != nil {
  339. return nil, err
  340. }
  341. return reqres.Response.GetApplySnapshotChunk(), nil
  342. }
  343. func (cli *socketClient) PrepareProposal(
  344. ctx context.Context,
  345. req types.RequestPrepareProposal) (*types.ResponsePrepareProposal, error) {
  346. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestPrepareProposal(req))
  347. if err != nil {
  348. return nil, err
  349. }
  350. return reqres.Response.GetPrepareProposal(), nil
  351. }
  352. func (cli *socketClient) ExtendVote(
  353. ctx context.Context,
  354. req types.RequestExtendVote) (*types.ResponseExtendVote, error) {
  355. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestExtendVote(req))
  356. if err != nil {
  357. return nil, err
  358. }
  359. return reqres.Response.GetExtendVote(), nil
  360. }
  361. func (cli *socketClient) VerifyVoteExtension(
  362. ctx context.Context,
  363. req types.RequestVerifyVoteExtension) (*types.ResponseVerifyVoteExtension, error) {
  364. reqres, err := cli.queueRequestAndFlush(ctx, types.ToRequestVerifyVoteExtension(req))
  365. if err != nil {
  366. return nil, err
  367. }
  368. return reqres.Response.GetVerifyVoteExtension(), nil
  369. }
  370. //----------------------------------------
  371. // queueRequest enqueues req onto the queue. If the queue is full, it ether
  372. // returns an error (sync=false) or blocks (sync=true).
  373. //
  374. // When sync=true, ctx can be used to break early. When sync=false, ctx will be
  375. // used later to determine if request should be dropped (if ctx.Err is
  376. // non-nil).
  377. //
  378. // The caller is responsible for checking cli.Error.
  379. func (cli *socketClient) queueRequest(ctx context.Context, req *types.Request, sync bool) (*ReqRes, error) {
  380. reqres := NewReqRes(req)
  381. if sync {
  382. select {
  383. case cli.reqQueue <- &reqResWithContext{R: reqres, C: context.Background()}:
  384. case <-ctx.Done():
  385. return nil, ctx.Err()
  386. }
  387. } else {
  388. select {
  389. case cli.reqQueue <- &reqResWithContext{R: reqres, C: ctx}:
  390. default:
  391. return nil, errors.New("buffer is full")
  392. }
  393. }
  394. return reqres, nil
  395. }
  396. func (cli *socketClient) queueRequestAsync(
  397. ctx context.Context,
  398. req *types.Request,
  399. ) (*ReqRes, error) {
  400. reqres, err := cli.queueRequest(ctx, req, false)
  401. if err != nil {
  402. return nil, queueErr(err)
  403. }
  404. return reqres, cli.Error()
  405. }
  406. func (cli *socketClient) queueRequestAndFlush(
  407. ctx context.Context,
  408. req *types.Request,
  409. ) (*ReqRes, error) {
  410. reqres, err := cli.queueRequest(ctx, req, true)
  411. if err != nil {
  412. return nil, queueErr(err)
  413. }
  414. if err := cli.Flush(ctx); err != nil {
  415. return nil, err
  416. }
  417. return reqres, cli.Error()
  418. }
  419. func queueErr(e error) error {
  420. return fmt.Errorf("can't queue req: %w", e)
  421. }
  422. // drainQueue marks as complete and discards all remaining pending requests
  423. // from the queue.
  424. func (cli *socketClient) drainQueue() {
  425. cli.mtx.Lock()
  426. defer cli.mtx.Unlock()
  427. // mark all in-flight messages as resolved (they will get cli.Error())
  428. for req := cli.reqSent.Front(); req != nil; req = req.Next() {
  429. reqres := req.Value.(*ReqRes)
  430. reqres.Done()
  431. }
  432. // Mark all queued messages as resolved.
  433. //
  434. // TODO(creachadair): We can't simply range the channel, because it is never
  435. // closed, and the writer continues to add work.
  436. // See https://github.com/tendermint/tendermint/issues/6996.
  437. for {
  438. select {
  439. case reqres := <-cli.reqQueue:
  440. reqres.R.Done()
  441. default:
  442. return
  443. }
  444. }
  445. }
  446. //----------------------------------------
  447. func resMatchesReq(req *types.Request, res *types.Response) (ok bool) {
  448. switch req.Value.(type) {
  449. case *types.Request_Echo:
  450. _, ok = res.Value.(*types.Response_Echo)
  451. case *types.Request_Flush:
  452. _, ok = res.Value.(*types.Response_Flush)
  453. case *types.Request_Info:
  454. _, ok = res.Value.(*types.Response_Info)
  455. case *types.Request_DeliverTx:
  456. _, ok = res.Value.(*types.Response_DeliverTx)
  457. case *types.Request_CheckTx:
  458. _, ok = res.Value.(*types.Response_CheckTx)
  459. case *types.Request_Commit:
  460. _, ok = res.Value.(*types.Response_Commit)
  461. case *types.Request_Query:
  462. _, ok = res.Value.(*types.Response_Query)
  463. case *types.Request_InitChain:
  464. _, ok = res.Value.(*types.Response_InitChain)
  465. case *types.Request_PrepareProposal:
  466. _, ok = res.Value.(*types.Response_PrepareProposal)
  467. case *types.Request_ExtendVote:
  468. _, ok = res.Value.(*types.Response_ExtendVote)
  469. case *types.Request_VerifyVoteExtension:
  470. _, ok = res.Value.(*types.Response_VerifyVoteExtension)
  471. case *types.Request_BeginBlock:
  472. _, ok = res.Value.(*types.Response_BeginBlock)
  473. case *types.Request_EndBlock:
  474. _, ok = res.Value.(*types.Response_EndBlock)
  475. case *types.Request_ApplySnapshotChunk:
  476. _, ok = res.Value.(*types.Response_ApplySnapshotChunk)
  477. case *types.Request_LoadSnapshotChunk:
  478. _, ok = res.Value.(*types.Response_LoadSnapshotChunk)
  479. case *types.Request_ListSnapshots:
  480. _, ok = res.Value.(*types.Response_ListSnapshots)
  481. case *types.Request_OfferSnapshot:
  482. _, ok = res.Value.(*types.Response_OfferSnapshot)
  483. }
  484. return ok
  485. }
  486. func (cli *socketClient) stopForError(err error) {
  487. if !cli.IsRunning() {
  488. return
  489. }
  490. cli.mtx.Lock()
  491. cli.err = err
  492. cli.mtx.Unlock()
  493. cli.logger.Info("Stopping abci.socketClient", "reason", err)
  494. if err := cli.Stop(); err != nil {
  495. cli.logger.Error("error stopping abci.socketClient", "err", err)
  496. }
  497. }