Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
node: size inbound limits from the connection budget and count refusals
Antonio Ojea49dd3ceb75f8
diff --git a/.github/k8s/agentmesh-router-template.yaml b/.github/k8s/agentmesh-router-template.yamlindex 5aa1c78a..18fc55a7 100644--- a/.github/k8s/agentmesh-router-template.yaml+++ b/.github/k8s/agentmesh-router-template.yaml@@ -75,6 +75,7 @@ spec:- "--jwt-path=/var/run/secrets/tokens/agentmesh-token"- "--keys-path=/data/router.key"- "--metrics-addr=0.0.0.0:9090"+ - "--high-watermark=${ROUTER_HIGH_WATERMARK}"# /healthz answers as soon as the process is up; /readyz once the# router has enrolled and its libp2p host is online.startupProbe:@@ -95,8 +96,10 @@ spec:periodSeconds: 20resources:requests:- cpu: 100m- memory: 128Mi+ # A router at its watermark of 6000 members holds about 1 GiB; a+ # request below that is the first pod evicted under pressure.+ cpu: 500m+ memory: 1GivolumeMounts:- name: agentmesh-tokenmountPath: /var/run/secrets/tokensdiff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yamlindex 5bc7f331..fe433313 100644--- a/.github/workflows/deploy.yaml+++ b/.github/workflows/deploy.yaml@@ -386,6 +386,10 @@ jobs:# How many routers the environment runs; the member capacity of the# mesh is this times the high watermark over two. Unset is 3.VAR_ROUTER_REPLICAS: ${{ vars.ROUTER_REPLICAS }}+ # Members one router holds before it sheds. Unset is 6000: with two+ # routers per member, six routers hold 10,000 members with one+ # router out for a rollout.+ VAR_ROUTER_HIGH_WATERMARK: ${{ vars.ROUTER_HIGH_WATERMARK }}run: |print_rollout_diagnostics() {local namespace="$1"@@ -419,13 +423,14 @@ jobs:export CLUSTER_REGION="${VAR_CLUSTER_REGION}"export CLUSTER_NAME="${VAR_CLUSTER_NAME}"export ROUTER_REPLICAS="${VAR_ROUTER_REPLICAS:-3}"+ export ROUTER_HIGH_WATERMARK="${VAR_ROUTER_HIGH_WATERMARK:-6000}"# Remove legacy sam-router StatefulSet before applying agentmesh-router so# hostPort 4501 (TCP/UDP) on the cluster nodes is released for the new pods.kubectl delete statefulset/sam-router-${ENV_NAME} service/sam-router-${ENV_NAME} -n ${NAMESPACE} --ignore-not-foundenvsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID} ${CLUSTER_NAME} ${CLUSTER_REGION} ${IMAGE_TAG}' < .github/k8s/agentmesh-control-plane-template.yaml | kubectl apply -f -- envsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID} ${CLUSTER_NAME} ${CLUSTER_REGION} ${IMAGE_TAG} ${ROUTER_REPLICAS}' < .github/k8s/agentmesh-router-template.yaml | kubectl apply -f -+ envsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID} ${CLUSTER_NAME} ${CLUSTER_REGION} ${IMAGE_TAG} ${ROUTER_REPLICAS} ${ROUTER_HIGH_WATERMARK}' < .github/k8s/agentmesh-router-template.yaml | kubectl apply -f -envsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID} ${CLUSTER_NAME} ${CLUSTER_REGION} ${IMAGE_TAG}' < .github/k8s/agentmesh-console-template.yaml | kubectl apply -f -envsubst '${ENV_NAME} ${NAMESPACE} ${GCP_PROJECT_ID}' < .github/k8s/dns-sync-cronjob-template.yaml | kubectl apply -f -# Managed Prometheus ships with GKE; a cluster without it should not block the mesh rollout.diff --git a/internal/node/node.go b/internal/node/node.goindex e84d2c83..e1334b8a 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -545,11 +545,15 @@ func (n *AgentMeshNode) Start(ctx context.Context) error {}logger.Infof("Configured %d routers, attaching to %d: %v", len(staticRelays), n.wantRouters(), staticRelays)- cm, err := connmgr.NewConnManager(100, 400, connmgr.WithGracePeriod(time.Minute))+ cm, err := connmgr.NewConnManager(ConnLowWaterMark, ConnHighWaterMark, connmgr.WithGracePeriod(time.Minute))if err != nil {return fmt.Errorf("failed to create connection manager: %w", err)}n.connMgr = cm+ rm, err := newResourceManager()+ if err != nil {+ return fmt.Errorf("failed to create resource manager: %w", err)+ }// Layer 1: Transports & NAT Services. TLS first: Go peers and the// Node/Python SDKs land on it. Noise is what a browser can speak, and a@@ -567,6 +571,7 @@ func (n *AgentMeshNode) Start(ctx context.Context) error {libp2p.EnableRelay(),libp2p.EnableHolePunching(),libp2p.ConnectionManager(cm),+ libp2p.ResourceManager(rm),libp2p.SwarmOpts(swarm.WithDialTimeout(15 * time.Second)),libp2p.AddrsFactory(n.announceFilter),}diff --git a/internal/node/node_metrics.go b/internal/node/node_metrics.goindex a22da585..119e7689 100644--- a/internal/node/node_metrics.go+++ b/internal/node/node_metrics.go@@ -106,7 +106,7 @@ func newNodeStateCollector(n *AgentMeshNode) *nodeStateCollector {func (c *nodeStateCollector) Describe(ch chan<- *prometheus.Desc) {for _, d := range []*prometheus.Desc{c.readyDesc, c.meshConnectedDesc, c.connectedDesc, c.authenticatedDesc,- c.dhtDesc, c.biscuitExpiryDesc, c.servicesDesc, c.routersDesc, c.routerCandsDesc,+ c.dhtDesc, c.biscuitExpiryDesc, c.servicesDesc, c.routersDesc, c.routerCandsDesc, connsPerSourceIPDesc,} {ch <- d}@@ -114,6 +114,7 @@ func (c *nodeStateCollector) Describe(ch chan<- *prometheus.Desc) {func (c *nodeStateCollector) Collect(ch chan<- prometheus.Metric) {n := c.n+ ch <- prometheus.MustNewConstMetric(connsPerSourceIPDesc, prometheus.GaugeValue, float64(ConnsPerSourceIP))if n.debugReady() != nil {ch <- prometheus.MustNewConstMetric(c.readyDesc, prometheus.GaugeValue, 0)returndiff --git a/internal/node/node_metrics_test.go b/internal/node/node_metrics_test.goindex 1f5cd020..022ca533 100644--- a/internal/node/node_metrics_test.go+++ b/internal/node/node_metrics_test.go@@ -106,6 +106,8 @@ func TestNodeMetricsServer(t *testing.T) {"agentmesh_node_connected_peers 0","agentmesh_node_authenticated_peers 2","agentmesh_node_dht_routing_table_size 0",+ "agentmesh_node_conns_per_source_ip_limit 100",+ `agentmesh_node_inbound_connections_refused_total{reason="per_ip_limit"} 0`,"agentmesh_node_biscuit_expiry_timestamp_seconds " + strconv.FormatFloat(float64(expiry), 'g', -1, 64),// The process-wide registry rides along: sidecar counters and libp2p."agentmesh_node_requests_in_flight",diff --git a/internal/node/resource_limits.go b/internal/node/resource_limits.gonew file mode 100644index 00000000..7c6fff47--- /dev/null+++ b/internal/node/resource_limits.go@@ -0,0 +1,111 @@+// 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 (+ "github.com/google/agentmesh/api"+ "github.com/google/agentmesh/internal/p2plimits"+ "github.com/libp2p/go-libp2p"+ "github.com/libp2p/go-libp2p/core/network"+ "github.com/libp2p/go-libp2p/core/protocol"+ rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"+ "github.com/libp2p/go-libp2p/p2p/protocol/identify"+ "github.com/prometheus/client_golang/prometheus"+ "github.com/prometheus/client_golang/prometheus/promauto"+)++// The node's connection budget: the connection manager trims down to the+// low watermark once the high one is passed, and the resource manager+// refuses past the high one. A node that publishes a service is called by+// many members, each over a connection of its own, so the budget is sized+// for a provider rather than for a leaf that talks to a few peers.+const (+ ConnLowWaterMark = 100+ ConnHighWaterMark = 400+)++// ConnsPerSourceIP is how many inbound connections one source address may+// hold at once. Members share addresses (pod SNAT, Cloud NAT, an office, a+// fleet on one host), and libp2p's default of 8 made a provider refuse the+// ninth caller behind any of them with nothing in its logs or metrics.+var ConnsPerSourceIP = p2plimits.DefaultConnsPerSourceIP(ConnHighWaterMark)++var inboundRefusedTotal = promauto.NewCounterVec(+ prometheus.CounterOpts{+ Name: "agentmesh_node_inbound_connections_refused_total",+ Help: "Inbound connections the resource manager refused before the handshake, by reason",+ },+ []string{"reason"},+)++func init() {+ for _, v := range p2plimits.Reasons {+ inboundRefusedTotal.WithLabelValues(v)+ }+}++// connsPerSourceIPDesc exports the cap in force, so a dashboard can read the+// refusal counter against it.+var connsPerSourceIPDesc = prometheus.NewDesc(+ "agentmesh_node_conns_per_source_ip_limit",+ "Inbound connections allowed from one source IP",+ nil, nil)++// nodeLimits returns the libp2p resource limits for a node, sized from its+// connection budget rather than from host memory. libp2p's defaults scale+// with the memory the process sees: a provider in a small container got 126+// inbound connections and 47 in handshake at once, and refused a fleet+// calling it. Each connection carries a few long-lived streams and a burst+// of short ones when a caller arrives (identify, the auth handshake, the+// call itself).+func nodeLimits(conns int) rcmgr.ConcreteLimitConfig {+ limits := rcmgr.DefaultLimits+ libp2p.SetDefaultServiceLimits(&limits)+ scaled := limits.AutoScale()++ const streamsPerConn = 8+ system := p2plimits.Streams(streamsPerConn * conns)+ system.Conns = rcmgr.LimitVal(2 * conns)+ system.ConnsInbound = rcmgr.LimitVal(conns)+ system.FD = rcmgr.LimitVal(2 * conns)+ transient := p2plimits.Streams(conns)+ transient.Conns = rcmgr.LimitVal(conns)+ transient.ConnsInbound = rcmgr.LimitVal(conns)+ transient.FD = rcmgr.LimitVal(conns)++ overrides := rcmgr.PartialLimitConfig{+ System: system,+ Transient: transient,+ Service: map[string]rcmgr.ResourceLimits{+ identify.ServiceName: p2plimits.Streams(conns),+ },+ Protocol: map[protocol.ID]rcmgr.ResourceLimits{+ identify.ID: p2plimits.Streams(conns),+ identify.IDPush: p2plimits.Streams(conns),+ api.AuthProtocolID: p2plimits.Streams(conns),+ },+ }+ return overrides.Build(scaled)+}++// newResourceManager is the resource manager the node's host runs with:+// nodeLimits, the per-source cap, and every refusal counted and logged.+func newResourceManager() (network.ResourceManager, error) {+ mgr, err := p2plimits.NewResourceManager(nodeLimits(ConnHighWaterMark), ConnsPerSourceIP)+ if err != nil {+ return nil, err+ }+ return p2plimits.Observe(mgr, inboundRefusedTotal, logger.Warnf), nil+}diff --git a/internal/node/resource_limits_test.go b/internal/node/resource_limits_test.gonew file mode 100644index 00000000..a43ebc98--- /dev/null+++ b/internal/node/resource_limits_test.go@@ -0,0 +1,56 @@+// 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 (+ "testing"++ "github.com/google/agentmesh/api"+ "github.com/libp2p/go-libp2p/core/connmgr"+ rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"+ "github.com/libp2p/go-libp2p/p2p/protocol/identify"+)++// A provider in a small container must admit as many callers as its+// connection budget says, not as many as libp2p derives from its memory.+func TestNodeLimitsFollowTheConnectionBudget(t *testing.T) {+ cfg := nodeLimits(ConnHighWaterMark).ToPartialLimitConfig()+ want := func(name string, got rcmgr.LimitVal, n int) {+ t.Helper()+ if int(got) != n {+ t.Errorf("%s = %d, want %d", name, got, n)+ }+ }+ want("system inbound conns", cfg.System.ConnsInbound, ConnHighWaterMark)+ want("system conns", cfg.System.Conns, 2*ConnHighWaterMark)+ want("system inbound streams", cfg.System.StreamsInbound, 8*ConnHighWaterMark)+ want("transient inbound conns", cfg.Transient.ConnsInbound, ConnHighWaterMark)+ want("identify service inbound streams", cfg.Service[identify.ServiceName].StreamsInbound, ConnHighWaterMark)+ want("auth protocol inbound streams", cfg.Protocol[api.AuthProtocolID].StreamsInbound, ConnHighWaterMark)++ if ConnsPerSourceIP != ConnHighWaterMark/4 {+ t.Errorf("ConnsPerSourceIP = %d, want a quarter of the high watermark, %d", ConnsPerSourceIP, ConnHighWaterMark/4)+ }+ rm, err := newResourceManager()+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = rm.Close() }()+ // libp2p refuses a host whose connection manager's high watermark is+ // above what its resource manager admits.+ if l := rm.(connmgr.GetConnLimiter).GetConnLimit(); l < ConnHighWaterMark {+ t.Errorf("resource manager admits %d connections, below the high watermark %d", l, ConnHighWaterMark)+ }+}diff --git a/internal/p2plimits/limits.go b/internal/p2plimits/limits.gonew file mode 100644index 00000000..6bfbf574--- /dev/null+++ b/internal/p2plimits/limits.go@@ -0,0 +1,210 @@+// 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 p2plimits builds the libp2p resource manager a mesh component+// runs with: limits sized from its connection budget, a per-source-address+// connection cap in place of libp2p's default of 8, and a wrapper that+// counts and logs every inbound connection the manager refuses. libp2p+// refuses a connection before any byte of TLS and, for its per-IP and+// rate-limit paths, without a trace event; a dialer sees the connection+// close or a QUIC CONNECTION_REFUSED, and nothing else records it.+package p2plimits++import (+ "errors"+ "net/netip"+ "strings"+ "sync"+ "time"++ "github.com/libp2p/go-libp2p/core/connmgr"+ "github.com/libp2p/go-libp2p/core/network"+ rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"+ xrate "github.com/libp2p/go-libp2p/x/rate"+ "github.com/multiformats/go-multiaddr"+ manet "github.com/multiformats/go-multiaddr/net"+ "github.com/prometheus/client_golang/prometheus"+)++// Why the resource manager refused an inbound connection; the label values+// of a refusal counter.+const (+ RefusedPerIP = "per_ip_limit"+ RefusedRateLimit = "rate_limit"+ RefusedScope = "scope_limit"+ RefusedOther = "other"+)++// Reasons lists every refusal label, for a counter to pre-register.+var Reasons = []string{RefusedPerIP, RefusedRateLimit, RefusedScope, RefusedOther}++// ConnsPerSourceIPShare is the fraction of the inbound connection budget one+// source address may hold when no cap is configured.+const ConnsPerSourceIPShare = 4++// DefaultConnsPerSourceIP is the per-source-address cap derived from a+// connection manager high watermark. Members share addresses (pod SNAT,+// Cloud NAT, offices, a load generator), and the handshake, not the+// address, is the trust boundary.+func DefaultConnsPerSourceIP(highWaterMark int) int {+ return max(highWaterMark/ConnsPerSourceIPShare, 1)+}++// libp2pDefaultConnsPerIP is the cap the resource manager applies when none+// is configured; the per-subnet rate is scaled from it.+const libp2pDefaultConnsPerIP = 8++// NewResourceManager is libp2p's resource manager with the given limits, a+// per-source-IP inbound connection cap of perIP and the per-subnet+// connection rate limit scaled to it. Loopback is exempt from both, as in+// libp2p's default, so a local mesh never meets them.+func NewResourceManager(limits rcmgr.ConcreteLimitConfig, perIP int) (network.ResourceManager, error) {+ scale := float64(perIP) / libp2pDefaultConnsPerIP+ connRateLimiter := &xrate.Limiter{+ NetworkPrefixLimits: []xrate.PrefixLimit{+ {Prefix: netip.MustParsePrefix("127.0.0.0/8"), Limit: xrate.Limit{}},+ {Prefix: netip.MustParsePrefix("::1/128"), Limit: xrate.Limit{}},+ },+ SubnetRateLimiter: xrate.SubnetLimiter{+ IPv4SubnetLimits: []xrate.SubnetLimit{+ {PrefixLength: 32, Limit: xrate.Limit{RPS: 0.2 * scale, Burst: 2 * perIP}},+ },+ IPv6SubnetLimits: []xrate.SubnetLimit{+ {PrefixLength: 56, Limit: xrate.Limit{RPS: 0.2 * scale, Burst: 2 * perIP}},+ },+ GracePeriod: time.Minute,+ },+ }+ return rcmgr.NewResourceManager(+ rcmgr.NewFixedLimiter(limits),+ rcmgr.WithLimitPerSubnet(+ []rcmgr.ConnLimitPerSubnet{{PrefixLength: 32, ConnCount: perIP}},+ []rcmgr.ConnLimitPerSubnet{{PrefixLength: 56, ConnCount: perIP}},+ ),+ rcmgr.WithConnRateLimiters(connRateLimiter),+ )+}++// Streams is a stream budget of n each way.+func Streams(n int) rcmgr.ResourceLimits {+ return rcmgr.ResourceLimits{+ Streams: rcmgr.LimitVal(2 * n),+ StreamsInbound: rcmgr.LimitVal(n),+ StreamsOutbound: rcmgr.LimitVal(n),+ }+}++// RefusalLogInterval bounds how often one source IP's refusals are logged;+// the counter carries the rate.+const RefusalLogInterval = time.Minute++// Observed counts and logs what the wrapped manager refuses. It keeps the+// wrapped manager's connection limit visible to libp2p's connmgr sanity+// check, and leaves every scope it returns untouched.+type Observed struct {+ network.ResourceManager+ refused *prometheus.CounterVec+ warnf func(format string, args ...any)+ mu sync.Mutex+ lastLogAt map[string]time.Time+ now func() time.Time+}++// Observe wraps inner. refused is counted by reason (see Reasons) and warnf+// written once per source address per RefusalLogInterval.+func Observe(inner network.ResourceManager, refused *prometheus.CounterVec, warnf func(format string, args ...any)) *Observed {+ for _, v := range Reasons {+ refused.WithLabelValues(v)+ }+ return &Observed{ResourceManager: inner, refused: refused, warnf: warnf, lastLogAt: map[string]time.Time{}, now: time.Now}+}++// SetClock replaces the clock the log limiter reads; for tests.+func (m *Observed) SetClock(now func() time.Time) { m.now = now }++// SourcesLogged is how many source addresses the log limiter remembers.+func (m *Observed) SourcesLogged() int {+ m.mu.Lock()+ defer m.mu.Unlock()+ return len(m.lastLogAt)+}++// LastLoggedAt is when source was last logged, and whether it is remembered.+func (m *Observed) LastLoggedAt(source string) (time.Time, bool) {+ m.mu.Lock()+ defer m.mu.Unlock()+ t, ok := m.lastLogAt[source]+ return t, ok+}++func (m *Observed) OpenConnection(dir network.Direction, usefd bool, endpoint multiaddr.Multiaddr) (network.ConnManagementScope, error) {+ scope, err := m.ResourceManager.OpenConnection(dir, usefd, endpoint)+ if err != nil && dir == network.DirInbound {+ m.refusedConn(endpoint, err)+ }+ return scope, err+}++// GetConnLimit is what libp2p compares the connection manager's high water+// mark against at host construction.+func (m *Observed) GetConnLimit() int {+ if l, ok := m.ResourceManager.(connmgr.GetConnLimiter); ok {+ return l.GetConnLimit()+ }+ return 0+}++var _ connmgr.GetConnLimiter = (*Observed)(nil)++func (m *Observed) refusedConn(endpoint multiaddr.Multiaddr, err error) {+ reason := RefusalReason(err)+ m.refused.WithLabelValues(reason).Inc()++ source := "?"+ if ip, ipErr := manet.ToIP(endpoint); ipErr == nil {+ source = ip.String()+ }+ m.mu.Lock()+ last, seen := m.lastLogAt[source]+ now := m.now()+ shouldLog := !seen || now.Sub(last) >= RefusalLogInterval+ if shouldLog {+ m.lastLogAt[source] = now+ for k, t := range m.lastLogAt {+ if now.Sub(t) >= RefusalLogInterval {+ delete(m.lastLogAt, k)+ }+ }+ }+ m.mu.Unlock()+ if shouldLog {+ m.warnf("[Conn] Refused inbound connection from %s (%s): %v; the dialer sees the connection close before TLS", source, reason, err)+ }+}++// RefusalReason maps the resource manager's errors to the counter's labels.+// The per-IP and rate-limit paths return plain strings, not sentinel errors.+func RefusalReason(err error) string {+ if errors.Is(err, network.ErrResourceLimitExceeded) {+ return RefusedScope+ }+ msg := err.Error()+ switch {+ case strings.Contains(msg, "connections per ip limit"):+ return RefusedPerIP+ case strings.Contains(msg, "rate limit exceeded"):+ return RefusedRateLimit+ }+ return RefusedOther+}diff --git a/internal/p2plimits/limits_test.go b/internal/p2plimits/limits_test.gonew file mode 100644index 00000000..9db3ffed--- /dev/null+++ b/internal/p2plimits/limits_test.go@@ -0,0 +1,173 @@+// 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 p2plimits++import (+ "errors"+ "fmt"+ "testing"+ "time"++ "github.com/libp2p/go-libp2p/core/network"+ rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"+ "github.com/multiformats/go-multiaddr"+ "github.com/prometheus/client_golang/prometheus"+ dto "github.com/prometheus/client_model/go"+)++func counterValue(t *testing.T, c prometheus.Counter) float64 {+ t.Helper()+ var m dto.Metric+ if err := c.Write(&m); err != nil {+ t.Fatal(err)+ }+ return m.GetCounter().GetValue()+}++func newRefusedCounter() *prometheus.CounterVec {+ return prometheus.NewCounterVec(prometheus.CounterOpts{Name: "test_refused_total"}, []string{"reason"})+}++// refusingResourceManager answers every OpenConnection with one error.+type refusingResourceManager struct {+ network.NullResourceManager+ err error+ limit int+}++func (m *refusingResourceManager) OpenConnection(network.Direction, bool, multiaddr.Multiaddr) (network.ConnManagementScope, error) {+ if m.err != nil {+ return nil, m.err+ }+ return &network.NullScope{}, nil+}++func (m *refusingResourceManager) GetConnLimit() int { return m.limit }++func TestObservedCountsAndClassifiesRefusals(t *testing.T) {+ endpoint := multiaddr.StringCast("/ip4/104.197.44.137/tcp/51234")+ refused := newRefusedCounter()+ quiet := func(string, ...any) {}+ for _, tc := range []struct {+ err error+ reason string+ }{+ {fmt.Errorf("connections per ip limit exceeded for %s", endpoint), RefusedPerIP},+ {errors.New("rate limit exceeded"), RefusedRateLimit},+ {fmt.Errorf("cannot reserve inbound connection: %w", network.ErrResourceLimitExceeded), RefusedScope},+ {errors.New("something else"), RefusedOther},+ } {+ before := counterValue(t, refused.WithLabelValues(tc.reason))+ m := Observe(&refusingResourceManager{err: tc.err}, refused, quiet)+ if _, err := m.OpenConnection(network.DirInbound, true, endpoint); err == nil {+ t.Fatalf("%s: refusal not returned", tc.reason)+ }+ if got := counterValue(t, refused.WithLabelValues(tc.reason)); got != before+1 {+ t.Errorf("%s: counter %v, want %v", tc.reason, got, before+1)+ }+ }++ // An outbound failure is not an inbound refusal.+ before := counterValue(t, refused.WithLabelValues(RefusedOther))+ m := Observe(&refusingResourceManager{err: errors.New("dial side")}, refused, quiet)+ _, _ = m.OpenConnection(network.DirOutbound, true, endpoint)+ if got := counterValue(t, refused.WithLabelValues(RefusedOther)); got != before {+ t.Errorf("outbound failure counted as an inbound refusal")+ }++ // A granted connection is passed through and not counted.+ ok := Observe(&refusingResourceManager{limit: 42}, refused, quiet)+ if _, err := ok.OpenConnection(network.DirInbound, true, endpoint); err != nil {+ t.Fatalf("granted connection refused: %v", err)+ }+ if ok.GetConnLimit() != 42 {+ t.Errorf("GetConnLimit = %d, want the wrapped manager's 42", ok.GetConnLimit())+ }+}++func TestObservedLogsOneSourceOncePerInterval(t *testing.T) {+ now := time.Unix(1_700_000_000, 0)+ var lines []string+ m := Observe(&refusingResourceManager{err: errors.New("rate limit exceeded")}, newRefusedCounter(),+ func(format string, args ...any) { lines = append(lines, fmt.Sprintf(format, args...)) })+ m.SetClock(func() time.Time { return now })+ a := multiaddr.StringCast("/ip4/10.0.0.1/tcp/1")+ b := multiaddr.StringCast("/ip4/10.0.0.2/tcp/1")++ for i := 0; i < 3; i++ {+ _, _ = m.OpenConnection(network.DirInbound, true, a)+ }+ _, _ = m.OpenConnection(network.DirInbound, true, b)+ if m.SourcesLogged() != 2 || len(lines) != 2 {+ t.Fatalf("sources remembered = %d, lines = %d; want 2 and 2", m.SourcesLogged(), len(lines))+ }+ if at, _ := m.LastLoggedAt("10.0.0.1"); !at.Equal(now) {+ t.Errorf("first source logged at %v, want the first refusal's time", at)+ }++ // Past the interval the source is logged again and stale ones are dropped.+ now = now.Add(RefusalLogInterval)+ _, _ = m.OpenConnection(network.DirInbound, true, a)+ if at, _ := m.LastLoggedAt("10.0.0.1"); !at.Equal(now) {+ t.Errorf("source not logged again after the interval")+ }+ if _, kept := m.LastLoggedAt("10.0.0.2"); kept {+ t.Errorf("a source silent for the whole interval is still remembered")+ }+ if len(lines) != 3 {+ t.Errorf("lines = %d, want 3", len(lines))+ }+}++// The per-source cap is what the manager enforces, and loopback is exempt.+func TestNewResourceManagerCapsOneSourceAddress(t *testing.T) {+ limits := rcmgr.InfiniteLimits+ m, err := NewResourceManager(limits, 2)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = m.Close() }()+ var scopes []network.ConnManagementScope+ for i := 0; i < 2; i++ {+ s, err := m.OpenConnection(network.DirInbound, true, multiaddr.StringCast("/ip4/203.0.113.7/tcp/1"))+ if err != nil {+ t.Fatalf("connection %d from one address refused: %v", i+1, err)+ }+ scopes = append(scopes, s)+ }+ _, err = m.OpenConnection(network.DirInbound, true, multiaddr.StringCast("/ip4/203.0.113.7/tcp/1"))+ if err == nil || RefusalReason(err) != RefusedPerIP {+ t.Fatalf("third connection from one address: err = %v, want the per-IP refusal", err)+ }+ for _, s := range scopes {+ s.Done()+ }+ for i := 0; i < 5; i++ {+ s, err := m.OpenConnection(network.DirInbound, true, multiaddr.StringCast("/ip4/127.0.0.1/tcp/1"))+ if err != nil {+ t.Fatalf("loopback connection %d refused: %v", i+1, err)+ }+ defer s.Done()+ }+}++func TestDefaultConnsPerSourceIP(t *testing.T) {+ if got := DefaultConnsPerSourceIP(4000); got != 1000 {+ t.Errorf("4000 -> %d, want 1000", got)+ }+ if got := DefaultConnsPerSourceIP(2); got != 1 {+ t.Errorf("2 -> %d, want the floor of 1", got)+ }+}diff --git a/internal/router/resource_limits.go b/internal/router/resource_limits.goindex 8594a909..ac029431 100644--- a/internal/router/resource_limits.go+++ b/internal/router/resource_limits.go@@ -15,20 +15,20 @@package routerimport (- "net/netip"- "time"-"github.com/google/agentmesh/api"+ "github.com/google/agentmesh/internal/p2plimits""github.com/libp2p/go-libp2p"- "github.com/libp2p/go-libp2p/core/network""github.com/libp2p/go-libp2p/core/protocol"rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"circuit "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/proto""github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay""github.com/libp2p/go-libp2p/p2p/protocol/identify"- xrate "github.com/libp2p/go-libp2p/x/rate")+// connCapHeadroom is the resource manager's connection cap as a multiple of+// the high watermark.+const connCapHeadroom = 2+// hubLimits returns the libp2p resource limits for a router, sized from the// connection budget rather than from host memory. libp2p's defaults are for// a leaf peer that talks to a few dozen others and scale with the memory of@@ -40,27 +40,27 @@ import (// joins (identify, the auth handshake, DHT), and a service many members// call holds one relayed connection per caller.//-// conns is the inbound connection budget per source address and circuits-// the relayed connections one peer may hold; both come from Options.-func hubLimits(conns, circuits int) rcmgr.ConcreteLimitConfig {+// highWaterMark is the member count the router sheds at and conns the+// inbound connection budget per source address, both from Options; circuits+// is the relayed connections one peer may hold. The connection caps sit+// above the watermark: the connection manager trims and the router sheds+// members between the watermark and the cap, and the manager refuses only+// what neither has handled yet. A cap at the watermark refused members+// while the router still counted itself below it.+func hubLimits(highWaterMark, conns, circuits int) rcmgr.ConcreteLimitConfig {limits := rcmgr.DefaultLimitslibp2p.SetDefaultServiceLimits(&limits)scaled := limits.AutoScale()- sysBase := max(conns, DefaultHighWaterMark)+ sysBase := max(conns, highWaterMark, DefaultHighWaterMark)+ connCap := connCapHeadroom * sysBase// Streams per member on the scopes that see every member.const streamsPerConn = 8- streams := func(n int) rcmgr.ResourceLimits {- return rcmgr.ResourceLimits{- Streams: rcmgr.LimitVal(2 * n),- StreamsInbound: rcmgr.LimitVal(n),- StreamsOutbound: rcmgr.LimitVal(n),- }- }- system := streams(streamsPerConn * sysBase)- system.Conns = rcmgr.LimitVal(2 * sysBase)- system.ConnsInbound = rcmgr.LimitVal(sysBase)- system.FD = rcmgr.LimitVal(2 * sysBase)+ streams := p2plimits.Streams+ system := streams(streamsPerConn * connCap)+ system.Conns = rcmgr.LimitVal(2 * connCap)+ system.ConnsInbound = rcmgr.LimitVal(connCap)+ system.FD = rcmgr.LimitVal(2 * connCap)transient := streams(sysBase)transient.Conns = rcmgr.LimitVal(sysBase)transient.ConnsInbound = rcmgr.LimitVal(sysBase)@@ -97,41 +97,3 @@ func hubLimits(conns, circuits int) rcmgr.ConcreteLimitConfig {}return overrides.Build(scaled)}--// perIPConnResourceManager is libp2p's resource manager with hubLimits, the-// per-source-IP inbound connection cap and the per-subnet connection rate-// limit scaled to it; see Options.ConnsPerSourceIP. All of these matter-// behind a proxy or NAT: every peer shares a few source IPs, so libp2p's-// per-IP cap (8), its per-IP rate (0.2 conns/s, burst 16) and the small-// transient scope each take down the whole listener under normal reconnect-// churn.-func perIPConnResourceManager(limit, circuits int) (network.ResourceManager, error) {- // Same shape as the rcmgr default limiter (loopback exempt, no global- // cap), with the per-subnet budget scaled by limit relative to the- // default per-IP cap of 8.- scale := float64(limit) / 8- connRateLimiter := &xrate.Limiter{- NetworkPrefixLimits: []xrate.PrefixLimit{- {Prefix: netip.MustParsePrefix("127.0.0.0/8"), Limit: xrate.Limit{}},- {Prefix: netip.MustParsePrefix("::1/128"), Limit: xrate.Limit{}},- },- SubnetRateLimiter: xrate.SubnetLimiter{- IPv4SubnetLimits: []xrate.SubnetLimit{- {PrefixLength: 32, Limit: xrate.Limit{RPS: 0.2 * scale, Burst: 2 * limit}},- },- IPv6SubnetLimits: []xrate.SubnetLimit{- {PrefixLength: 56, Limit: xrate.Limit{RPS: 0.2 * scale, Burst: 2 * limit}},- },- GracePeriod: time.Minute,- },- }-- return rcmgr.NewResourceManager(- rcmgr.NewFixedLimiter(hubLimits(limit, circuits)),- rcmgr.WithLimitPerSubnet(- []rcmgr.ConnLimitPerSubnet{{PrefixLength: 32, ConnCount: limit}},- []rcmgr.ConnLimitPerSubnet{{PrefixLength: 56, ConnCount: limit}},- ),- rcmgr.WithConnRateLimiters(connRateLimiter),- )-}diff --git a/internal/router/resource_limits_test.go b/internal/router/resource_limits_test.goindex 7c8e6898..e782201b 100644--- a/internal/router/resource_limits_test.go+++ b/internal/router/resource_limits_test.go@@ -27,10 +27,11 @@ import (// TestHubLimitsFollowTheConnectionBudget pins the scopes that refused a// joining fleet on the testnet to the connection budget instead of the// host's memory: a router on a small VM must admit as many members as its-// watermarks say.+// watermarks say, and the connection cap sits above the watermark so the+// router sheds members before the manager refuses them.func TestHubLimitsFollowTheConnectionBudget(t *testing.T) {- const conns, circuits = 6000, 1024- cfg := hubLimits(conns, circuits).ToPartialLimitConfig()+ const highWaterMark, conns, circuits = 6000, 1500, 1024+ cfg := hubLimits(highWaterMark, conns, circuits).ToPartialLimitConfig()want := func(name string, got rcmgr.LimitVal, n int) {t.Helper()@@ -38,20 +39,24 @@ func TestHubLimitsFollowTheConnectionBudget(t *testing.T) {t.Errorf("%s = %d, want %d", name, got, n)}}- want("system inbound conns", cfg.System.ConnsInbound, conns)- want("system inbound streams", cfg.System.StreamsInbound, 8*conns)- want("transient inbound streams", cfg.Transient.StreamsInbound, conns)- want("identify service inbound streams", cfg.Service[identify.ServiceName].StreamsInbound, conns)- want("identify protocol inbound streams", cfg.Protocol[identify.ID].StreamsInbound, conns)- want("auth protocol inbound streams", cfg.Protocol[api.AuthProtocolID].StreamsInbound, conns)- want("relay service inbound streams", cfg.Service[relay.ServiceName].StreamsInbound, conns)- want("hop protocol inbound streams", cfg.Protocol[circuit.ProtoIDv2Hop].StreamsInbound, conns)+ want("system inbound conns", cfg.System.ConnsInbound, connCapHeadroom*highWaterMark)+ want("system conns", cfg.System.Conns, 2*connCapHeadroom*highWaterMark)+ want("system inbound streams", cfg.System.StreamsInbound, 8*connCapHeadroom*highWaterMark)+ want("transient inbound conns", cfg.Transient.ConnsInbound, highWaterMark)+ want("transient inbound streams", cfg.Transient.StreamsInbound, highWaterMark)+ want("identify service inbound streams", cfg.Service[identify.ServiceName].StreamsInbound, highWaterMark)+ want("identify protocol inbound streams", cfg.Protocol[identify.ID].StreamsInbound, highWaterMark)+ want("auth protocol inbound streams", cfg.Protocol[api.AuthProtocolID].StreamsInbound, highWaterMark)+ want("relay service inbound streams", cfg.Service[relay.ServiceName].StreamsInbound, highWaterMark)+ want("hop protocol inbound streams", cfg.Protocol[circuit.ProtoIDv2Hop].StreamsInbound, highWaterMark)// A destination many members call holds one stop stream per caller.want("relay per-peer outbound streams", cfg.ServicePeer[relay.ServiceName].StreamsOutbound, circuits)want("stop protocol per-peer outbound streams", cfg.ProtocolPeer[circuit.ProtoIDv2Stop].StreamsOutbound, circuits)- // Below the default high watermark the budget is the watermark, so a- // small per-address cap does not shrink the router.- small := hubLimits(8, circuits).ToPartialLimitConfig()- want("system inbound conns with a small per-address cap", small.System.ConnsInbound, DefaultHighWaterMark)+ // A per-address cap above the watermark widens the budget to it; a small+ // one or a small watermark does not shrink the router below the default.+ wide := hubLimits(100, 8000, circuits).ToPartialLimitConfig()+ want("system inbound conns with a wide per-address cap", wide.System.ConnsInbound, connCapHeadroom*8000)+ small := hubLimits(100, 8, circuits).ToPartialLimitConfig()+ want("system inbound conns with a small watermark and cap", small.System.ConnsInbound, connCapHeadroom*DefaultHighWaterMark)}diff --git a/internal/router/resource_observer.go b/internal/router/resource_observer.goindex 7e53999f..1c5e9bdb 100644--- a/internal/router/resource_observer.go+++ b/internal/router/resource_observer.go@@ -15,30 +15,16 @@package routerimport (- "errors"- "strings""sync""time"- "github.com/libp2p/go-libp2p/core/connmgr"+ "github.com/google/agentmesh/internal/p2plimits""github.com/libp2p/go-libp2p/core/network""github.com/libp2p/go-libp2p/core/peer"- "github.com/multiformats/go-multiaddr"- manet "github.com/multiformats/go-multiaddr/net""github.com/prometheus/client_golang/prometheus""github.com/prometheus/client_golang/prometheus/promauto")-// Why the resource manager refused an inbound connection. A refusal happens-// before any byte of TLS: the dialer sees the TCP connection close at once,-// and libp2p's own metrics count only the scope-limit case.-const (- refusedPerIP = "per_ip_limit"- refusedRateLimit = "rate_limit"- refusedScope = "scope_limit"- refusedOther = "other"-)-var inboundRefusedTotal = promauto.NewCounterVec(prometheus.CounterOpts{Name: "agentmesh_router_inbound_connections_refused_total",@@ -47,87 +33,16 @@ var inboundRefusedTotal = promauto.NewCounterVec([]string{"reason"},)-// refusalLogInterval bounds how often one source IP's refusals are logged;-// the counter carries the rate.-const refusalLogInterval = time.Minute-func init() {- for _, v := range []string{refusedPerIP, refusedRateLimit, refusedScope, refusedOther} {+ for _, v := range p2plimits.Reasons {inboundRefusedTotal.WithLabelValues(v)}}-// observedResourceManager counts and logs what the wrapped manager refuses.-// It keeps the wrapped manager's connection limit visible to libp2p's-// connmgr sanity check, and leaves every scope it returns untouched.-type observedResourceManager struct {- network.ResourceManager- mu sync.Mutex- lastLogAt map[string]time.Time- now func() time.Time-}--func observeResourceManager(inner network.ResourceManager) *observedResourceManager {- return &observedResourceManager{ResourceManager: inner, lastLogAt: map[string]time.Time{}, now: time.Now}-}--func (m *observedResourceManager) OpenConnection(dir network.Direction, usefd bool, endpoint multiaddr.Multiaddr) (network.ConnManagementScope, error) {- scope, err := m.ResourceManager.OpenConnection(dir, usefd, endpoint)- if err != nil && dir == network.DirInbound {- m.refused(endpoint, err)- }- return scope, err-}--// GetConnLimit is what libp2p compares the connection manager's high water-// mark against at host construction.-func (m *observedResourceManager) GetConnLimit() int {- if l, ok := m.ResourceManager.(connmgr.GetConnLimiter); ok {- return l.GetConnLimit()- }- return 0-}--func (m *observedResourceManager) refused(endpoint multiaddr.Multiaddr, err error) {- reason := refusalReason(err)- inboundRefusedTotal.WithLabelValues(reason).Inc()-- source := "?"- if ip, ipErr := manet.ToIP(endpoint); ipErr == nil {- source = ip.String()- }- m.mu.Lock()- last, seen := m.lastLogAt[source]- now := m.now()- shouldLog := !seen || now.Sub(last) >= refusalLogInterval- if shouldLog {- m.lastLogAt[source] = now- for k, t := range m.lastLogAt {- if now.Sub(t) >= refusalLogInterval {- delete(m.lastLogAt, k)- }- }- }- m.mu.Unlock()- if shouldLog {- logger.Warnf("[Conn] Refused inbound connection from %s (%s): %v; the dialer sees the connection close before TLS", source, reason, err)- }-}--// refusalReason maps the resource manager's errors to the counter's labels.-// The per-IP and rate-limit paths return plain strings, not sentinel errors.-func refusalReason(err error) string {- if errors.Is(err, network.ErrResourceLimitExceeded) {- return refusedScope- }- msg := err.Error()- switch {- case strings.Contains(msg, "connections per ip limit"):- return refusedPerIP- case strings.Contains(msg, "rate limit exceeded"):- return refusedRateLimit- }- return refusedOther+// observeResourceManager counts the wrapped manager's refusals in+// inboundRefusedTotal and logs them, once per source per minute.+func observeResourceManager(inner network.ResourceManager) *p2plimits.Observed {+ return p2plimits.Observe(inner, inboundRefusedTotal, logger.Warnf)}// connsPerSourceIPDesc exports the cap in force, so a dashboard can read the@@ -137,18 +52,12 @@ var connsPerSourceIPDesc = prometheus.NewDesc("Inbound connections allowed from one source IP",nil, nil)-// connsPerSourceIPShare is the fraction of the inbound connection budget one-// source address may hold when no cap is configured.-const connsPerSourceIPShare = 4-// DefaultConnsPerSourceIP is the per-source-address cap derived from a// connection manager high watermark.func DefaultConnsPerSourceIP(highWaterMark int) int {- return max(highWaterMark/connsPerSourceIPShare, 1)+ return p2plimits.DefaultConnsPerSourceIP(highWaterMark)}-var _ connmgr.GetConnLimiter = (*observedResourceManager)(nil)-// effectiveConnsPerSourceIP is the cap a dashboard should compare against.func effectiveConnsPerSourceIP(configured int) int {if configured > 0 {diff --git a/internal/router/resource_observer_test.go b/internal/router/resource_observer_test.goindex a8d2c47d..b4664210 100644--- a/internal/router/resource_observer_test.go+++ b/internal/router/resource_observer_test.go@@ -15,111 +15,12 @@package routerimport (- "errors"- "fmt""testing""time"- "github.com/libp2p/go-libp2p/core/network""github.com/libp2p/go-libp2p/core/peer"- "github.com/multiformats/go-multiaddr"- "github.com/prometheus/client_golang/prometheus"- dto "github.com/prometheus/client_model/go")-func counterValue(t *testing.T, c prometheus.Counter) float64 {- t.Helper()- var m dto.Metric- if err := c.Write(&m); err != nil {- t.Fatal(err)- }- return m.GetCounter().GetValue()-}--// refusingResourceManager answers every OpenConnection with one error.-type refusingResourceManager struct {- network.NullResourceManager- err error- limit int-}--func (m *refusingResourceManager) OpenConnection(network.Direction, bool, multiaddr.Multiaddr) (network.ConnManagementScope, error) {- if m.err != nil {- return nil, m.err- }- return &network.NullScope{}, nil-}--func (m *refusingResourceManager) GetConnLimit() int { return m.limit }--func TestObservedResourceManagerCountsAndClassifiesRefusals(t *testing.T) {- endpoint := multiaddr.StringCast("/ip4/104.197.44.137/tcp/51234")- for _, tc := range []struct {- err error- reason string- }{- {fmt.Errorf("connections per ip limit exceeded for %s", endpoint), refusedPerIP},- {errors.New("rate limit exceeded"), refusedRateLimit},- {fmt.Errorf("cannot reserve inbound connection: %w", network.ErrResourceLimitExceeded), refusedScope},- {errors.New("something else"), refusedOther},- } {- before := counterValue(t, inboundRefusedTotal.WithLabelValues(tc.reason))- m := observeResourceManager(&refusingResourceManager{err: tc.err})- if _, err := m.OpenConnection(network.DirInbound, true, endpoint); err == nil {- t.Fatalf("%s: refusal not returned", tc.reason)- }- if got := counterValue(t, inboundRefusedTotal.WithLabelValues(tc.reason)); got != before+1 {- t.Errorf("%s: counter %v, want %v", tc.reason, got, before+1)- }- }-- // An outbound failure is not an inbound refusal.- before := counterValue(t, inboundRefusedTotal.WithLabelValues(refusedOther))- m := observeResourceManager(&refusingResourceManager{err: errors.New("dial side")})- _, _ = m.OpenConnection(network.DirOutbound, true, endpoint)- if got := counterValue(t, inboundRefusedTotal.WithLabelValues(refusedOther)); got != before {- t.Errorf("outbound failure counted as an inbound refusal")- }-- // A granted connection is passed through and not counted.- ok := observeResourceManager(&refusingResourceManager{limit: 42})- if _, err := ok.OpenConnection(network.DirInbound, true, endpoint); err != nil {- t.Fatalf("granted connection refused: %v", err)- }- if ok.GetConnLimit() != 42 {- t.Errorf("GetConnLimit = %d, want the wrapped manager's 42", ok.GetConnLimit())- }-}--func TestObservedResourceManagerLogsOneSourceOncePerInterval(t *testing.T) {- now := time.Unix(1_700_000_000, 0)- m := observeResourceManager(&refusingResourceManager{err: errors.New("rate limit exceeded")})- m.now = func() time.Time { return now }- a := multiaddr.StringCast("/ip4/10.0.0.1/tcp/1")- b := multiaddr.StringCast("/ip4/10.0.0.2/tcp/1")-- for i := 0; i < 3; i++ {- _, _ = m.OpenConnection(network.DirInbound, true, a)- }- _, _ = m.OpenConnection(network.DirInbound, true, b)- if len(m.lastLogAt) != 2 {- t.Fatalf("sources remembered = %d, want 2", len(m.lastLogAt))- }- if !m.lastLogAt["10.0.0.1"].Equal(now) {- t.Errorf("first source logged at %v, want the first refusal's time", m.lastLogAt["10.0.0.1"])- }-- // Past the interval the source is logged again and stale ones are dropped.- now = now.Add(refusalLogInterval)- _, _ = m.OpenConnection(network.DirInbound, true, a)- if !m.lastLogAt["10.0.0.1"].Equal(now) {- t.Errorf("source not logged again after the interval")- }- if _, kept := m.lastLogAt["10.0.0.2"]; kept {- t.Errorf("a source silent for the whole interval is still remembered")- }-}-func TestPerPeerLogLimiter(t *testing.T) {var l perPeerLogLimiternow := time.Unix(1_700_000_000, 0)diff --git a/internal/router/router.go b/internal/router/router.goindex 5e5f218d..f776d45a 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -35,6 +35,7 @@ import ("github.com/google/agentmesh/api"cpclient "github.com/google/agentmesh/internal/controlplane/client""github.com/google/agentmesh/internal/identity"+ "github.com/google/agentmesh/internal/p2plimits""github.com/google/agentmesh/internal/ratelimit"golog "github.com/ipfs/go-log/v2""github.com/libp2p/go-libp2p"@@ -434,7 +435,7 @@ func (r *Router) Start() (retErr error) {// Every refusal the resource manager makes is counted and logged with// its source; a refused dialer only sees its connection close before TLS.- mgr, err := perIPConnResourceManager(r.config.ConnsPerSourceIP, r.config.RelayMaxCircuits)+ mgr, err := p2plimits.NewResourceManager(hubLimits(r.config.HighWaterMark, r.config.ConnsPerSourceIP, r.config.RelayMaxCircuits), r.config.ConnsPerSourceIP)if err != nil {return fmt.Errorf("failed to create resource manager: %w", err)}diff --git a/site/content/docs/guides/scalability.md b/site/content/docs/guides/scalability.mdindex 0101613a..fde857a6 100644--- a/site/content/docs/guides/scalability.md+++ b/site/content/docs/guides/scalability.md@@ -49,7 +49,8 @@ them.| Relay reservations per router | `agentmesh-router --relay-max-reservations` | the high mark (4000) | A member that cannot reserve is not reachable through that router. || Relayed connections per peer | `agentmesh-router --relay-max-circuits` | 1024 | A service called through the relay holds one circuit per caller; the next caller is refused. || Enrollments per second | control plane, fixed | 10 a second, burst 20 | The next enrollment is answered `429` with `Retry-After`; the node retries for up to three minutes. |-| Connections per node | `agentmesh-node`, fixed | 400 high, 100 low | A node called by more peers than this at once closes connections down to 100. |+| Connections per node | `agentmesh-node`, fixed | 400 high, 100 low | A node called by more peers than this at once closes connections down to 100; past 400 it refuses the next one. |+| Connections per source address at a node | `agentmesh-node`, fixed | a quarter of the high mark (100) | The node refuses the next connection from that address, counted in `agentmesh_node_inbound_connections_refused_total`. A service called by a fleet behind one NAT or one cluster's egress sees them all from one address. || Router lease | `agentmesh-control-plane --lease-duration`, `agentmesh-router --shutdown-lease-ttl` | 15m, 30s | A router that stops without the last lease stays listed for the lease duration. |The first two rows are the model. A fleet of F members on N routers, each@@ -71,7 +72,9 @@ at its default of 2, and size for the day one router is down:a stopped router and for the connections members open in passing (a DHTquery, a call to a peer on this router, two connections each while theyenroll). 5000 members on four routers need 4000; 10,000 members need- six routers at 4800 or seven at 4000.+ six routers at 4800 or seven at 4000. The testnets deploy with 6000+ (`ROUTER_HIGH_WATERMARK` in the deploy workflow) on six routers+ (`ROUTER_REPLICAS`), which holds 10,000 members with one router out.- `--low-watermark` at its default, 15% below the high mark. The gap iswhat one shedding moves to the other routers; a smaller gap sheds moreoften, a larger one moves more members at once. A router that sheds is@@ -93,7 +96,13 @@ and no limit, as `charts/agentmesh` and the testnet manifests do; thetestnet runs its routers on 2 vCPU without a limit. The router sizes itslibp2p stream limits from the watermarks, so a small VM admits as manymembers as its watermarks say; what a small VM cannot do is handshake them-quickly.+quickly. Its libp2p connection cap is twice the high watermark: between+the two, the connection manager trims and the router sheds, and the cap+refuses only what neither has handled yet. A router that reads+`agentmesh_router_inbound_connections_refused_total{reason="scope_limit"}`+rising has more connections than two watermarks, which a rollout of a+mesh at capacity produces when the stopped router's members land on the+others; the fix is a router or a higher watermark.Routers connect to one another, every pair, to run the DHT and GossipSubacross the mesh; a router never sheds those connections. That is N × (N − 1)@@ -215,6 +224,7 @@ The router and the control plane serve Prometheus metrics on| `agentmesh_router_connections{direction="inbound"}` against `agentmesh_router_connection_watermark{level="high"}` | How full a router is. The gap, summed over the routers that are not draining, is the free capacity of the mesh. || `agentmesh_router_goaway_sent_total{reason="OVERLOADED"}` | A router at its high mark sent members to the others. Rising on a router that is not draining, the fleet has outgrown its routers. || `agentmesh_router_inbound_connections_refused_total` | Members behind one address have hit `--conns-per-source-ip`. |+| `agentmesh_node_inbound_connections_refused_total{reason}` against `agentmesh_node_conns_per_source_ip_limit` | On a provider: callers it turned away before the handshake. `per_ip_limit` is a fleet behind one address, `scope_limit` more callers at once than the node's connection budget. The caller sees the connection close before TLS, or `CONNECTION_REFUSED` over QUIC, and nothing more. || `libp2p_relaysvc_reservations_total{type="opened"}` minus `{type="closed"}`, against `agentmesh_router_relay_limit{limit="reservations"}` | Reservations in use against the budget. || `libp2p_relaysvc_connection_rejections_total{reason="resource limit exceeded"}` | A service has more callers than `--relay-max-circuits`. || `libp2p_rcmgr_blocked_resources` | libp2p refused a connection or stream on a scope. On a router this should stay flat. |diff --git a/site/content/docs/reference/node-api.md b/site/content/docs/reference/node-api.mdindex dbffb2e8..d7b9a6b2 100644--- a/site/content/docs/reference/node-api.md+++ b/site/content/docs/reference/node-api.md@@ -63,7 +63,12 @@ Authorization Server.| `GET /debug/*` | token | Operator diagnostics. These answer even when the mesh is unreachable. |`--metrics-addr` serves `/metrics`, `/healthz` and `/readyz` on a second-listener without authentication, for scrapers that hold no token.+listener without authentication, for scrapers that hold no token. Besides+the gauges `/debug/mesh-info` answers on demand, `/metrics` carries+`agentmesh_node_inbound_connections_refused_total{reason}`, the inbound+connections the node turned away before the handshake, and+`agentmesh_node_conns_per_source_ip_limit`, the per-address cap they are+read against; see the scalability guide.## Token endpoint (`/oauth/token`) and revocation (`/oauth/revoke`)