JsonClient.cs 12 KB

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