@@ -768,73 +768,36 @@ func DetectProtocol(urlStr string, apiInterface string) (DirectRPCProtocol, erro
768768 }
769769}
770770
771- // SendRequest implements DirectRPCConnection for HTTP/HTTPS
771+ // SendRequest implements DirectRPCConnection for HTTP/HTTPS: a POST of data to the url, as
772+ // application/json unless a caller header names another Content-Type. Callers needing another
773+ // method or path use DoHTTPRequest; both go through do, so they set headers by the same rules.
774+ // A 4xx/5xx reply comes back as the response and an *HTTPStatusError together.
772775func (h * HTTPDirectRPCConnection ) SendRequest (
773776 ctx context.Context ,
774777 data []byte ,
775778 headers map [string ]string ,
776779) (* DirectRPCResponse , error ) {
777- // NOTE: for JSON-RPC we use POST with a JSON body.
778- // For REST-style APIs (e.g. Cosmos LCD), the chain parser must provide the correct URL path and HTTP method
779- // (GET/POST/etc.). This transport layer sends bytes and returns bytes; method selection is driven by chain spec.
780- req , err := http .NewRequestWithContext (ctx , http .MethodPost , h .nodeUrl .AuthConfig .AddAuthPath (h .nodeUrl .Url ), bytes .NewReader (data ))
781- if err != nil {
782- // NewRequestWithContext only fails on malformed URL / method — a programmer
783- // error, not a transport failure or upstream outage.
784- return nil , fmt .Errorf ("failed to build request: %w" , err )
785- }
786-
787- // Apply auth headers from config + per-request headers from chainMessage/chainParser.
788- for k , v := range h .nodeUrl .GetAuthHeaders () {
789- req .Header .Set (k , v )
790- }
791- for k , v := range headers {
792- req .Header .Set (k , v )
793- }
794- req .Header .Set ("Content-Type" , "application/json" )
795- // Accept-Encoding is the url's own (NodeUrl.AcceptEncoding): identity unless
796- // the operator opted it in to gzip. Setting any value keeps Go's http client
797- // from adding `gzip` and decoding it on its own. That path cost the eth router
798- // ~30-39% of its CPU (http2gzipReader → compress/flate.decompressor), and
799- // asking for identity took it from 2.47 cores to 1.23 (MAG-1589). This
800- // scoping is smart-router-only: the shared transport still lets provider
801- // chain proxies keep their standard auto-gzip behavior. A gzip reply is
802- // inflated by readHTTPResponseBody instead.
803- // Set *after* caller headers so it cannot be accidentally overridden.
804- req .Header .Set ("Accept-Encoding" , h .nodeUrl .UpstreamAcceptEncoding ())
805- h .markRetireIfDue (req )
806-
807- resp , err := h .client .Do (req )
808- if err != nil {
809- return nil , fmt .Errorf ("http request failed: %w" , err )
780+ callerHeaders := make ([]pairingtypes.Metadata , 0 , len (headers ))
781+ for name , value := range headers {
782+ callerHeaders = append (callerHeaders , pairingtypes.Metadata {Name : name , Value : value })
810783 }
811- defer resp .Body .Close ()
812- h .observeStatus (resp .StatusCode )
813-
814- body , err := readHTTPResponseBody (resp )
784+ resp , err := h .do (ctx , http .MethodPost , h .nodeUrl .Url , data , "application/json" , callerHeaders )
815785 if err != nil {
816- return nil , fmt . Errorf ( "failed reading response body: %w" , err )
786+ return nil , err
817787 }
818788
819789 // Build response with metadata (HTTP headers)
820790 response := & DirectRPCResponse {
821- Data : body ,
822- Metadata : resp .Header , // http.Header is map[string][]string
791+ Data : resp . Body ,
792+ Metadata : resp .Headers , // http.Header is map[string][]string
823793 StatusCode : resp .StatusCode ,
824794 }
825795
826796 // Check HTTP status code and return error for non-2xx responses
827797 // Note: For JSON-RPC, status 200 with RPC error in body is common and valid
828798 // We return the response in both cases - the caller will check for RPC errors
829799 if resp .StatusCode >= 400 {
830- // For 4xx/5xx errors, include status code in error but also return the response
831- retryAfter , _ := common .ParseRetryAfter (resp .Header , time .Now ())
832- return response , & HTTPStatusError {
833- StatusCode : resp .StatusCode ,
834- Status : resp .Status ,
835- Body : body ,
836- RetryAfter : retryAfter ,
837- }
800+ return response , NewHTTPStatusError (resp .StatusCode , resp .Status , resp .Headers , resp .Body )
838801 }
839802
840803 return response , nil
@@ -916,6 +879,19 @@ func (e *HTTPStatusError) Unwrap() error {
916879 return & common.RateLimitedError {RetryAfter : e .RetryAfter }
917880}
918881
882+ // NewHTTPStatusError builds the error for a 4xx/5xx reply, with RetryAfter read from the reply's
883+ // headers. Every producer goes through it, so the error reads the same whichever path saw the
884+ // status.
885+ func NewHTTPStatusError (statusCode int , status string , header map [string ][]string , body []byte ) * HTTPStatusError {
886+ retryAfter , _ := common .ParseRetryAfter (header , time .Now ())
887+ return & HTTPStatusError {
888+ StatusCode : statusCode ,
889+ Status : status ,
890+ Body : body ,
891+ RetryAfter : retryAfter ,
892+ }
893+ }
894+
919895func (h * HTTPDirectRPCConnection ) GetProtocol () DirectRPCProtocol {
920896 return h .protocol
921897}
@@ -938,73 +914,79 @@ func (h *HTTPDirectRPCConnection) DoHTTPRequest(
938914 ctx context.Context ,
939915 params HTTPRequestParams ,
940916) (* HTTPDirectRPCResponse , error ) {
941- // Build request body reader
917+ // Don't return error for 4xx/5xx - client needs the response
918+ return h .do (ctx , params .Method , params .URL , params .Body , params .ContentType , params .Headers )
919+ }
920+
921+ // do sends one request to the node and reads the whole reply, inflated if the upstream gzipped
922+ // it. Both senders use it, so headers are applied in one order for JSON-RPC and REST alike:
923+ // - the url's auth headers, then the client's address when the url asks for IP forwarding;
924+ // - contentType, for a request with a body, BEFORE the caller's headers, so a spec-supplied
925+ // content-type wins over this default instead of being overwritten by it. Stellar's REST
926+ // POST collection overrides it to application/x-www-form-urlencoded (Horizon rejects
927+ // anything else on /transactions with 415). This matches the chainlib REST proxy;
928+ // - the caller's headers, where an empty value deletes the header (the spec's nullify);
929+ // - Accept-Encoding last, so no caller header can override it.
930+ func (h * HTTPDirectRPCConnection ) do (
931+ ctx context.Context ,
932+ method , url string ,
933+ body []byte ,
934+ contentType string ,
935+ headers []pairingtypes.Metadata ,
936+ ) (* HTTPDirectRPCResponse , error ) {
942937 var bodyReader io.Reader
943- if params . Body != nil {
944- bodyReader = bytes .NewReader (params . Body )
938+ if body != nil {
939+ bodyReader = bytes .NewReader (body )
945940 }
946941
947942 // Apply auth path transformation (e.g., prepend /api/v1 if configured)
948- fullURL := h .nodeUrl .AuthConfig .AddAuthPath (params .URL )
949-
950- req , err := http .NewRequestWithContext (ctx , params .Method , fullURL , bodyReader )
943+ req , err := http .NewRequestWithContext (ctx , method , h .nodeUrl .AuthConfig .AddAuthPath (url ), bodyReader )
951944 if err != nil {
945+ // NewRequestWithContext only fails on malformed URL / method — a programmer
946+ // error, not a transport failure or upstream outage.
952947 return nil , fmt .Errorf ("failed to build HTTP request: %w" , err )
953948 }
954949
955- // Apply NodeUrl auth headers (API keys, bearer tokens, etc.)
956950 h .nodeUrl .SetAuthHeaders (ctx , req .Header .Set )
957-
958- // Apply IP forwarding if needed
959951 h .nodeUrl .SetIpForwardingIfNecessary (ctx , req .Header .Set )
960-
961- // Set the default Content-Type for requests with a body BEFORE applying
962- // per-request headers, so a spec-supplied content-type wins over this default
963- // instead of being overwritten by it. Stellar's REST POST collection overrides
964- // content-type to application/x-www-form-urlencoded (Horizon rejects anything
965- // else on /transactions with 415); with the opposite ordering that override was
966- // computed correctly and then discarded here. This matches the ordering the
967- // chainlib REST proxy has always used.
968- if params .Body != nil && params .ContentType != "" {
969- req .Header .Set ("Content-Type" , params .ContentType )
952+ if body != nil && contentType != "" {
953+ req .Header .Set ("Content-Type" , contentType )
970954 }
971-
972- // Apply per-request headers with delete semantics
973- for _ , header := range params .Headers {
955+ for _ , header := range headers {
974956 if header .Value == "" {
975- req .Header .Del (header .Name ) // Empty value = delete header
957+ req .Header .Del (header .Name )
976958 } else {
977959 req .Header .Set (header .Name , header .Value )
978960 }
979961 }
980-
981- // The url's own Accept-Encoding, identity unless it opted in to gzip. See
982- // SendRequest above for the full rationale. Set last so it cannot be
983- // overridden by per-request headers.
962+ // Accept-Encoding is the url's own (NodeUrl.AcceptEncoding): identity unless
963+ // the operator opted it in to gzip. Setting any value keeps Go's http client
964+ // from adding `gzip` and decoding it on its own. That path cost the eth router
965+ // ~30-39% of its CPU (http2gzipReader → compress/flate.decompressor), and
966+ // asking for identity took it from 2.47 cores to 1.23 (MAG-1589). This
967+ // scoping is smart-router-only: the shared transport still lets provider
968+ // chain proxies keep their standard auto-gzip behavior. A gzip reply is
969+ // inflated by readHTTPResponseBody instead.
984970 req .Header .Set ("Accept-Encoding" , h .nodeUrl .UpstreamAcceptEncoding ())
985971 h .markRetireIfDue (req )
986972
987- // Send request
988973 resp , err := h .client .Do (req )
989974 if err != nil {
990975 return nil , fmt .Errorf ("http request failed: %w" , err )
991976 }
992977 defer resp .Body .Close ()
993978 h .observeStatus (resp .StatusCode )
994979
995- // Read response body, inflated if the upstream gzipped it
996- body , err := readHTTPResponseBody (resp )
980+ respBody , err := readHTTPResponseBody (resp )
997981 if err != nil {
998982 return nil , fmt .Errorf ("failed reading response: %w" , err )
999983 }
1000984
1001- // Return complete response (status + headers + body)
1002- // Don't return error for 4xx/5xx - client needs the response
1003985 return & HTTPDirectRPCResponse {
1004986 StatusCode : resp .StatusCode ,
1005987 Status : resp .Status ,
1006988 Headers : resp .Header ,
1007- Body : body ,
989+ Body : respBody ,
1008990 }, nil
1009991}
1010992
0 commit comments