DBRaw.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Concurrent;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Linq;
  7. using System.Runtime.Versioning;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Runtime.InteropServices.ComTypes;
  11. using BeetleX.EventArgs;
  12. using Microsoft.Extensions.Caching.Memory;
  13. using Npgsql;
  14. namespace PlatformBenchmarks
  15. {
  16. public class RawDb
  17. {
  18. private readonly ConcurrentRandom _random;
  19. private readonly DbProviderFactory _dbProviderFactory;
  20. private readonly static MemoryCache _cache = new MemoryCache(
  21. new MemoryCacheOptions()
  22. {
  23. ExpirationScanFrequency = TimeSpan.FromMinutes(60)
  24. });
  25. private static readonly object[] _cacheKeys = Enumerable.Range(0, 10001).Select((i) => new CacheKey(i)).ToArray();
  26. public static string _connectionString = null;
  27. public RawDb(ConcurrentRandom random, DbProviderFactory dbProviderFactory)
  28. {
  29. _random = random;
  30. _dbProviderFactory = dbProviderFactory;
  31. OnCreateCommand();
  32. }
  33. private void OnCreateCommand()
  34. {
  35. SingleCommand = new Npgsql.NpgsqlCommand();
  36. SingleCommand.CommandText = "SELECT id, randomnumber FROM world WHERE id = @Id";
  37. mID = new Npgsql.NpgsqlParameter<int>("@Id", _random.Next(1, 10001));
  38. SingleCommand.Parameters.Add(mID);
  39. FortuneCommand = new Npgsql.NpgsqlCommand();
  40. FortuneCommand.CommandText = "SELECT id, message FROM fortune";
  41. }
  42. private DbCommand SingleCommand;
  43. private DbCommand FortuneCommand;
  44. private Npgsql.NpgsqlParameter<int> mID;
  45. private static int ListDefaultSize = 8;
  46. private World[] mWorldBuffer = null;
  47. private World[] GetWorldBuffer()
  48. {
  49. if (mWorldBuffer == null)
  50. mWorldBuffer = new World[512];
  51. return mWorldBuffer;
  52. }
  53. private Fortune[] mFortunesBuffer = null;
  54. private Fortune[] GetFortuneBuffer()
  55. {
  56. if (mFortunesBuffer == null)
  57. mFortunesBuffer = new Fortune[512];
  58. return mFortunesBuffer;
  59. }
  60. public async Task<World> LoadSingleQueryRow()
  61. {
  62. using (var db = _dbProviderFactory.CreateConnection())
  63. {
  64. db.ConnectionString = _connectionString;
  65. await db.OpenAsync();
  66. SingleCommand.Connection = db;
  67. mID.TypedValue = _random.Next(1, 10001);
  68. return await ReadSingleRow(db, SingleCommand);
  69. }
  70. }
  71. async Task<World> ReadSingleRow(DbConnection connection, DbCommand cmd)
  72. {
  73. using (var rdr = await cmd.ExecuteReaderAsync(CommandBehavior.SingleRow))
  74. {
  75. await rdr.ReadAsync();
  76. return new World
  77. {
  78. Id = rdr.GetInt32(0),
  79. RandomNumber = rdr.GetInt32(1)
  80. };
  81. }
  82. }
  83. public async Task<ArraySegment<World>> LoadMultipleQueriesRows(int count)
  84. {
  85. using (var db = _dbProviderFactory.CreateConnection())
  86. {
  87. db.ConnectionString = _connectionString;
  88. await db.OpenAsync();
  89. return await LoadMultipleRows(count, db);
  90. }
  91. }
  92. public Task<World[]> LoadCachedQueries(int count)
  93. {
  94. var result = new World[count];
  95. var cacheKeys = _cacheKeys;
  96. var cache = _cache;
  97. var random = _random;
  98. for (var i = 0; i < result.Length; i++)
  99. {
  100. var id = random.Next(1, 10001);
  101. var key = cacheKeys[id];
  102. var data = cache.Get<CachedWorld>(key);
  103. if (data != null)
  104. {
  105. result[i] = data;
  106. }
  107. else
  108. {
  109. return LoadUncachedQueries(id, i, count, this, result);
  110. }
  111. }
  112. return Task.FromResult(result);
  113. static async Task<World[]> LoadUncachedQueries(int id, int i, int count, RawDb rawdb, World[] result)
  114. {
  115. using (var db = new NpgsqlConnection(_connectionString))
  116. {
  117. await db.OpenAsync();
  118. Func<ICacheEntry, Task<CachedWorld>> create = async (entry) =>
  119. {
  120. return await rawdb.ReadSingleRow(db, rawdb.SingleCommand);
  121. };
  122. var cacheKeys = _cacheKeys;
  123. var key = cacheKeys[id];
  124. rawdb.SingleCommand.Connection = db;
  125. rawdb.mID.TypedValue = id;
  126. for (; i < result.Length; i++)
  127. {
  128. var data = await _cache.GetOrCreateAsync<CachedWorld>(key, create);
  129. result[i] = data;
  130. id = rawdb._random.Next(1, 10001);
  131. rawdb.SingleCommand.Connection = db;
  132. rawdb.mID.TypedValue = id;
  133. key = cacheKeys[id];
  134. }
  135. }
  136. return result;
  137. }
  138. }
  139. private async Task<ArraySegment<World>> LoadMultipleRows(int count, DbConnection db)
  140. {
  141. SingleCommand.Connection = db;
  142. SingleCommand.Parameters[0].Value = _random.Next(1, 10001);
  143. var result = GetWorldBuffer();
  144. for (int i = 0; i < count; i++)
  145. {
  146. result[i] = await ReadSingleRow(db, SingleCommand);
  147. SingleCommand.Parameters[0].Value = _random.Next(1, 10001);
  148. }
  149. return new ArraySegment<World>(result, 0, count);
  150. }
  151. public async Task<ArraySegment<Fortune>> LoadFortunesRows()
  152. {
  153. int count = 0;
  154. var result = GetFortuneBuffer();
  155. using (var db = new NpgsqlConnection(_connectionString))
  156. {
  157. await db.OpenAsync();
  158. FortuneCommand.Connection = db;
  159. using (var rdr = await FortuneCommand.ExecuteReaderAsync())
  160. {
  161. while (await rdr.ReadAsync())
  162. {
  163. result[count] = (new Fortune
  164. {
  165. Id = rdr.GetInt32(0),
  166. Message = rdr.GetString(1)
  167. });
  168. count++;
  169. }
  170. }
  171. }
  172. result[count] = (new Fortune { Message = "Additional fortune added at request time." });
  173. count++;
  174. Array.Sort<Fortune>(result, 0, count);
  175. return new ArraySegment<Fortune>(result, 0, count);
  176. }
  177. public async Task<World[]> LoadMultipleUpdatesRows(int count)
  178. {
  179. using (var db = new NpgsqlConnection(_connectionString))
  180. {
  181. await db.OpenAsync();
  182. var updateCmd = UpdateCommandsCached.PopCommand(count);
  183. try
  184. {
  185. var command = updateCmd.Command;
  186. command.Connection = db;
  187. SingleCommand.Connection = db;
  188. mID.TypedValue = _random.Next(1, int.MaxValue) % 10000 + 1;
  189. var results = new World[count];
  190. for (int i = 0; i < count; i++)
  191. {
  192. results[i] = await ReadSingleRow(db, SingleCommand);
  193. mID.TypedValue = _random.Next(1, int.MaxValue) % 10000 + 1;
  194. }
  195. for (int i = 0; i < count; i++)
  196. {
  197. var randomNumber = _random.Next(1, int.MaxValue) % 10000 + 1;
  198. updateCmd.Parameters[i * 2].TypedValue = results[i].Id;
  199. updateCmd.Parameters[i * 2 + 1].TypedValue = randomNumber;
  200. //updateCmd.Parameters[i * 2].Value = results[i].Id;
  201. //updateCmd.Parameters[i * 2 + 1].Value = randomNumber;
  202. results[i].RandomNumber = randomNumber;
  203. }
  204. await command.ExecuteNonQueryAsync();
  205. return results;
  206. }
  207. catch (Exception e_)
  208. {
  209. throw e_;
  210. }
  211. finally
  212. {
  213. UpdateCommandsCached.PushCommand(count, updateCmd);
  214. }
  215. }
  216. }
  217. }
  218. public sealed class CacheKey : IEquatable<CacheKey>
  219. {
  220. private readonly int _value;
  221. public CacheKey(int value)
  222. => _value = value;
  223. public bool Equals(CacheKey key)
  224. => key._value == _value;
  225. public override bool Equals(object obj)
  226. => ReferenceEquals(obj, this);
  227. public override int GetHashCode()
  228. => _value;
  229. public override string ToString()
  230. => _value.ToString();
  231. }
  232. internal class UpdateCommandsCached
  233. {
  234. private static System.Collections.Concurrent.ConcurrentStack<CommandCacheItem>[] mCacheTable
  235. = new System.Collections.Concurrent.ConcurrentStack<CommandCacheItem>[1024];
  236. public static string[] IDParamereNames = new string[1024];
  237. public static string[] RandomParamereNames = new string[1024];
  238. static UpdateCommandsCached()
  239. {
  240. for (int i = 0; i < 1024; i++)
  241. {
  242. IDParamereNames[i] = $"@Id_{i}";
  243. RandomParamereNames[i] = $"@Random_{i}";
  244. mCacheTable[i] = new System.Collections.Concurrent.ConcurrentStack<CommandCacheItem>();
  245. }
  246. }
  247. private static CommandCacheItem CreatCommand(int count)
  248. {
  249. CommandCacheItem item = new CommandCacheItem();
  250. NpgsqlCommand cmd = new Npgsql.NpgsqlCommand();
  251. cmd.CommandText = BatchUpdateString.Query(count);
  252. for (int i = 0; i < count; i++)
  253. {
  254. var id = new NpgsqlParameter<int>();
  255. id.ParameterName = IDParamereNames[i];
  256. cmd.Parameters.Add(id);
  257. item.Parameters.Add(id);
  258. var random = new NpgsqlParameter<int>();
  259. random.ParameterName = RandomParamereNames[i];
  260. cmd.Parameters.Add(random);
  261. item.Parameters.Add(random);
  262. }
  263. item.Command = cmd;
  264. return item;
  265. }
  266. public static void PushCommand(int count, CommandCacheItem cmd)
  267. {
  268. mCacheTable[count].Push(cmd);
  269. }
  270. public static CommandCacheItem PopCommand(int count)
  271. {
  272. if (mCacheTable[count].TryPop(out CommandCacheItem cmd))
  273. return cmd;
  274. return CreatCommand(count);
  275. }
  276. private static bool mInited = false;
  277. public static void Init()
  278. {
  279. if (mInited)
  280. return;
  281. lock (typeof(UpdateCommandsCached))
  282. {
  283. if (mInited)
  284. return;
  285. for (int i = 1; i <= 500; i++)
  286. {
  287. for (int k = 0; k < 10; k++)
  288. {
  289. var cmd = CreatCommand(i);
  290. mCacheTable[i].Push(cmd);
  291. }
  292. }
  293. mInited = true;
  294. HttpServer.ApiServer.Log(LogType.Info, null, $"Init update commands cached");
  295. return;
  296. }
  297. }
  298. }
  299. class CommandCacheItem
  300. {
  301. public Npgsql.NpgsqlCommand Command { get; set; }
  302. public List<Npgsql.NpgsqlParameter<int>> Parameters { get; private set; } = new List<Npgsql.NpgsqlParameter<int>>(1024);
  303. }
  304. internal class BatchUpdateString
  305. {
  306. private const int MaxBatch = 500;
  307. private static string[] _queries = new string[MaxBatch + 1];
  308. public static string Query(int batchSize)
  309. {
  310. if (_queries[batchSize] != null)
  311. {
  312. return _queries[batchSize];
  313. }
  314. var lastIndex = batchSize - 1;
  315. var sb = StringBuilderCache.Acquire();
  316. sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
  317. Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
  318. sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
  319. return _queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb);
  320. }
  321. }
  322. internal static class StringBuilderCache
  323. {
  324. private const int DefaultCapacity = 1386;
  325. private const int MaxBuilderSize = DefaultCapacity * 3;
  326. [ThreadStatic]
  327. private static StringBuilder t_cachedInstance;
  328. /// <summary>Get a StringBuilder for the specified capacity.</summary>
  329. /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks>
  330. public static StringBuilder Acquire(int capacity = DefaultCapacity)
  331. {
  332. if (capacity <= MaxBuilderSize)
  333. {
  334. StringBuilder sb = t_cachedInstance;
  335. if (capacity < DefaultCapacity)
  336. {
  337. capacity = DefaultCapacity;
  338. }
  339. if (sb != null)
  340. {
  341. // Avoid stringbuilder block fragmentation by getting a new StringBuilder
  342. // when the requested size is larger than the current capacity
  343. if (capacity <= sb.Capacity)
  344. {
  345. t_cachedInstance = null;
  346. sb.Clear();
  347. return sb;
  348. }
  349. }
  350. }
  351. return new StringBuilder(capacity);
  352. }
  353. public static void Release(StringBuilder sb)
  354. {
  355. if (sb.Capacity <= MaxBuilderSize)
  356. {
  357. t_cachedInstance = sb;
  358. }
  359. }
  360. public static string GetStringAndRelease(StringBuilder sb)
  361. {
  362. string result = sb.ToString();
  363. Release(sb);
  364. return result;
  365. }
  366. }
  367. }