|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Net.Http; |
| 4 | +using System.Net.Http.Headers; |
| 5 | +using System.Text; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Nethereum.JsonRpc.Client.RpcMessages; |
| 9 | +using Nethereum.JsonRpc.Client; |
| 10 | +using Newtonsoft.Json; |
| 11 | + |
| 12 | +namespace Thirdweb |
| 13 | +{ |
| 14 | + public class ThirdwebClient : ClientBase |
| 15 | + { |
| 16 | + private const int NUMBER_OF_SECONDS_TO_RECREATE_HTTP_CLIENT = 60; |
| 17 | + public static int MaximumConnectionsPerServer { get; set; } = 20; |
| 18 | + private readonly Uri _baseUrl; |
| 19 | + private readonly HttpClientHandler _httpClientHandler; |
| 20 | + private readonly JsonSerializerSettings _jsonSerializerSettings; |
| 21 | + private volatile bool _firstHttpClient; |
| 22 | + private HttpClient _httpClient; |
| 23 | + private HttpClient _httpClient2; |
| 24 | + private bool _rotateHttpClients = true; |
| 25 | + private DateTime _httpClientLastCreatedAt; |
| 26 | + private readonly object _lockObject = new object(); |
| 27 | + |
| 28 | + public ThirdwebClient(Uri baseUrl, JsonSerializerSettings jsonSerializerSettings = null, HttpClientHandler httpClientHandler = null) |
| 29 | + { |
| 30 | + _baseUrl = baseUrl; |
| 31 | + |
| 32 | + if (jsonSerializerSettings == null) |
| 33 | + jsonSerializerSettings = DefaultJsonSerializerSettingsFactory.BuildDefaultJsonSerializerSettings(); |
| 34 | + |
| 35 | + _jsonSerializerSettings = jsonSerializerSettings; |
| 36 | + _httpClientHandler = httpClientHandler; |
| 37 | + |
| 38 | +#if NETCOREAPP2_1 || NETCOREAPP3_1 || NET5_0_OR_GREATER |
| 39 | + _httpClient = CreateNewHttpClient(); |
| 40 | + _rotateHttpClients = false; |
| 41 | +#else |
| 42 | + CreateNewRotatedHttpClient(); |
| 43 | +#endif |
| 44 | + } |
| 45 | + |
| 46 | + private static HttpMessageHandler GetDefaultHandler() |
| 47 | + { |
| 48 | + try |
| 49 | + { |
| 50 | +#if NETSTANDARD2_0 |
| 51 | + return new HttpClientHandler |
| 52 | + { |
| 53 | + MaxConnectionsPerServer = MaximumConnectionsPerServer |
| 54 | + }; |
| 55 | + |
| 56 | +#elif NETCOREAPP2_1 || NETCOREAPP3_1 || NET5_0_OR_GREATER |
| 57 | + return new SocketsHttpHandler |
| 58 | + { |
| 59 | + PooledConnectionLifetime = new TimeSpan(0, NUMBER_OF_SECONDS_TO_RECREATE_HTTP_CLIENT, 0), |
| 60 | + PooledConnectionIdleTimeout = new TimeSpan(0, NUMBER_OF_SECONDS_TO_RECREATE_HTTP_CLIENT, 0), |
| 61 | + MaxConnectionsPerServer = MaximumConnectionsPerServer |
| 62 | + }; |
| 63 | +#else |
| 64 | + return null; |
| 65 | +#endif |
| 66 | + } |
| 67 | + catch |
| 68 | + { |
| 69 | + return null; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + public ThirdwebClient(Uri baseUrl, HttpClient httpClient, AuthenticationHeaderValue authHeaderValue = null, JsonSerializerSettings jsonSerializerSettings = null) |
| 74 | + { |
| 75 | + _baseUrl = baseUrl; |
| 76 | + |
| 77 | + if (authHeaderValue == null) |
| 78 | + { |
| 79 | + authHeaderValue = BasicAuthenticationHeaderHelper.GetBasicAuthenticationHeaderValueFromUri(baseUrl); |
| 80 | + } |
| 81 | + |
| 82 | + if (jsonSerializerSettings == null) |
| 83 | + jsonSerializerSettings = DefaultJsonSerializerSettingsFactory.BuildDefaultJsonSerializerSettings(); |
| 84 | + _jsonSerializerSettings = jsonSerializerSettings; |
| 85 | + InitialiseHttpClient(httpClient); |
| 86 | + _httpClient = httpClient; |
| 87 | + _rotateHttpClients = false; |
| 88 | + } |
| 89 | + |
| 90 | + protected override async Task<RpcResponseMessage[]> SendAsync(RpcRequestMessage[] requests) |
| 91 | + { |
| 92 | + try |
| 93 | + { |
| 94 | + var httpClient = GetOrCreateHttpClient(); |
| 95 | + var rpcRequestJson = JsonConvert.SerializeObject(requests, _jsonSerializerSettings); |
| 96 | + var httpContent = new StringContent(rpcRequestJson, Encoding.UTF8, "application/json"); |
| 97 | + var cancellationTokenSource = new CancellationTokenSource(); |
| 98 | + cancellationTokenSource.CancelAfter(ConnectionTimeout); |
| 99 | + |
| 100 | + var httpResponseMessage = await httpClient.PostAsync(String.Empty, httpContent, cancellationTokenSource.Token).ConfigureAwait(false); |
| 101 | + httpResponseMessage.EnsureSuccessStatusCode(); |
| 102 | + |
| 103 | + var stream = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false); |
| 104 | + using (var streamReader = new StreamReader(stream)) |
| 105 | + using (var reader = new JsonTextReader(streamReader)) |
| 106 | + { |
| 107 | + var serializer = JsonSerializer.Create(_jsonSerializerSettings); |
| 108 | + var messages = serializer.Deserialize<RpcResponseMessage[]>(reader); |
| 109 | + |
| 110 | + return messages; |
| 111 | + } |
| 112 | + } |
| 113 | + catch (TaskCanceledException ex) |
| 114 | + { |
| 115 | + var exception = new RpcClientTimeoutException($"Rpc timeout after {ConnectionTimeout.TotalMilliseconds} milliseconds", ex); |
| 116 | + throw exception; |
| 117 | + } |
| 118 | + catch (Exception ex) |
| 119 | + { |
| 120 | + var exception = new RpcClientUnknownException("Error occurred when trying to send multiple rpc requests(s)", ex); |
| 121 | + throw exception; |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + protected override async Task<RpcResponseMessage> SendAsync(RpcRequestMessage request, string route = null) |
| 126 | + { |
| 127 | + try |
| 128 | + { |
| 129 | + var httpClient = GetOrCreateHttpClient(); |
| 130 | + var rpcRequestJson = JsonConvert.SerializeObject(request, _jsonSerializerSettings); |
| 131 | + var httpContent = new StringContent(rpcRequestJson, Encoding.UTF8, "application/json"); |
| 132 | + var cancellationTokenSource = new CancellationTokenSource(); |
| 133 | + cancellationTokenSource.CancelAfter(ConnectionTimeout); |
| 134 | + |
| 135 | + var httpResponseMessage = await httpClient.PostAsync(route, httpContent, cancellationTokenSource.Token).ConfigureAwait(false); |
| 136 | + httpResponseMessage.EnsureSuccessStatusCode(); |
| 137 | + |
| 138 | + var stream = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false); |
| 139 | + using (var streamReader = new StreamReader(stream)) |
| 140 | + using (var reader = new JsonTextReader(streamReader)) |
| 141 | + { |
| 142 | + var serializer = JsonSerializer.Create(_jsonSerializerSettings); |
| 143 | + var message = serializer.Deserialize<RpcResponseMessage>(reader); |
| 144 | + return message; |
| 145 | + } |
| 146 | + } |
| 147 | + catch (TaskCanceledException ex) |
| 148 | + { |
| 149 | + var exception = new RpcClientTimeoutException($"Rpc timeout after {ConnectionTimeout.TotalMilliseconds} milliseconds", ex); |
| 150 | + throw exception; |
| 151 | + } |
| 152 | + catch (Exception ex) |
| 153 | + { |
| 154 | + var exception = new RpcClientUnknownException("Error occurred when trying to send rpc requests(s): " + request.Method, ex); |
| 155 | + throw exception; |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + private HttpClient GetOrCreateHttpClient() |
| 160 | + { |
| 161 | + if (_rotateHttpClients) //already created if not rotated |
| 162 | + { |
| 163 | + lock (_lockObject) |
| 164 | + { |
| 165 | + var timeSinceCreated = DateTime.UtcNow - _httpClientLastCreatedAt; |
| 166 | + if (timeSinceCreated.TotalSeconds > NUMBER_OF_SECONDS_TO_RECREATE_HTTP_CLIENT) |
| 167 | + CreateNewRotatedHttpClient(); |
| 168 | + return GetClient(); |
| 169 | + } |
| 170 | + } |
| 171 | + else |
| 172 | + { |
| 173 | + return GetClient(); |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + private HttpClient GetClient() |
| 178 | + { |
| 179 | + if (_rotateHttpClients) |
| 180 | + { |
| 181 | + lock (_lockObject) |
| 182 | + { |
| 183 | + return _firstHttpClient ? _httpClient : _httpClient2; |
| 184 | + } |
| 185 | + } |
| 186 | + else |
| 187 | + { |
| 188 | + return _httpClient; |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + private void CreateNewRotatedHttpClient() |
| 193 | + { |
| 194 | + var httpClient = CreateNewHttpClient(); |
| 195 | + _httpClientLastCreatedAt = DateTime.UtcNow; |
| 196 | + |
| 197 | + if (_firstHttpClient) |
| 198 | + { |
| 199 | + lock (_lockObject) |
| 200 | + { |
| 201 | + _firstHttpClient = false; |
| 202 | + _httpClient2 = httpClient; |
| 203 | + } |
| 204 | + } |
| 205 | + else |
| 206 | + { |
| 207 | + lock (_lockObject) |
| 208 | + { |
| 209 | + _firstHttpClient = true; |
| 210 | + _httpClient = httpClient; |
| 211 | + } |
| 212 | + } |
| 213 | + } |
| 214 | + |
| 215 | + private HttpClient CreateNewHttpClient() |
| 216 | + { |
| 217 | + HttpClient httpClient = new HttpClient(); |
| 218 | + |
| 219 | + if (_httpClientHandler != null) |
| 220 | + { |
| 221 | + httpClient = new HttpClient(_httpClientHandler); |
| 222 | + } |
| 223 | + else |
| 224 | + { |
| 225 | + var handler = GetDefaultHandler(); |
| 226 | + if (handler != null) |
| 227 | + { |
| 228 | + httpClient = new HttpClient(handler); |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | + InitialiseHttpClient(httpClient); |
| 233 | + return httpClient; |
| 234 | + } |
| 235 | + |
| 236 | + private void InitialiseHttpClient(HttpClient httpClient) |
| 237 | + { |
| 238 | + httpClient.DefaultRequestHeaders.Add("x-sdk-name", "UnitySDK"); |
| 239 | + httpClient.DefaultRequestHeaders.Add("x-sdk-platform", Utils.GetRuntimePlatform()); |
| 240 | + httpClient.DefaultRequestHeaders.Add("x-sdk-version", ThirdwebSDK.version); |
| 241 | + httpClient.BaseAddress = _baseUrl; |
| 242 | + } |
| 243 | + } |
| 244 | +} |
0 commit comments