diff --git a/internal/node/libp2p_transport.go b/internal/node/libp2p_transport.go new file mode 100644 index 000000000..35dd9c5db --- /dev/null +++ b/internal/node/libp2p_transport.go @@ -0,0 +1,70 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package node + +import ( + "context" + "fmt" + "net" + "net/http" + + gostream "github.com/libp2p/go-libp2p-gostream" + libp2phttp "github.com/libp2p/go-libp2p-http" + "github.com/libp2p/go-libp2p/core/host" + "github.com/libp2p/go-libp2p/core/peer" +) + +// newLibp2pHTTPTransport returns a transport for libp2p:// URLs whose host is a +// peer ID. Requests go through net/http's Transport over a gostream connection +// to the peer's /libp2p-http protocol, as the router's ingress transport does, +// so net/http closes the stream when the request's context ends. +// +// go-libp2p-http's own transport uses the request context only to open the +// stream, which left the stream, and the remote handler behind it, open after +// the caller cancelled a long or streaming request. +// +// Keep-alives are disabled so each request gets its own stream, as it did with +// go-libp2p-http. A pooled stream over a limited (relayed) connection can be +// closed by the relay while idle, and net/http does not retry a request with a +// body, such as an A2A POST, on a reused connection. +func newLibp2pHTTPTransport(h host.Host) http.RoundTripper { + return libp2pSchemeTransport{&http.Transport{ + DialContext: func(ctx context.Context, _, addr string) (net.Conn, error) { + hostPart, _, err := net.SplitHostPort(addr) + if err != nil { + hostPart = addr + } + pid, err := peer.Decode(hostPart) + if err != nil { + return nil, fmt.Errorf("invalid target peer %q: %w", hostPart, err) + } + return gostream.Dial(ctx, h, pid, libp2phttp.DefaultP2PProtocol) + }, + DisableKeepAlives: true, + }} +} + +// libp2pSchemeTransport sends libp2p:// requests through next as http://, so +// callers keep libp2p:// URLs, which an ordinary client refuses. +type libp2pSchemeTransport struct{ next http.RoundTripper } + +func (t libp2pSchemeTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Scheme != "libp2p" { + return nil, fmt.Errorf("unsupported scheme %q", req.URL.Scheme) + } + out := req.Clone(req.Context()) + out.URL.Scheme = "http" + return t.next.RoundTrip(out) +} diff --git a/internal/node/libp2p_transport_test.go b/internal/node/libp2p_transport_test.go new file mode 100644 index 000000000..5dc14a1b1 --- /dev/null +++ b/internal/node/libp2p_transport_test.go @@ -0,0 +1,116 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package node + +import ( + "bufio" + "context" + "net/http" + "testing" + "time" + + "github.com/libp2p/go-libp2p" + gostream "github.com/libp2p/go-libp2p-gostream" + libp2phttp "github.com/libp2p/go-libp2p-http" + "github.com/libp2p/go-libp2p/core/host" + "github.com/libp2p/go-libp2p/core/peer" +) + +// streamingPeers starts a server peer whose /stream handler sends one line and +// then waits for its request to end, reporting that on the returned channel. +func streamingPeers(t *testing.T) (client, server host.Host, ended <-chan struct{}) { + t.Helper() + newHost := func() host.Host { + h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = h.Close() }) + return h + } + server, client = newHost(), newHost() + + listener, err := gostream.Listen(server, libp2phttp.DefaultP2PProtocol) + if err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + mux := http.NewServeMux() + mux.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("first\n")) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + close(done) + case <-time.After(30 * time.Second): + } + }) + srv := &http.Server{Handler: mux} + go func() { _ = srv.Serve(listener) }() + t.Cleanup(func() { _ = srv.Close() }) + + if err := client.Connect(context.Background(), peer.AddrInfo{ID: server.ID(), Addrs: server.Addrs()}); err != nil { + t.Fatal(err) + } + return client, server, done +} + +func TestLibp2pHTTPTransportResetsStreamOnCancel(t *testing.T) { + client, server, ended := streamingPeers(t) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "libp2p://"+server.ID().String()+"/stream", nil) + if err != nil { + t.Fatal(err) + } + resp, err := newLibp2pHTTPTransport(client).RoundTrip(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + if line, err := bufio.NewReader(resp.Body).ReadString('\n'); err != nil || line != "first\n" { + t.Fatalf("first line = %q, %v", line, err) + } + + cancel() + select { + case <-ended: + case <-time.After(5 * time.Second): + t.Fatal("remote handler still running 5s after the caller cancelled") + } +} + +func TestLibp2pHTTPTransportKeepsStreamUntilCancel(t *testing.T) { + client, server, ended := streamingPeers(t) + + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "libp2p://"+server.ID().String()+"/stream", nil) + if err != nil { + t.Fatal(err) + } + resp, err := newLibp2pHTTPTransport(client).RoundTrip(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + if line, err := bufio.NewReader(resp.Body).ReadString('\n'); err != nil || line != "first\n" { + t.Fatalf("first line = %q, %v", line, err) + } + select { + case <-ended: + t.Fatal("remote handler ended although the caller kept the request open") + case <-time.After(500 * time.Millisecond): + } +} diff --git a/internal/node/openai_facade.go b/internal/node/openai_facade.go index 52c8da7e4..a560f2b18 100644 --- a/internal/node/openai_facade.go +++ b/internal/node/openai_facade.go @@ -29,7 +29,6 @@ import ( "time" "github.com/google/agentmesh/api" - libp2phttp "github.com/libp2p/go-libp2p-http" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" ) @@ -103,7 +102,7 @@ type openAIFacade struct { } func newOpenAIFacade(node *AgentMeshNode, egress http.Handler) *openAIFacade { - client := &http.Client{Transport: libp2phttp.NewTransport(node.Host)} + client := &http.Client{Transport: newLibp2pHTTPTransport(node.Host)} return &openAIFacade{ forward: egress, ttl: modelRegistryTTL, diff --git a/internal/node/sidecar.go b/internal/node/sidecar.go index 0bca8f55d..5e25a777a 100644 --- a/internal/node/sidecar.go +++ b/internal/node/sidecar.go @@ -34,7 +34,6 @@ import ( "time" "github.com/google/agentmesh/api" - libp2phttp "github.com/libp2p/go-libp2p-http" "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" ) @@ -714,7 +713,7 @@ func (node *AgentMeshNode) prepareEgressPeer(ctx context.Context, peerID string) } func createEgressProxy(node *AgentMeshNode) http.Handler { - transport := libp2phttp.NewTransport(node.Host) + transport := newLibp2pHTTPTransport(node.Host) proxy := &httputil.ReverseProxy{ Rewrite: func(pr *httputil.ProxyRequest) {