Skip to content
This repository was archived by the owner on Jul 9, 2023. It is now read-only.

Commit 7b0d41f

Browse files
Merge pull request #525 from justcoding121/master
refactor connection generation
2 parents 98f198d + f88da92 commit 7b0d41f

File tree

2 files changed

+37
-61
lines changed

2 files changed

+37
-61
lines changed

src/Titanium.Web.Proxy/RequestHandler.cs

Lines changed: 29 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -198,37 +198,13 @@ await clientStreamWriter.WriteResponseAsync(args.HttpClient.Response,
198198
connection = null;
199199
}
200200

201-
RetryResult result;
202-
if (request.UpgradeToWebSocket)
203-
{
204-
//a connection generator task with captured parameters via closure.
205-
Func<Task<TcpServerConnection>> generator = () =>
206-
tcpConnectionFactory.GetServerConnection(this, args, isConnect: false,
207-
applicationProtocol: clientConnection.NegotiatedApplicationProtocol,
208-
noCache: false, cancellationToken: cancellationToken);
209-
210-
//for connection pool, retry fails until cache is exhausted.
211-
result = await retryPolicy<ServerConnectionException>().ExecuteAsync(async (serverConnection) =>
212-
{
213-
args.TimeLine["Connection Ready"] = DateTime.Now;
214-
215-
// if upgrading to websocket then relay the request without reading the contents
216-
await handleWebSocketUpgrade(httpCmd, args, request,
217-
response, clientStream, clientStreamWriter,
218-
serverConnection, cancellationTokenSource, cancellationToken);
219-
closeServerConnection = true;
220-
return false;
221-
222-
}, generator, connection);
223-
}
224-
else
225-
{
226-
result = await handleHttpSessionRequest(args, connection,
227-
clientConnection.NegotiatedApplicationProtocol, cancellationToken);
228-
}
201+
var result = await handleHttpSessionRequest(httpCmd, args, connection,
202+
clientConnection.NegotiatedApplicationProtocol,
203+
cancellationToken, cancellationTokenSource);
229204

230205
//update connection to latest used
231206
connection = result.LatestConnection;
207+
closeServerConnection = !result.Continue;
232208

233209
//throw if exception happened
234210
if (!result.IsSuccess)
@@ -260,13 +236,13 @@ await handleWebSocketUpgrade(httpCmd, args, request,
260236
throw new Exception("Session was terminated by user.");
261237
}
262238

263-
//Get/release server connection for each HTTP session instead of per client connection.
239+
//Release server connection for each HTTP session instead of per client connection.
264240
//This will be more efficient especially when client is idly holding server connection
265241
//between sessions without using it.
266242
//Do not release authenticated connections for performance reasons.
267243
//Otherwise it will keep authenticating per session.
268244
if (EnableConnectionPool && connection != null
269-
&& !connection.IsWinAuthenticated)
245+
&& !connection.IsWinAuthenticated)
270246
{
271247
await tcpConnectionFactory.Release(connection);
272248
connection = null;
@@ -300,45 +276,40 @@ await tcpConnectionFactory.Release(connection,
300276
}
301277
}
302278

303-
private async Task<RetryResult> handleHttpSessionRequest(SessionEventArgs args,
304-
TcpServerConnection connection,
305-
SslApplicationProtocol protocol,
306-
CancellationToken cancellationToken)
279+
private async Task<RetryResult> handleHttpSessionRequest(string httpCmd, SessionEventArgs args,
280+
TcpServerConnection serverConnection, SslApplicationProtocol sslApplicationProtocol,
281+
CancellationToken cancellationToken, CancellationTokenSource cancellationTokenSource)
307282
{
308-
//host/scheme changed from ReRequest
309-
if (args.ReRequest
310-
&& (args.HttpClient.Request.IsHttps != connection.IsHttps
311-
|| args.HttpClient.Request.Host != connection.HostName))
312-
{
313-
connection = null;
314-
}
315-
316-
317283
//a connection generator task with captured parameters via closure.
318284
Func<Task<TcpServerConnection>> generator = () =>
319-
tcpConnectionFactory.GetServerConnection(this, args, isConnect: false,
320-
applicationProtocol: protocol,
321-
noCache: false, cancellationToken: cancellationToken);
285+
tcpConnectionFactory.GetServerConnection(this, args, isConnect: false,
286+
applicationProtocol: sslApplicationProtocol,
287+
noCache: false, cancellationToken: cancellationToken);
322288

323289
//for connection pool, retry fails until cache is exhausted.
324-
return await retryPolicy<ServerConnectionException>().ExecuteAsync(async (serverConnection) =>
290+
return await retryPolicy<ServerConnectionException>().ExecuteAsync(async (connection) =>
325291
{
326292
args.TimeLine["Connection Ready"] = DateTime.Now;
327293

294+
if (args.HttpClient.Request.UpgradeToWebSocket)
295+
{
296+
// if upgrading to websocket then relay the request without reading the contents
297+
await handleWebSocketUpgrade(httpCmd, args, args.HttpClient.Request,
298+
args.HttpClient.Response, args.ProxyClient.ClientStream, args.ProxyClient.ClientStreamWriter,
299+
connection, cancellationTokenSource, cancellationToken);
300+
return false;
301+
}
302+
303+
args.TimeLine["Connection Ready"] = DateTime.Now;
304+
328305
// construct the web request that we are going to issue on behalf of the client.
329-
await handleHttpSessionRequest(serverConnection, args);
306+
await handleHttpSessionRequest(connection, args);
330307
return true;
331308

332-
}, generator, connection);
309+
}, generator, serverConnection);
333310
}
334311

335-
/// <summary>
336-
/// Handle a specific session (request/response sequence)
337-
/// </summary>
338-
/// <param name="serverConnection">The tcp connection.</param>
339-
/// <param name="args">The session event arguments.</param>
340-
/// <returns></returns>
341-
private async Task handleHttpSessionRequest(TcpServerConnection serverConnection, SessionEventArgs args)
312+
private async Task handleHttpSessionRequest(TcpServerConnection connection, SessionEventArgs args)
342313
{
343314
var cancellationToken = args.CancellationTokenSource.Token;
344315
var request = args.HttpClient.Request;
@@ -350,7 +321,7 @@ private async Task handleHttpSessionRequest(TcpServerConnection serverConnection
350321
// and see if server would return 100 conitinue
351322
if (request.ExpectContinue)
352323
{
353-
args.HttpClient.SetConnection(serverConnection);
324+
args.HttpClient.SetConnection(connection);
354325
await args.HttpClient.SendRequest(Enable100ContinueBehaviour, args.IsTransparent,
355326
cancellationToken);
356327
}
@@ -377,7 +348,7 @@ await clientStreamWriter.WriteResponseStatusAsync(args.HttpClient.Response.HttpV
377348
// If expect continue is not enabled then set the connectio and send request headers
378349
if (!request.ExpectContinue)
379350
{
380-
args.HttpClient.SetConnection(serverConnection);
351+
args.HttpClient.SetConnection(connection);
381352
await args.HttpClient.SendRequest(Enable100ContinueBehaviour, args.IsTransparent,
382353
cancellationToken);
383354
}

src/Titanium.Web.Proxy/ResponseHandler.cs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Threading.Tasks;
44
using Titanium.Web.Proxy.EventArguments;
55
using Titanium.Web.Proxy.Extensions;
6+
using Titanium.Web.Proxy.Http;
67
using Titanium.Web.Proxy.Network.WinAuth.Security;
78

89
namespace Titanium.Web.Proxy
@@ -63,7 +64,7 @@ private async Task handleHttpSessionResponse(SessionEventArgs args)
6364
//write custom user response with body and return.
6465
await clientStreamWriter.WriteResponseAsync(response, cancellationToken: cancellationToken);
6566

66-
if(args.HttpClient.Connection != null
67+
if (args.HttpClient.Connection != null
6768
&& !args.HttpClient.CloseServerConnection)
6869
{
6970
// syphon out the original response body from server connection
@@ -78,10 +79,14 @@ private async Task handleHttpSessionResponse(SessionEventArgs args)
7879
// likely after making modifications from User Response Handler
7980
if (args.ReRequest)
8081
{
82+
await tcpConnectionFactory.Release(args.HttpClient.Connection);
83+
8184
// clear current response
8285
await args.ClearResponse(cancellationToken);
83-
await handleHttpSessionRequest(args, args.HttpClient.Connection,
84-
args.ClientConnection.NegotiatedApplicationProtocol, cancellationToken);
86+
var httpCmd = Request.CreateRequestLine(args.HttpClient.Request.Method,
87+
args.HttpClient.Request.OriginalUrl, args.HttpClient.Request.HttpVersion);
88+
await handleHttpSessionRequest(httpCmd, args, null, args.ClientConnection.NegotiatedApplicationProtocol,
89+
cancellationToken, args.CancellationTokenSource);
8590
return;
8691
}
8792

0 commit comments

Comments
 (0)