JsonClient.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Runtime.CompilerServices;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using InABox.Core;
  12. using InABox.Remote.Shared;
  13. using RestSharp;
  14. //using InABox.Logging;
  15. namespace InABox.Clients
  16. {
  17. public class CompressedResponse
  18. {
  19. public CompressedResponse()
  20. {
  21. Headers = new Dictionary<string, string>();
  22. Options = new Dictionary<string, string>();
  23. }
  24. public string ContentType { get; set; }
  25. public Dictionary<string, string> Headers { get; set; }
  26. public int Status { get; set; }
  27. public string StatusCode { get; set; }
  28. public string Response { get; set; }
  29. public Dictionary<string, string> Options { get; set; }
  30. }
  31. public class JsonClient<TEntity> : RemoteClient<TEntity> where TEntity : Entity, new()
  32. {
  33. private readonly bool _compression = true;
  34. private BinarySerializationSettings BinarySerializationSettings;
  35. public JsonClient(string url, bool useSimpleEncryption, bool compression, BinarySerializationSettings binarySerializationSettings) : base(url, useSimpleEncryption)
  36. {
  37. _compression = compression;
  38. BinarySerializationSettings = binarySerializationSettings;
  39. }
  40. public JsonClient(string url, bool useSimpleEncryption) : this(url, useSimpleEncryption, true, BinarySerializationSettings.Latest)
  41. {
  42. }
  43. public JsonClient(string url) : this(url, false, true, BinarySerializationSettings.Latest)
  44. {
  45. }
  46. public static string Ping(String[] urls, out DatabaseInfo info)
  47. {
  48. String result = "";
  49. info = new DatabaseInfo();
  50. List<Task<Tuple<String,DatabaseInfo>>> pings = urls.Select(x => Task.Run(
  51. () => new Tuple<String,DatabaseInfo>(x,new JsonClient<User>(x).Info())
  52. )).ToList();
  53. while (pings.Count > 0)
  54. {
  55. var ping = Task.WhenAny(pings).Result;
  56. if (ping.Status == TaskStatus.RanToCompletion && !String.IsNullOrWhiteSpace(ping.Result.Item2.Version))
  57. {
  58. result = ping.Result.Item1;
  59. info = ping.Result.Item2;
  60. break;
  61. }
  62. else
  63. pings.Remove(ping);
  64. }
  65. return result;
  66. }
  67. //private static void CheckSecuritySettings()
  68. //{
  69. // Boolean platformSupportsTls12 = false;
  70. // foreach (SecurityProtocolType protocol in Enum.GetValues(typeof(SecurityProtocolType)))
  71. // platformSupportsTls12 = platformSupportsTls12 || (protocol.GetHashCode() == 3072);
  72. // if (!ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072) && platformSupportsTls12)
  73. // ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
  74. // if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Ssl3))
  75. // System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
  76. //}
  77. protected override TResponse SendRequest<TRequest, TResponse>(TRequest request, string Action, SerializationFormat requestFormat, SerializationFormat responseFormat, bool includeEntity = true)
  78. {
  79. //DateTime now = DateTime.Now;
  80. //Log(" * {0}{1}() Starting..", Action, typeof(TEntity).Name);
  81. //Stopwatch sw = new Stopwatch();
  82. //sw.Start();
  83. //CheckSecuritySettings();
  84. var result = default(TResponse);
  85. if (string.IsNullOrEmpty(URL))
  86. {
  87. result = (TResponse)Activator.CreateInstance(typeof(TResponse));
  88. result.Status = StatusCode.BadServer;
  89. result.Messages.Add("Server URL not set!");
  90. return result;
  91. }
  92. //sw.Restart();
  93. //var deserialized = Serialization.Deserialize<TRequest>(json);
  94. //Log(" * {0}{1}() Serializing data took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, json.Length);
  95. //sw.Restart();
  96. var uri = new Uri(URL);
  97. var cli = new RestClient(uri);
  98. var cmd = string.Format(
  99. "{0}{1}?format={2}&responseFormat={3}&serializationVersion={4}",
  100. Action,
  101. includeEntity ? typeof(TEntity).Name : "",
  102. requestFormat,
  103. responseFormat,
  104. BinarySerializationSettings.Version
  105. );
  106. var req = new RestRequest(cmd, Method.POST)
  107. {
  108. Timeout = Timeout.Milliseconds,
  109. };
  110. //Log(" * {0}{1}() Creating Uri, Client and RestRequest took {2}ms", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds);
  111. //sw.Restart();
  112. req.AdvancedResponseWriter = (stream, response) =>
  113. {
  114. //Log(" * {0}{1}() Response from Server took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
  115. //length = response.ContentLength;
  116. //sw.Restart();
  117. try
  118. {
  119. if (responseFormat == SerializationFormat.Binary && typeof(TResponse).HasInterface<ISerializeBinary>())
  120. {
  121. result = (TResponse)Serialization.ReadBinary(typeof(TResponse), stream, BinarySerializationSettings);
  122. }
  123. else
  124. {
  125. result = Serialization.Deserialize<TResponse>(stream, true);
  126. }
  127. }
  128. catch (Exception e)
  129. {
  130. Logger.Send(LogType.Information, "", $"Error deserializing response: {e.Message}");
  131. }
  132. //Log(" * {0}{1}() Deserializing Stream took {2}ms ({3} bytes)", Action, typeof(TEntity).Name, sw.ElapsedMilliseconds, response.ContentLength);
  133. };
  134. if(requestFormat == SerializationFormat.Binary && request is ISerializeBinary binary)
  135. {
  136. var data = binary.WriteBinary(BinarySerializationSettings);
  137. req.AddOrUpdateParameter("application/octet-stream", data, ParameterType.RequestBody);
  138. req.RequestFormat = DataFormat.None;
  139. }
  140. else
  141. {
  142. var json = Serialization.Serialize(request);
  143. req.AddOrUpdateParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
  144. req.RequestFormat = DataFormat.Json;
  145. }
  146. try
  147. {
  148. //sw.Restart();
  149. var res = cli.Execute(req);
  150. //Log(" * {0}{1}() returns {2} bytes in {3}ms", Action, typeof(TEntity).Name, res.ContentLength, sw.ElapsedMilliseconds);
  151. if (result == null)
  152. {
  153. if (res.ErrorException == null)
  154. {
  155. if (res.StatusCode != HttpStatusCode.OK)
  156. throw new Exception(String.Format("HTTP Request returns {0} {1}" + (int)res.StatusCode, CoreUtils.SplitCamelCase(res.StatusCode.ToString())));
  157. try
  158. {
  159. Stream stream;
  160. if (_compression)
  161. {
  162. //sw.Restart();
  163. var comp = Serialization.Deserialize<CompressedResponse>(res.Content, true);
  164. var bytes = Convert.FromBase64String(comp.Response);
  165. var ms = new MemoryStream(bytes);
  166. stream = new MemoryStream();
  167. using (var decompressionStream = new DeflateStream(ms, CompressionMode.Decompress))
  168. {
  169. decompressionStream.CopyTo(stream);
  170. }
  171. }
  172. else
  173. {
  174. stream = new MemoryStream(res.RawBytes);
  175. }
  176. if (responseFormat == SerializationFormat.Binary && typeof(TResponse).HasInterface<ISerializeBinary>())
  177. {
  178. result = (TResponse)Serialization.ReadBinary(typeof(TResponse), stream, BinarySerializationSettings);
  179. }
  180. else
  181. {
  182. result = Serialization.Deserialize<TResponse>(stream, true);
  183. }
  184. stream.Dispose();
  185. }
  186. catch (Exception eDeserialize)
  187. {
  188. throw new Exception(string.Format("Unable to deserialize response!\n\n{0}\n\n{1}", eDeserialize.Message, res.Content));
  189. }
  190. }
  191. else
  192. {
  193. // Connectivity
  194. result = new TResponse();
  195. result.Status = StatusCode.BadServer;
  196. result.Messages.Add(res.ErrorMessage);
  197. }
  198. }
  199. }
  200. catch (Exception err)
  201. {
  202. result = new TResponse();
  203. result.Status = StatusCode.BadServer;
  204. result.Messages.Add(err.Message);
  205. if (err.InnerException != null)
  206. result.Messages.Add("- " + err.InnerException.Message);
  207. }
  208. req = null;
  209. cli = null;
  210. //double elapsed = (DateTime.Now - now).TotalMilliseconds;
  211. //Log(" * {0}{1}() completed in {2:F0}ms", Action, typeof(TEntity).Name, elapsed);
  212. return result;
  213. }
  214. // SupportedTypes() function fallback for if the server is running on ServiceStack
  215. private void SupportedTypesOld(RestClient cli, List<string> result)
  216. {
  217. var req = new RestRequest("/operations/metadata?format=csv", Method.GET) { Timeout = 20000 };
  218. try
  219. {
  220. var res = cli.Execute(req);
  221. if (res.ErrorException == null)
  222. {
  223. var lines = res.Content.Split('\n').Skip(1);
  224. foreach (var line in lines)
  225. {
  226. var fields = line.Split(',');
  227. var svc = fields[2];
  228. if (!result.Contains(svc)) result.Add(svc);
  229. //if (svc.Equals("Comal_Classes_Login"))
  230. // result.Add("InABox_Core_Login");
  231. }
  232. }
  233. }
  234. catch (Exception)
  235. {
  236. }
  237. req = null;
  238. cli = null;
  239. }
  240. // This code is duplicated in InABox.Clients.Remote.MsgPack
  241. // This should stay as-is, and work to remove RestSharp from MsgPack Client
  242. public override IEnumerable<string> SupportedTypes()
  243. {
  244. var result = new List<string>();
  245. var uri = new Uri(URL);
  246. var cli = new RestClient(uri);
  247. var req = new RestRequest("/classes", Method.GET) { Timeout = 20000 };
  248. try
  249. {
  250. var res = cli.Execute(req);
  251. if (res.StatusCode != HttpStatusCode.OK)
  252. {
  253. SupportedTypesOld(cli, result);
  254. }
  255. else if (res.ErrorException == null)
  256. {
  257. var list = res.Content.Trim('[', ']').Split(',');
  258. foreach (var operation in list)
  259. {
  260. var trimmed = operation.Trim('"');
  261. if (!result.Contains(trimmed)) result.Add(trimmed);
  262. //if (svc.Equals("Comal_Classes_Login"))
  263. // result.Add("InABox_Core_Login");
  264. }
  265. }
  266. }
  267. catch (Exception e)
  268. {
  269. }
  270. req = null;
  271. cli = null;
  272. return result.ToArray();
  273. }
  274. public override DatabaseInfo Info()
  275. {
  276. var uri = new Uri(URL);
  277. var cli = new RestClient(uri);
  278. var req = new RestRequest("/info", Method.GET) { Timeout = 20000 };
  279. try
  280. {
  281. var res = cli.Execute(req);
  282. if (res.StatusCode != HttpStatusCode.OK)
  283. {
  284. return new DatabaseInfo();
  285. }
  286. else if (res.ErrorException == null)
  287. {
  288. var info = Core.Serialization.Deserialize<InfoResponse>(res.Content);
  289. return info.Info;
  290. }
  291. }
  292. catch (Exception)
  293. {
  294. return new DatabaseInfo();
  295. }
  296. return new DatabaseInfo();
  297. }
  298. }
  299. }