Skip to content

Commit c2fe643

Browse files
avitenzerclaude
andcommitted
refactor(lavasession): send both direct HTTP requests through one sender (MAG-4279, MAG-4278)
HTTPDirectRPCConnection had two copies of the same request: SendRequest (a POST of a JSON body) and DoHTTPRequest (any method and path). Both are now thin wrappers over one do(ctx, method, url, body, contentType, headers), and the endpoint poller's REST path builds its HTTPStatusError through the new NewHTTPStatusError instead of rebuilding the struct by hand. The copies had drifted (MAG-4278 item 17). Each rule is settled on the DoHTTPRequest copy, which is what the relay path already uses for JSON-RPC and REST: - Content-Type: the default is set before the caller's headers, so a spec-supplied content type wins; SendRequest set application/json after them and overwrote it. - IP forwarding: a url with ip-forwarding now forwards the client's address from SendRequest too; it only did so from DoHTTPRequest. - Empty header values: an empty caller value deletes the header (the spec's nullify); SendRequest sent it as an empty header. - Status error: both producers already carried the upstream's status line; they now build the error in one place, Retry-After included. Kept: SendRequest's default content type stays application/json, and it still returns a 4xx/5xx as the response plus an *HTTPStatusError, where DoHTTPRequest returns it as a response only. The poller's and recovery probe's error texts are now "failed to build HTTP request" / "failed reading response", the relay path's texts; nothing matches on either. No current caller observes a change: the relay path already sends JSON-RPC and REST through DoHTTPRequest, and SendRequest's remaining HTTP callers (the endpoint poller and the recovery probe) pass no spec headers and carry no client address. TestHTTPSenders_SetHeadersByTheSameRules runs every rule through both senders; against the old SendRequest (go test -overlay) the IP-forwarding, content-type and delete-on-empty rows fail. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent c17c2cc commit c2fe643

3 files changed

Lines changed: 169 additions & 90 deletions

File tree

‎protocol/endpointstate/endpoint_poller.go‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"encoding/json"
66
"fmt"
7-
"net/http"
87
"sort"
98
"sync/atomic"
109
"time"
@@ -527,13 +526,7 @@ func (ecf *EndpointPoller) doRESTRequest(ctx context.Context, method, path strin
527526
return nil, err
528527
}
529528
if resp.StatusCode >= 400 {
530-
retryAfter, _ := common.ParseRetryAfter(http.Header(resp.Headers), time.Now())
531-
return nil, &lavasession.HTTPStatusError{
532-
StatusCode: resp.StatusCode,
533-
Status: resp.Status,
534-
Body: resp.Body,
535-
RetryAfter: retryAfter,
536-
}
529+
return nil, lavasession.NewHTTPStatusError(resp.StatusCode, resp.Status, resp.Headers, resp.Body)
537530
}
538531
return resp.Body, nil
539532
}

‎protocol/lavasession/direct_rpc_connection.go‎

Lines changed: 64 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -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.
772775
func (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+
919895
func (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

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package lavasession
2+
3+
import (
4+
"context"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
"time"
9+
10+
"github.com/magma-Devs/smart-router/protocol/common"
11+
pairingtypes "github.com/magma-Devs/smart-router/types/relay"
12+
"github.com/stretchr/testify/require"
13+
"google.golang.org/grpc/metadata"
14+
)
15+
16+
// The two HTTP senders set headers by one set of rules (MAG-4278 item 17): a caller's
17+
// Content-Type wins over the default, the client's address is forwarded when the url asks for
18+
// it, and an empty caller value deletes the header. SendRequest used to set application/json
19+
// after the caller's headers, skip IP forwarding and send an empty value as an empty header.
20+
func TestHTTPSenders_SetHeadersByTheSameRules(t *testing.T) {
21+
senders := map[string]func(h *HTTPDirectRPCConnection, ctx context.Context, url string, headers map[string]string) error{
22+
"SendRequest": func(h *HTTPDirectRPCConnection, ctx context.Context, _ string, headers map[string]string) error {
23+
_, err := h.SendRequest(ctx, []byte(`{}`), headers)
24+
return err
25+
},
26+
"DoHTTPRequest": func(h *HTTPDirectRPCConnection, ctx context.Context, url string, headers map[string]string) error {
27+
params := HTTPRequestParams{Method: http.MethodPost, URL: url, Body: []byte(`{}`), ContentType: "application/json"}
28+
for name, value := range headers {
29+
params.Headers = append(params.Headers, pairingtypes.Metadata{Name: name, Value: value})
30+
}
31+
_, err := h.DoHTTPRequest(ctx, params)
32+
return err
33+
},
34+
}
35+
36+
// sendAndSee sends one request with the caller's headers and returns what the node received.
37+
sendAndSee := func(t *testing.T, send func(*HTTPDirectRPCConnection, context.Context, string, map[string]string) error, headers map[string]string) (http.Header, *HTTPDirectRPCConnection) {
38+
var seen http.Header
39+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
40+
seen = r.Header.Clone()
41+
_, _ = w.Write([]byte(`{}`))
42+
}))
43+
defer srv.Close()
44+
45+
h := newHTTPConnection(t, common.NodeUrl{
46+
Url: srv.URL,
47+
IpForwarding: true,
48+
AuthConfig: common.AuthConfig{AuthHeaders: map[string]string{"X-Api-Key": "secret"}},
49+
})
50+
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(common.IP_FORWARDING_HEADER_NAME, "203.0.113.7"))
51+
require.NoError(t, send(h, ctx, srv.URL, headers))
52+
return seen, h
53+
}
54+
55+
for name, send := range senders {
56+
t.Run(name, func(t *testing.T) {
57+
t.Run("defaults", func(t *testing.T) {
58+
seen, h := sendAndSee(t, send, nil)
59+
require.Equal(t, "application/json", seen.Get("Content-Type"))
60+
require.Equal(t, "secret", seen.Get("X-Api-Key"), "the url's auth header")
61+
require.Equal(t, h.nodeUrl.UpstreamAcceptEncoding(), seen.Get("Accept-Encoding"))
62+
})
63+
t.Run("the client's address is forwarded when the url asks for it", func(t *testing.T) {
64+
seen, _ := sendAndSee(t, send, nil)
65+
require.Equal(t, "203.0.113.7", seen.Get(common.IP_FORWARDING_HEADER_NAME))
66+
})
67+
t.Run("a caller's content type wins over the default", func(t *testing.T) {
68+
seen, _ := sendAndSee(t, send, map[string]string{"Content-Type": "application/x-www-form-urlencoded"})
69+
require.Equal(t, "application/x-www-form-urlencoded", seen.Get("Content-Type"))
70+
})
71+
t.Run("an empty caller value deletes the header", func(t *testing.T) {
72+
seen, _ := sendAndSee(t, send, map[string]string{"X-Api-Key": "", "X-Spec-Directive": "on"})
73+
_, present := seen["X-Api-Key"]
74+
require.False(t, present, "sent as %q", seen.Values("X-Api-Key"))
75+
require.Equal(t, "on", seen.Get("X-Spec-Directive"))
76+
})
77+
t.Run("no caller header overrides Accept-Encoding", func(t *testing.T) {
78+
seen, h := sendAndSee(t, send, map[string]string{"Accept-Encoding": "gzip"})
79+
require.Equal(t, h.nodeUrl.UpstreamAcceptEncoding(), seen.Get("Accept-Encoding"))
80+
})
81+
})
82+
}
83+
}
84+
85+
// Every producer of an HTTPStatusError builds it the same way, so a rejection reads the same
86+
// whichever path saw it: the code, the upstream's own status line, the body and Retry-After.
87+
func TestNewHTTPStatusError_MatchesWhatTheSenderReturns(t *testing.T) {
88+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
89+
w.Header().Set("Retry-After", "7")
90+
w.WriteHeader(http.StatusTooManyRequests)
91+
_, _ = w.Write([]byte(`slow down`))
92+
}))
93+
defer srv.Close()
94+
95+
h := newHTTPConnection(t, common.NodeUrl{Url: srv.URL})
96+
resp, sendErr := h.SendRequest(context.Background(), []byte(`{}`), nil)
97+
require.Error(t, sendErr)
98+
99+
built := NewHTTPStatusError(resp.StatusCode, "429 Too Many Requests", resp.Metadata, resp.Data)
100+
require.Equal(t, built, sendErr)
101+
require.Equal(t, 7*time.Second, built.RetryAfter)
102+
require.Equal(t, "429 Too Many Requests", built.Status)
103+
require.Equal(t, []byte(`slow down`), built.Body)
104+
}

0 commit comments

Comments
 (0)