JsonClient.cs 12 KB

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