@@ -2,6 +2,7 @@ package api
22
33import (
44 "bytes"
5+ "context"
56 "encoding/hex"
67 "fmt"
78 "github.com/cloudstruct/tx-submit-api-mirror/config"
@@ -12,6 +13,8 @@ import (
1213 "golang.org/x/crypto/blake2b"
1314 "io/ioutil"
1415 "net/http"
16+ "net/http/httptrace"
17+ "time"
1518)
1619
1720func Start (cfg * config.Config ) error {
@@ -74,12 +77,26 @@ func handleSubmitTx(c *gin.Context) {
7477 // Send request to each backend
7578 for _ , backend := range cfg .Backends {
7679 go func (backend string ) {
80+ startTime := time .Now ()
7781 body := bytes .NewBuffer (rawTx )
78- resp , err := http .Post (backend , "application/cbor" , body )
82+ connReused := false
83+ // Trace HTTP request to get information about whether the connection was reused
84+ clientTrace := & httptrace.ClientTrace {
85+ GotConn : func (info httptrace.GotConnInfo ) { connReused = info .Reused },
86+ }
87+ traceCtx := httptrace .WithClientTrace (context .Background (), clientTrace )
88+ req , err := http .NewRequestWithContext (traceCtx , http .MethodPost , backend , body )
89+ if err != nil {
90+ logger .Errorf ("failed to create request: %s" , err )
91+ return
92+ }
93+ req .Header .Add ("Content-Type" , "application/cbor" )
94+ resp , err := http .DefaultClient .Do (req )
7995 if err != nil {
8096 logger .Errorf ("failed to send request to backend %s: %s" , backend , err )
8197 return
8298 }
99+ elapsedTime := time .Since (startTime )
83100 // We have to read the entire response body and close it to prevent a memory leak
84101 respBody , err := ioutil .ReadAll (resp .Body )
85102 if err != nil {
@@ -88,9 +105,9 @@ func handleSubmitTx(c *gin.Context) {
88105 }
89106 defer resp .Body .Close ()
90107 if resp .StatusCode == 202 {
91- logger .Infof ( "successfully submitted transaction %s to backend %s" , txIdHex , backend )
108+ logger .Infow ( fmt . Sprintf ( "successfully submitted transaction %s to backend %s" , txIdHex , backend ), "latency" , elapsedTime . Seconds (), "connReused" , connReused )
92109 } else {
93- logger .Errorf ( "failed to send request to backend %s: got response %d, %s" , backend , resp .StatusCode , string (respBody ))
110+ logger .Errorw ( fmt . Sprintf ( "failed to send request to backend %s: got response %d, %s" , backend , resp .StatusCode , string (respBody )), "latency" , elapsedTime . Seconds (), "connReused" , connReused )
94111 }
95112 }(backend )
96113 }
0 commit comments