This repository was archived by the owner on Mar 30, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdankdb.cs
More file actions
636 lines (583 loc) · 21.2 KB
/
dankdb.cs
File metadata and controls
636 lines (583 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
using System.Collections.Concurrent;
using System.Numerics;
using System.Text.Json;
// Version 14.1
// Created by ItzKITb
// GNU license
namespace DankDB
{
public class Worker
{
public static LruCache<string, CacheItem> cache = new(1000);
internal static ConcurrentDictionary<string, SemaphoreSlim> file_locks = new();
public static bool debug = false;
internal static DateTime start = DateTime.UtcNow;
public static readonly int version = 14;
}
/// <summary>
/// Database statistics
/// </summary>
public class Statistics
{
/// <summary>
/// Total reads
/// </summary>
public static BigInteger reads { internal set; get; } = 0;
/// <summary>
/// Total writes
/// </summary>
public static BigInteger writes { internal set; get; } = 0;
/// <summary>
/// Total cache reads
/// </summary>
public static BigInteger cache_reads { internal set; get; } = 0;
/// <summary>
/// Total cache writes
/// </summary>
public static BigInteger cache_writes { internal set; get; } = 0;
/// <summary>
/// Total removes
/// </summary>
public static BigInteger removes { internal set; get; } = 0;
/// <summary>
/// Total renames
/// </summary>
public static BigInteger renames { internal set; get; } = 0;
/// <summary>
/// Total files checks
/// </summary>
public static BigInteger checks { internal set; get; } = 0;
}
/// <summary>
/// Database sync manager
/// </summary>
public class Manager
{
/// <summary>
/// Create a database and write empty data into it
/// </summary>
/// <param name="path"></param>
public static void CreateDatabase(string path)
{
Statistics.checks++;
if (!File.Exists(path))
{
File.WriteAllText(path, "{}");
Debugger.Write($"[Sync] Database \"{path}\" created.");
Statistics.writes++;
}
}
/// <summary>
/// Add/Overwrite information in a specific database key
/// </summary>
/// <param name="path"></param>
/// <param name="key"></param>
/// <param name="data"></param>
public static void Save(string path, string key, object data)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
semaphore.Wait();
try
{
var cacheItem = LoadCacheItem(path);
cacheItem.data[key] = JsonSerializer.SerializeToElement(data);
SaveCacheItem(path, cacheItem);
Debugger.Write($"[Sync] Data \"{data}\" in key \"{key}\" is stored in \"{path}\".");
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Get data from database key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path"></param>
/// <param name="key"></param>
/// <returns>Data in the database key</returns>
public static T Get<T>(string path, string key)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
semaphore.Wait();
try
{
var cacheItem = LoadCacheItem(path);
Debugger.Write($"[Sync] The key \"{key}\" from the file \"{path}\" was successfully retrieved.");
return cacheItem.data.TryGetValue(key, out var value)
? JsonSerializer.Deserialize<T>(value.GetRawText())
: default;
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Delete key from database
/// </summary>
/// <param name="path"></param>
/// <param name="key"></param>
public static void DeleteKey(string path, string key)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
semaphore.Wait();
try
{
var cacheItem = LoadCacheItem(path);
if (cacheItem.data.Remove(key))
{
Statistics.removes++;
SaveCacheItem(path, cacheItem);
Debugger.Write($"[Sync] Key \"{key}\" in file \"{path}\" removed.");
}
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Check if such key exists in the database
/// </summary>
/// <param name="path"></param>
/// <param name="key"></param>
public static bool IsContainsKey(string path, string key)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
semaphore.Wait();
try
{
var cacheItem = LoadCacheItem(path);
Debugger.Write($"[Sync] The key \"{key}\" from the file \"{path}\" was successfully retrieved.");
return cacheItem.data.ContainsKey(key);
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Change the name of the key in the database
/// </summary>
/// <param name="path"></param>
/// <param name="oldKey"></param>
/// <param name="newKey"></param>
public static void RenameKey(string path, string oldKey, string newKey)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
semaphore.Wait();
try
{
var cacheItem = LoadCacheItem(path);
if (cacheItem.data.TryGetValue(oldKey, out var value))
{
cacheItem.data.Remove(oldKey);
cacheItem.data[newKey] = value;
Statistics.renames++;
SaveCacheItem(path, cacheItem);
Debugger.Write($"[Sync] The key \"{oldKey}\" in the file \"{path}\" has been renamed to \"{newKey}\".");
}
}
finally
{
semaphore.Release();
}
}
private static CacheItem LoadCacheItem(string path)
{
Statistics.checks++;
var fileInfo = new FileInfo(path);
fileInfo.Refresh();
var currentLastModified = fileInfo.Exists ? fileInfo.LastWriteTimeUtc : DateTime.MinValue;
if (Worker.cache.TryGet(path, out var cachedItem) &&
cachedItem.last_modified.ToString() == currentLastModified.ToString())
{
Statistics.cache_reads++;
Debugger.Write($"[Sync] Data for file \"{path}\" loaded from cache.");
return cachedItem;
}
Debugger.Write($"[Sync] Loading from file. ({(cachedItem == null ? "null" : cachedItem)}, {(cachedItem == null ? "null" : cachedItem.last_modified == currentLastModified)}, {(cachedItem == null ? "null" : cachedItem.last_modified)}, {currentLastModified})");
Dictionary<string, JsonElement> data;
Statistics.reads++;
if (File.Exists(path))
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
data = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(stream);
}
else
{
data = new Dictionary<string, JsonElement>();
}
var newCacheItem = new CacheItem { data = data, last_modified = currentLastModified };
Worker.cache.AddOrUpdate(path, newCacheItem);
Debugger.Write("[Sync] Loaded.");
return newCacheItem;
}
private static void SaveCacheItem(string path, CacheItem cacheItem)
{
using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
JsonSerializer.Serialize(stream, cacheItem.data);
Statistics.writes++;
var fileInfo = new FileInfo(path);
fileInfo.Refresh();
cacheItem.last_modified = fileInfo.LastWriteTimeUtc;
Worker.cache.AddOrUpdate(path, cacheItem);
Statistics.cache_writes++;
Debugger.Write($"[Sync] File \"{path}\" saved.");
}
}
/// <summary>
/// Database async
/// </summary>
public class AsyncManager
{
/// <summary>
/// Create a database and write empty data into it
/// </summary>
/// <param name="path"></param>
public static async Task CreateDatabase(string path)
{
Statistics.checks++;
if (!File.Exists(path))
{
await File.WriteAllTextAsync(path, "{}");
Debugger.Write($"[Async] Database \"{path}\" created.");
Statistics.writes++;
}
}
/// <summary>
/// Add/Overwrite information in a specific database key
/// </summary>
/// <param name="path"></param>
/// <param name="key"></param>
/// <param name="data"></param>
public static async Task Save(string path, string key, object data)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync();
try
{
var cacheItem = await LoadCacheItem(path);
cacheItem.data[key] = JsonSerializer.SerializeToElement(data);
await SaveCacheItem(path, cacheItem);
Debugger.Write($"[Async] Data \"{data}\" in key \"{key}\" is stored in \"{path}\".");
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Get data from database key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path"></param>
/// <param name="key"></param>
/// <returns>Data in the database key</returns>
public static async Task<T> Get<T>(string path, string key)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync();
try
{
var cacheItem = await LoadCacheItem(path);
Debugger.Write($"[Async] The key \"{key}\" from the file \"{path}\" was successfully retrieved.");
return cacheItem.data.TryGetValue(key, out var value)
? JsonSerializer.Deserialize<T>(value.GetRawText())
: default;
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Delete key from database
/// </summary>
/// <param name="path"></param>
/// <param name="key"></param>
public static async Task DeleteKey(string path, string key)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync();
try
{
var cacheItem = await LoadCacheItem(path);
if (cacheItem.data.Remove(key))
{
await SaveCacheItem(path, cacheItem);
Statistics.removes++;
Debugger.Write($"[Async] Key \"{key}\" in file \"{path}\" removed.");
}
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Check if such key exists in the database
/// </summary>
/// <param name="path"></param>
/// <param name="key"></param>
public static async Task<bool> IsContainsKey(string path, string key)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
semaphore.Wait();
try
{
var cacheItem = await LoadCacheItem(path);
Debugger.Write($"[Sync] The key \"{key}\" from the file \"{path}\" was successfully retrieved.");
return cacheItem.data.ContainsKey(key);
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Change the name of the key in the database
/// </summary>
/// <param name="path"></param>
/// <param name="oldKey"></param>
/// <param name="newKey"></param>
public static async Task RenameKey(string path, string oldKey, string newKey)
{
var semaphore = Worker.file_locks.GetOrAdd(path, _ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync();
try
{
var cacheItem = await LoadCacheItem(path);
if (cacheItem.data.TryGetValue(oldKey, out var value))
{
cacheItem.data.Remove(oldKey);
cacheItem.data[newKey] = value;
Statistics.renames++;
await SaveCacheItem(path, cacheItem);
Debugger.Write($"[Async] The key \"{oldKey}\" in the file \"{path}\" has been renamed to \"{newKey}\".");
}
}
finally
{
semaphore.Release();
}
}
private static async Task<CacheItem> LoadCacheItem(string path)
{
Statistics.checks++;
var fileInfo = new FileInfo(path);
fileInfo.Refresh();
var currentLastModified = fileInfo.Exists ? fileInfo.LastWriteTimeUtc : DateTime.MinValue;
if (Worker.cache.TryGet(path, out var cachedItem) &&
cachedItem.last_modified.ToString() == currentLastModified.ToString())
{
Statistics.cache_reads++;
Debugger.Write($"[Async] Data for file \"{path}\" loaded from cache.");
return cachedItem;
}
Debugger.Write($"[Async] Loading data from file \"{path}\". ({(cachedItem == null ? "null" : cachedItem)}, {(cachedItem == null ? "null" : cachedItem.last_modified == currentLastModified)}, {(cachedItem == null ? "null" : cachedItem.last_modified)}, {currentLastModified})");
Dictionary<string, JsonElement> data;
Statistics.reads++;
if (File.Exists(path))
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, true);
data = await JsonSerializer.DeserializeAsync<Dictionary<string, JsonElement>>(stream);
}
else
{
data = new Dictionary<string, JsonElement>();
}
var newCacheItem = new CacheItem { data = data, last_modified = currentLastModified };
Worker.cache.AddOrUpdate(path, newCacheItem);
Debugger.Write("[Async] Loaded.");
return newCacheItem;
}
private static async Task SaveCacheItem(string path, CacheItem cacheItem)
{
await using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true);
await JsonSerializer.SerializeAsync(stream, cacheItem.data);
Statistics.writes++;
Statistics.checks++;
var fileInfo = new FileInfo(path);
fileInfo.Refresh();
cacheItem.last_modified = fileInfo.LastWriteTimeUtc;
Worker.cache.AddOrUpdate(path, cacheItem);
Statistics.cache_writes++;
Debugger.Write($"[Async] File \"{path}\" saved.");
}
}
/// <summary>
/// LRU (least recently used) cache class
/// </summary>
public sealed class LruCache<TKey, TValue> where TKey : notnull
{
private readonly ConcurrentDictionary<TKey, LinkedListNode<LruCacheItem>> cache = new();
private readonly LinkedList<LruCacheItem> lru = new();
public int capacity { get; set; }
public int count => cache.Count;
public LruCache(int capacity)
{
this.capacity = capacity;
}
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
var node = cache.GetOrAdd(key, k =>
{
var item = new LruCacheItem(k, valueFactory(k));
return new LinkedListNode<LruCacheItem>(item);
});
lock (lru)
{
if (node.List == lru)
lru.Remove(node);
lru.AddFirst(node);
}
MaintainCapacity();
cache[key].Value.UpdateTime();
return node.Value.Value;
}
public async Task<TValue> GetOrAddAsync(TKey key, Func<TKey, Task<TValue>> valueFactory)
{
if (cache.TryGetValue(key, out var existingNode))
{
cache[key].Value.UpdateTime();
lock (lru)
{
lru.Remove(existingNode);
lru.AddFirst(existingNode);
}
return existingNode.Value.Value;
}
var value = await valueFactory(key);
var newNode = new LinkedListNode<LruCacheItem>(new LruCacheItem(key, value));
lock (lru)
{
if (cache.TryAdd(key, newNode))
{
lru.AddFirst(newNode);
}
else
{
lru.AddFirst(cache[key]);
}
}
MaintainCapacity();
return value;
}
public void AddOrUpdate(TKey key, TValue value)
{
var newNode = new LinkedListNode<LruCacheItem>(new LruCacheItem(key, value));
lock (lru)
{
if (cache.TryGetValue(key, out var oldNode))
{
lru.Remove(oldNode);
}
cache[key] = newNode;
lru.AddFirst(newNode);
MaintainCapacity();
}
}
public bool TryGet(TKey key, out TValue value)
{
if (cache.TryGetValue(key, out var node))
{
cache[key].Value.UpdateTime();
value = node.Value.Value;
lock (lru)
{
lru.Remove(node);
lru.AddFirst(node);
}
return true;
}
value = default;
return false;
}
public void Refresh(TKey key)
{
if (cache.TryGetValue(key, out var node))
{
cache[key].Value.UpdateTime();
lock (lru)
{
lru.Remove(node);
lru.AddFirst(node);
}
}
}
public void Invalidate(TKey key)
{
lock (lru)
{
if (cache.TryRemove(key, out var node))
lru.Remove(node);
}
}
public void Clear()
{
lock (lru)
{
cache.Clear();
lru.Clear();
}
}
public void Clear(TimeSpan OlderThan)
{
DateTime now = DateTime.UtcNow;
lock (lru)
{
foreach (var node in cache)
{
if ((now - node.Value.Value.LastEditTime) > OlderThan)
{
cache.TryRemove(node.Key, out _);
lru.Remove(node.Value);
}
}
}
}
private void MaintainCapacity()
{
while (cache.Count > capacity)
{
lock (lru)
{
if (cache.Count <= capacity) break;
var lastNode = lru.Last;
cache.TryRemove(lastNode.Value.Key, out _);
lru.RemoveLast();
}
}
}
private sealed class LruCacheItem
{
public TKey Key { get; }
public TValue Value { get; }
public DateTime LastEditTime { get; private set; }
public LruCacheItem(TKey key, TValue value)
{
Key = key;
Value = value;
LastEditTime = DateTime.UtcNow;
}
public void UpdateTime()
{
LastEditTime = DateTime.UtcNow;
}
}
}
public class CacheItem
{
public Dictionary<string, JsonElement> data { get; set; } = new();
public DateTime last_modified { get; set; }
}
class Debugger
{
public static void Write(string text)
{
if (Worker.debug) Console.WriteLine($"[DankDB debug] [{(DateTime.UtcNow - Worker.start).TotalMicroseconds}]: {text}");
}
}
}