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.

598 lines
16 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
8 years ago
8 years ago
8 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. "time"
  12. "github.com/tendermint/tendermint/abci/types"
  13. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  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. addr string
  32. mustConnect bool
  33. conn net.Conn
  34. reqQueue chan *reqResWithContext
  35. mtx tmsync.Mutex
  36. err error
  37. reqSent *list.List // list of requests sent, waiting for response
  38. resCb func(*types.Request, *types.Response) // called on all requests, if set.
  39. }
  40. var _ Client = (*socketClient)(nil)
  41. // NewSocketClient creates a new socket client, which connects to a given
  42. // address. If mustConnect is true, the client will return an error upon start
  43. // if it fails to connect.
  44. func NewSocketClient(logger log.Logger, addr string, mustConnect bool) Client {
  45. cli := &socketClient{
  46. reqQueue: make(chan *reqResWithContext, reqQueueSize),
  47. mustConnect: mustConnect,
  48. addr: addr,
  49. reqSent: list.New(),
  50. resCb: nil,
  51. }
  52. cli.BaseService = *service.NewBaseService(logger, "socketClient", cli)
  53. return cli
  54. }
  55. // OnStart implements Service by connecting to the server and spawning reading
  56. // and writing goroutines.
  57. func (cli *socketClient) OnStart(ctx context.Context) error {
  58. var (
  59. err error
  60. conn net.Conn
  61. )
  62. for {
  63. conn, err = tmnet.Connect(cli.addr)
  64. if err != nil {
  65. if cli.mustConnect {
  66. return err
  67. }
  68. cli.Logger.Error(fmt.Sprintf("abci.socketClient failed to connect to %v. Retrying after %vs...",
  69. cli.addr, dialRetryIntervalSeconds), "err", err)
  70. time.Sleep(time.Second * dialRetryIntervalSeconds)
  71. continue
  72. }
  73. cli.conn = conn
  74. go cli.sendRequestsRoutine(ctx, conn)
  75. go cli.recvResponseRoutine(ctx, conn)
  76. return nil
  77. }
  78. }
  79. // OnStop implements Service by closing connection and flushing all queues.
  80. func (cli *socketClient) OnStop() {
  81. if cli.conn != nil {
  82. cli.conn.Close()
  83. }
  84. cli.drainQueue()
  85. }
  86. // Error returns an error if the client was stopped abruptly.
  87. func (cli *socketClient) Error() error {
  88. cli.mtx.Lock()
  89. defer cli.mtx.Unlock()
  90. return cli.err
  91. }
  92. // SetResponseCallback sets a callback, which will be executed for each
  93. // non-error & non-empty response from the server.
  94. //
  95. // NOTE: callback may get internally generated flush responses.
  96. func (cli *socketClient) SetResponseCallback(resCb Callback) {
  97. cli.mtx.Lock()
  98. defer cli.mtx.Unlock()
  99. cli.resCb = resCb
  100. }
  101. //----------------------------------------
  102. func (cli *socketClient) sendRequestsRoutine(ctx context.Context, conn io.Writer) {
  103. bw := bufio.NewWriter(conn)
  104. for {
  105. select {
  106. case <-ctx.Done():
  107. return
  108. case <-cli.Quit():
  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) EchoAsync(ctx context.Context, msg string) (*ReqRes, error) {
  191. return cli.queueRequestAsync(ctx, types.ToRequestEcho(msg))
  192. }
  193. func (cli *socketClient) FlushAsync(ctx context.Context) (*ReqRes, error) {
  194. return cli.queueRequestAsync(ctx, types.ToRequestFlush())
  195. }
  196. func (cli *socketClient) InfoAsync(ctx context.Context, req types.RequestInfo) (*ReqRes, error) {
  197. return cli.queueRequestAsync(ctx, types.ToRequestInfo(req))
  198. }
  199. func (cli *socketClient) DeliverTxAsync(ctx context.Context, req types.RequestDeliverTx) (*ReqRes, error) {
  200. return cli.queueRequestAsync(ctx, types.ToRequestDeliverTx(req))
  201. }
  202. func (cli *socketClient) CheckTxAsync(ctx context.Context, req types.RequestCheckTx) (*ReqRes, error) {
  203. return cli.queueRequestAsync(ctx, types.ToRequestCheckTx(req))
  204. }
  205. func (cli *socketClient) QueryAsync(ctx context.Context, req types.RequestQuery) (*ReqRes, error) {
  206. return cli.queueRequestAsync(ctx, types.ToRequestQuery(req))
  207. }
  208. func (cli *socketClient) CommitAsync(ctx context.Context) (*ReqRes, error) {
  209. return cli.queueRequestAsync(ctx, types.ToRequestCommit())
  210. }
  211. func (cli *socketClient) InitChainAsync(ctx context.Context, req types.RequestInitChain) (*ReqRes, error) {
  212. return cli.queueRequestAsync(ctx, types.ToRequestInitChain(req))
  213. }
  214. func (cli *socketClient) BeginBlockAsync(ctx context.Context, req types.RequestBeginBlock) (*ReqRes, error) {
  215. return cli.queueRequestAsync(ctx, types.ToRequestBeginBlock(req))
  216. }
  217. func (cli *socketClient) EndBlockAsync(ctx context.Context, req types.RequestEndBlock) (*ReqRes, error) {
  218. return cli.queueRequestAsync(ctx, types.ToRequestEndBlock(req))
  219. }
  220. func (cli *socketClient) ListSnapshotsAsync(ctx context.Context, req types.RequestListSnapshots) (*ReqRes, error) {
  221. return cli.queueRequestAsync(ctx, types.ToRequestListSnapshots(req))
  222. }
  223. func (cli *socketClient) OfferSnapshotAsync(ctx context.Context, req types.RequestOfferSnapshot) (*ReqRes, error) {
  224. return cli.queueRequestAsync(ctx, types.ToRequestOfferSnapshot(req))
  225. }
  226. func (cli *socketClient) LoadSnapshotChunkAsync(
  227. ctx context.Context,
  228. req types.RequestLoadSnapshotChunk,
  229. ) (*ReqRes, error) {
  230. return cli.queueRequestAsync(ctx, types.ToRequestLoadSnapshotChunk(req))
  231. }
  232. func (cli *socketClient) ApplySnapshotChunkAsync(
  233. ctx context.Context,
  234. req types.RequestApplySnapshotChunk,
  235. ) (*ReqRes, error) {
  236. return cli.queueRequestAsync(ctx, types.ToRequestApplySnapshotChunk(req))
  237. }
  238. //----------------------------------------
  239. func (cli *socketClient) FlushSync(ctx context.Context) error {
  240. reqRes, err := cli.queueRequest(ctx, types.ToRequestFlush(), true)
  241. if err != nil {
  242. return queueErr(err)
  243. }
  244. if err := cli.Error(); err != nil {
  245. return err
  246. }
  247. gotResp := make(chan struct{})
  248. go func() {
  249. // NOTE: if we don't flush the queue, its possible to get stuck here
  250. reqRes.Wait()
  251. close(gotResp)
  252. }()
  253. select {
  254. case <-gotResp:
  255. return cli.Error()
  256. case <-ctx.Done():
  257. return ctx.Err()
  258. }
  259. }
  260. func (cli *socketClient) EchoSync(ctx context.Context, msg string) (*types.ResponseEcho, error) {
  261. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestEcho(msg))
  262. if err != nil {
  263. return nil, err
  264. }
  265. return reqres.Response.GetEcho(), nil
  266. }
  267. func (cli *socketClient) InfoSync(
  268. ctx context.Context,
  269. req types.RequestInfo,
  270. ) (*types.ResponseInfo, error) {
  271. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestInfo(req))
  272. if err != nil {
  273. return nil, err
  274. }
  275. return reqres.Response.GetInfo(), nil
  276. }
  277. func (cli *socketClient) DeliverTxSync(
  278. ctx context.Context,
  279. req types.RequestDeliverTx,
  280. ) (*types.ResponseDeliverTx, error) {
  281. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestDeliverTx(req))
  282. if err != nil {
  283. return nil, err
  284. }
  285. return reqres.Response.GetDeliverTx(), nil
  286. }
  287. func (cli *socketClient) CheckTxSync(
  288. ctx context.Context,
  289. req types.RequestCheckTx,
  290. ) (*types.ResponseCheckTx, error) {
  291. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestCheckTx(req))
  292. if err != nil {
  293. return nil, err
  294. }
  295. return reqres.Response.GetCheckTx(), nil
  296. }
  297. func (cli *socketClient) QuerySync(
  298. ctx context.Context,
  299. req types.RequestQuery,
  300. ) (*types.ResponseQuery, error) {
  301. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestQuery(req))
  302. if err != nil {
  303. return nil, err
  304. }
  305. return reqres.Response.GetQuery(), nil
  306. }
  307. func (cli *socketClient) CommitSync(ctx context.Context) (*types.ResponseCommit, error) {
  308. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestCommit())
  309. if err != nil {
  310. return nil, err
  311. }
  312. return reqres.Response.GetCommit(), nil
  313. }
  314. func (cli *socketClient) InitChainSync(
  315. ctx context.Context,
  316. req types.RequestInitChain,
  317. ) (*types.ResponseInitChain, error) {
  318. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestInitChain(req))
  319. if err != nil {
  320. return nil, err
  321. }
  322. return reqres.Response.GetInitChain(), nil
  323. }
  324. func (cli *socketClient) BeginBlockSync(
  325. ctx context.Context,
  326. req types.RequestBeginBlock,
  327. ) (*types.ResponseBeginBlock, error) {
  328. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestBeginBlock(req))
  329. if err != nil {
  330. return nil, err
  331. }
  332. return reqres.Response.GetBeginBlock(), nil
  333. }
  334. func (cli *socketClient) EndBlockSync(
  335. ctx context.Context,
  336. req types.RequestEndBlock,
  337. ) (*types.ResponseEndBlock, error) {
  338. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestEndBlock(req))
  339. if err != nil {
  340. return nil, err
  341. }
  342. return reqres.Response.GetEndBlock(), nil
  343. }
  344. func (cli *socketClient) ListSnapshotsSync(
  345. ctx context.Context,
  346. req types.RequestListSnapshots,
  347. ) (*types.ResponseListSnapshots, error) {
  348. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestListSnapshots(req))
  349. if err != nil {
  350. return nil, err
  351. }
  352. return reqres.Response.GetListSnapshots(), nil
  353. }
  354. func (cli *socketClient) OfferSnapshotSync(
  355. ctx context.Context,
  356. req types.RequestOfferSnapshot,
  357. ) (*types.ResponseOfferSnapshot, error) {
  358. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestOfferSnapshot(req))
  359. if err != nil {
  360. return nil, err
  361. }
  362. return reqres.Response.GetOfferSnapshot(), nil
  363. }
  364. func (cli *socketClient) LoadSnapshotChunkSync(
  365. ctx context.Context,
  366. req types.RequestLoadSnapshotChunk) (*types.ResponseLoadSnapshotChunk, error) {
  367. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestLoadSnapshotChunk(req))
  368. if err != nil {
  369. return nil, err
  370. }
  371. return reqres.Response.GetLoadSnapshotChunk(), nil
  372. }
  373. func (cli *socketClient) ApplySnapshotChunkSync(
  374. ctx context.Context,
  375. req types.RequestApplySnapshotChunk) (*types.ResponseApplySnapshotChunk, error) {
  376. reqres, err := cli.queueRequestAndFlushSync(ctx, types.ToRequestApplySnapshotChunk(req))
  377. if err != nil {
  378. return nil, err
  379. }
  380. return reqres.Response.GetApplySnapshotChunk(), nil
  381. }
  382. //----------------------------------------
  383. // queueRequest enqueues req onto the queue. If the queue is full, it ether
  384. // returns an error (sync=false) or blocks (sync=true).
  385. //
  386. // When sync=true, ctx can be used to break early. When sync=false, ctx will be
  387. // used later to determine if request should be dropped (if ctx.Err is
  388. // non-nil).
  389. //
  390. // The caller is responsible for checking cli.Error.
  391. func (cli *socketClient) queueRequest(ctx context.Context, req *types.Request, sync bool) (*ReqRes, error) {
  392. reqres := NewReqRes(req)
  393. if sync {
  394. select {
  395. case cli.reqQueue <- &reqResWithContext{R: reqres, C: context.Background()}:
  396. case <-ctx.Done():
  397. return nil, ctx.Err()
  398. }
  399. } else {
  400. select {
  401. case cli.reqQueue <- &reqResWithContext{R: reqres, C: ctx}:
  402. default:
  403. return nil, errors.New("buffer is full")
  404. }
  405. }
  406. return reqres, nil
  407. }
  408. func (cli *socketClient) queueRequestAsync(
  409. ctx context.Context,
  410. req *types.Request,
  411. ) (*ReqRes, error) {
  412. reqres, err := cli.queueRequest(ctx, req, false)
  413. if err != nil {
  414. return nil, queueErr(err)
  415. }
  416. return reqres, cli.Error()
  417. }
  418. func (cli *socketClient) queueRequestAndFlushSync(
  419. ctx context.Context,
  420. req *types.Request,
  421. ) (*ReqRes, error) {
  422. reqres, err := cli.queueRequest(ctx, req, true)
  423. if err != nil {
  424. return nil, queueErr(err)
  425. }
  426. if err := cli.FlushSync(ctx); err != nil {
  427. return nil, err
  428. }
  429. return reqres, cli.Error()
  430. }
  431. func queueErr(e error) error {
  432. return fmt.Errorf("can't queue req: %w", e)
  433. }
  434. // drainQueue marks as complete and discards all remaining pending requests
  435. // from the queue.
  436. func (cli *socketClient) drainQueue() {
  437. cli.mtx.Lock()
  438. defer cli.mtx.Unlock()
  439. // mark all in-flight messages as resolved (they will get cli.Error())
  440. for req := cli.reqSent.Front(); req != nil; req = req.Next() {
  441. reqres := req.Value.(*ReqRes)
  442. reqres.Done()
  443. }
  444. // Mark all queued messages as resolved.
  445. //
  446. // TODO(creachadair): We can't simply range the channel, because it is never
  447. // closed, and the writer continues to add work.
  448. // See https://github.com/tendermint/tendermint/issues/6996.
  449. for {
  450. select {
  451. case reqres := <-cli.reqQueue:
  452. reqres.R.Done()
  453. default:
  454. return
  455. }
  456. }
  457. }
  458. //----------------------------------------
  459. func resMatchesReq(req *types.Request, res *types.Response) (ok bool) {
  460. switch req.Value.(type) {
  461. case *types.Request_Echo:
  462. _, ok = res.Value.(*types.Response_Echo)
  463. case *types.Request_Flush:
  464. _, ok = res.Value.(*types.Response_Flush)
  465. case *types.Request_Info:
  466. _, ok = res.Value.(*types.Response_Info)
  467. case *types.Request_DeliverTx:
  468. _, ok = res.Value.(*types.Response_DeliverTx)
  469. case *types.Request_CheckTx:
  470. _, ok = res.Value.(*types.Response_CheckTx)
  471. case *types.Request_Commit:
  472. _, ok = res.Value.(*types.Response_Commit)
  473. case *types.Request_Query:
  474. _, ok = res.Value.(*types.Response_Query)
  475. case *types.Request_InitChain:
  476. _, ok = res.Value.(*types.Response_InitChain)
  477. case *types.Request_BeginBlock:
  478. _, ok = res.Value.(*types.Response_BeginBlock)
  479. case *types.Request_EndBlock:
  480. _, ok = res.Value.(*types.Response_EndBlock)
  481. case *types.Request_ApplySnapshotChunk:
  482. _, ok = res.Value.(*types.Response_ApplySnapshotChunk)
  483. case *types.Request_LoadSnapshotChunk:
  484. _, ok = res.Value.(*types.Response_LoadSnapshotChunk)
  485. case *types.Request_ListSnapshots:
  486. _, ok = res.Value.(*types.Response_ListSnapshots)
  487. case *types.Request_OfferSnapshot:
  488. _, ok = res.Value.(*types.Response_OfferSnapshot)
  489. }
  490. return ok
  491. }
  492. func (cli *socketClient) stopForError(err error) {
  493. if !cli.IsRunning() {
  494. return
  495. }
  496. cli.mtx.Lock()
  497. cli.err = err
  498. cli.mtx.Unlock()
  499. cli.Logger.Info("Stopping abci.socketClient", "reason", err)
  500. if err := cli.Stop(); err != nil {
  501. cli.Logger.Error("Error stopping abci.socketClient", "err", err)
  502. }
  503. }