Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion src/Netclaw.Providers/ProviderPluginBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// Copyright (C) 2026 - 2026 Petabridge, LLC <https://petabridge.com>
// </copyright>
// -----------------------------------------------------------------------
using System.Net.Sockets;
using Microsoft.Extensions.AI;
using Netclaw.Configuration;
using Netclaw.Configuration.Providers;
Expand Down Expand Up @@ -47,7 +48,46 @@ public Task<ProviderProbeResult> ProbeAsync(ProviderEntry entry, CancellationTok
/// </summary>
protected static HttpClient CreateLlmHttpClient(Uri? baseAddress = null)
{
return new HttpClient(new SessionAffinityHandler())
var socketHandler = new SocketsHttpHandler
{
ConnectTimeout = TimeSpan.FromSeconds(10),
PooledConnectionIdleTimeout = TimeSpan.FromSeconds(60),

// HTTP/2 PING for cloud providers that negotiate h2 over TLS.
// No-op for HTTP/1.1 connections (self-hosted backends).
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
KeepAlivePingDelay = TimeSpan.FromSeconds(15),
KeepAlivePingTimeout = TimeSpan.FromSeconds(5),

// TCP keepalive detects dead/half-open peers at the OS level.
// Probes peer liveness independently of data flow — a slow-but-alive
// prefill answers probes; a dead/restarted backend does not.
ConnectCallback = async (context, ct) =>
{
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp)
{
NoDelay = true
};

socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 10);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 5);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3);

try
{
await socket.ConnectAsync(context.DnsEndPoint, ct);
return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
}
};

return new HttpClient(new SessionAffinityHandler(socketHandler))
{
BaseAddress = baseAddress,
Timeout = TimeSpan.FromHours(1)
Expand Down
Loading