|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Net.Sockets; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using Halibut.Diagnostics; |
| 6 | + |
| 7 | +namespace Halibut.Transport.Protocol |
| 8 | +{ |
| 9 | + public static class TcpClientTimeoutExtensionMethods |
| 10 | + { |
| 11 | + public static async Task WithTimeout(this TcpClient stream, HalibutTimeoutsAndLimits halibutTimeoutsAndLimits, MessageExchangeStreamTimeout timeout, Func<Task> func) |
| 12 | + { |
| 13 | + var currentReadTimeout = stream.Client.ReceiveTimeout; |
| 14 | + var currentWriteTimeout = stream.Client.SendTimeout; |
| 15 | + |
| 16 | + try |
| 17 | + { |
| 18 | + stream.SetReadAndWriteTimeouts(timeout, halibutTimeoutsAndLimits); |
| 19 | + await func(); |
| 20 | + } |
| 21 | + finally |
| 22 | + { |
| 23 | + stream.ReceiveTimeout = currentReadTimeout; |
| 24 | + stream.SendTimeout = currentWriteTimeout; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + public static void SetReadAndWriteTimeouts(this TcpClient stream, MessageExchangeStreamTimeout timeout, HalibutTimeoutsAndLimits halibutTimeoutsAndLimits) |
| 29 | + { |
| 30 | + switch (timeout) |
| 31 | + { |
| 32 | + case MessageExchangeStreamTimeout.NormalTimeout: |
| 33 | + stream.Client.SendTimeout = (int)halibutTimeoutsAndLimits.TcpClientSendTimeout.TotalMilliseconds; |
| 34 | + stream.Client.ReceiveTimeout = (int)halibutTimeoutsAndLimits.TcpClientReceiveTimeout.TotalMilliseconds; |
| 35 | + break; |
| 36 | + case MessageExchangeStreamTimeout.ControlMessageExchangeShortTimeout: |
| 37 | + stream.Client.SendTimeout = (int)halibutTimeoutsAndLimits.TcpClientHeartbeatSendTimeout.TotalMilliseconds; |
| 38 | + stream.Client.ReceiveTimeout = (int)halibutTimeoutsAndLimits.TcpClientHeartbeatReceiveTimeout.TotalMilliseconds; |
| 39 | + break; |
| 40 | + case MessageExchangeStreamTimeout.AuthenticationShortTimeout: |
| 41 | + stream.Client.SendTimeout = (int)halibutTimeoutsAndLimits.TcpClientAuthenticationSendTimeout.TotalMilliseconds; |
| 42 | + stream.Client.ReceiveTimeout = (int)halibutTimeoutsAndLimits.TcpClientAuthenticationReceiveTimeout.TotalMilliseconds; |
| 43 | + break; |
| 44 | + case MessageExchangeStreamTimeout.PollingForNextRequestShortTimeout: |
| 45 | + stream.Client.SendTimeout = (int)halibutTimeoutsAndLimits.TcpClientPollingForNextRequestSendTimeout.TotalMilliseconds; |
| 46 | + stream.Client.ReceiveTimeout = (int)halibutTimeoutsAndLimits.TcpClientPollingForNextRequestReceiveTimeout.TotalMilliseconds; |
| 47 | + break; |
| 48 | + default: |
| 49 | + throw new ArgumentOutOfRangeException(nameof(timeout), timeout, null); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments