@@ -2,6 +2,7 @@ package api
2
2
3
3
import (
4
4
"bytes"
5
+ "context"
5
6
"encoding/hex"
6
7
"fmt"
7
8
"github.com/cloudstruct/tx-submit-api-mirror/config"
@@ -12,6 +13,8 @@ import (
12
13
"golang.org/x/crypto/blake2b"
13
14
"io/ioutil"
14
15
"net/http"
16
+ "net/http/httptrace"
17
+ "time"
15
18
)
16
19
17
20
func Start (cfg * config.Config ) error {
@@ -74,12 +77,26 @@ func handleSubmitTx(c *gin.Context) {
74
77
// Send request to each backend
75
78
for _ , backend := range cfg .Backends {
76
79
go func (backend string ) {
80
+ startTime := time .Now ()
77
81
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 )
79
95
if err != nil {
80
96
logger .Errorf ("failed to send request to backend %s: %s" , backend , err )
81
97
return
82
98
}
99
+ elapsedTime := time .Since (startTime )
83
100
// We have to read the entire response body and close it to prevent a memory leak
84
101
respBody , err := ioutil .ReadAll (resp .Body )
85
102
if err != nil {
@@ -88,9 +105,9 @@ func handleSubmitTx(c *gin.Context) {
88
105
}
89
106
defer resp .Body .Close ()
90
107
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 )
92
109
} 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 )
94
111
}
95
112
}(backend )
96
113
}
0 commit comments