-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScanCacheService.cs
More file actions
333 lines (282 loc) · 11.2 KB
/
Copy pathScanCacheService.cs
File metadata and controls
333 lines (282 loc) · 11.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace c2flux
{
public sealed class ScanCacheService
{
private const int CacheVersion = 2;
private const int RetentionDays = 30;
private const int CachedTreeDepth = 2;
private const int MaxCachedChildrenPerDirectory = 300;
private readonly string _cacheFilePath;
private readonly Dictionary<string, ScanCacheFileEntry> _fileEntries;
private readonly HashSet<string> _seenFilePaths;
private ScanCacheService(string cacheFilePath, Dictionary<string, ScanCacheFileEntry> fileEntries)
{
_cacheFilePath = cacheFilePath;
_fileEntries = fileEntries;
_seenFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
public static ScanCacheService Load(string rootPath)
{
string cacheFilePath = GetCacheFilePath(rootPath);
if (!File.Exists(cacheFilePath))
{
return new ScanCacheService(cacheFilePath, new Dictionary<string, ScanCacheFileEntry>(StringComparer.OrdinalIgnoreCase));
}
try
{
string json = File.ReadAllText(cacheFilePath);
ScanCacheDatabase database = JsonSerializer.Deserialize<ScanCacheDatabase>(json);
if (database == null || database.Version != CacheVersion || database.Files == null)
{
return new ScanCacheService(cacheFilePath, new Dictionary<string, ScanCacheFileEntry>(StringComparer.OrdinalIgnoreCase));
}
Dictionary<string, ScanCacheFileEntry> fileEntries = new Dictionary<string, ScanCacheFileEntry>(StringComparer.OrdinalIgnoreCase);
foreach (ScanCacheFileEntry fileEntry in database.Files)
{
if (!string.IsNullOrWhiteSpace(fileEntry.FullPath))
{
fileEntries[fileEntry.FullPath] = fileEntry;
}
}
return new ScanCacheService(cacheFilePath, fileEntries);
}
catch (Exception exception)
{
try
{
AppAlertLog.AddWarning(
"Scan cache",
"The scan cache could not be loaded.",
"Path: " + cacheFilePath +
Environment.NewLine +
exception);
}
catch (Exception loggingException)
{
try
{
System.Diagnostics.Trace.TraceError(
"AppAlertLog failed while logging an exception: " +
loggingException);
}
catch
{
}
}
return new ScanCacheService(cacheFilePath, new Dictionary<string, ScanCacheFileEntry>(StringComparer.OrdinalIgnoreCase));
}
}
public static FileSystemEntry TryLoadCachedTree(string rootPath)
{
string cacheFilePath = GetCacheFilePath(rootPath);
if (!File.Exists(cacheFilePath))
{
return null;
}
try
{
string json = File.ReadAllText(cacheFilePath);
ScanCacheDatabase database = JsonSerializer.Deserialize<ScanCacheDatabase>(json);
if (database == null || database.Version != CacheVersion || database.RootEntry == null)
{
return null;
}
return ConvertToFileSystemEntry(database.RootEntry);
}
catch (Exception exception)
{
try
{
AppAlertLog.AddWarning(
"Scan cache",
"The cached scan tree could not be loaded.",
"Path: " + cacheFilePath +
Environment.NewLine +
exception);
}
catch (Exception loggingException)
{
try
{
System.Diagnostics.Trace.TraceError(
"AppAlertLog failed while logging an exception: " +
loggingException);
}
catch
{
}
}
return null;
}
}
public long GetLengthAndUpdate(string fullPath, long length, long lastWriteTimeUtcTicks, int attributes)
{
if (string.IsNullOrWhiteSpace(fullPath))
{
return 0;
}
DateTime lastSeenUtc = DateTime.UtcNow;
if (_fileEntries.TryGetValue(fullPath, out ScanCacheFileEntry existingEntry) &&
existingEntry.SizeBytes == length &&
existingEntry.LastWriteTimeUtcTicks == lastWriteTimeUtcTicks &&
existingEntry.Attributes == attributes)
{
existingEntry.LastSeenUtcTicks = lastSeenUtc.Ticks;
_seenFilePaths.Add(fullPath);
return existingEntry.SizeBytes;
}
_fileEntries[fullPath] = new ScanCacheFileEntry
{
FullPath = fullPath,
SizeBytes = length,
LastWriteTimeUtcTicks = lastWriteTimeUtcTicks,
Attributes = attributes,
LastSeenUtcTicks = lastSeenUtc.Ticks
};
_seenFilePaths.Add(fullPath);
return length;
}
public void Save(FileSystemEntry rootEntry)
{
DateTime retentionLimitUtc = DateTime.UtcNow.AddDays(-RetentionDays);
List<ScanCacheFileEntry> fileEntries = new List<ScanCacheFileEntry>();
foreach (ScanCacheFileEntry fileEntry in _fileEntries.Values)
{
if (!_seenFilePaths.Contains(fileEntry.FullPath))
continue;
if (fileEntry.LastSeenUtcTicks < retentionLimitUtc.Ticks)
continue;
fileEntries.Add(fileEntry);
}
ScanCacheDatabase database = new ScanCacheDatabase
{
Version = CacheVersion,
CreatedUtcTicks = DateTime.UtcNow.Ticks,
Files = fileEntries,
RootEntry = ConvertToCacheTreeEntry(rootEntry, CachedTreeDepth)
};
Directory.CreateDirectory(Path.GetDirectoryName(_cacheFilePath));
JsonSerializerOptions options = new JsonSerializerOptions
{
WriteIndented = false
};
string temporaryFilePath = _cacheFilePath + ".tmp";
string json = JsonSerializer.Serialize(database, options);
File.WriteAllText(temporaryFilePath, json, Encoding.UTF8);
if (File.Exists(_cacheFilePath))
{
File.Replace(
temporaryFilePath,
_cacheFilePath,
null);
}
else
{
File.Move(
temporaryFilePath,
_cacheFilePath);
}
}
private static string GetCacheFilePath(string rootPath)
{
string cacheDirectoryPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"WTF",
"ScanCache");
Directory.CreateDirectory(cacheDirectoryPath);
return Path.Combine(cacheDirectoryPath, CreateCacheFileName(rootPath));
}
private static string CreateCacheFileName(string rootPath)
{
string normalizedRootPath = string.IsNullOrWhiteSpace(rootPath)
? "unknown"
: rootPath.Trim().ToUpperInvariant();
byte[] hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(normalizedRootPath));
return Convert.ToHexString(hashBytes) + ".json";
}
private static ScanCacheTreeEntry ConvertToCacheTreeEntry(FileSystemEntry entry, int remainingDepth)
{
if (entry == null)
{
return null;
}
ScanCacheTreeEntry cacheEntry = new ScanCacheTreeEntry
{
Name = entry.Name,
FullPath = entry.FullPath,
SizeBytes = entry.SizeBytes,
IsDirectory = entry.IsDirectory,
Children = new List<ScanCacheTreeEntry>()
};
if (remainingDepth <= 0)
{
return cacheEntry;
}
foreach (FileSystemEntry child in entry.Children
.Where(child => child.IsDirectory)
.OrderByDescending(child => child.SizeBytes)
.ThenBy(child => child.Name)
.Take(MaxCachedChildrenPerDirectory))
{
cacheEntry.Children.Add(ConvertToCacheTreeEntry(child, remainingDepth - 1));
}
return cacheEntry;
}
private static FileSystemEntry ConvertToFileSystemEntry(ScanCacheTreeEntry cacheEntry)
{
if (cacheEntry == null)
{
return null;
}
FileSystemEntry entry = new FileSystemEntry
{
Name = cacheEntry.Name,
FullPath = cacheEntry.FullPath,
SizeBytes = cacheEntry.SizeBytes,
IsDirectory = cacheEntry.IsDirectory
};
if (cacheEntry.Children != null)
{
foreach (ScanCacheTreeEntry child in cacheEntry.Children)
{
FileSystemEntry childEntry = ConvertToFileSystemEntry(child);
if (childEntry != null)
{
entry.Children.Add(childEntry);
}
}
}
return entry;
}
private sealed class ScanCacheDatabase
{
public int Version { get; set; }
public long CreatedUtcTicks { get; set; }
public List<ScanCacheFileEntry> Files { get; set; }
public ScanCacheTreeEntry RootEntry { get; set; }
}
private sealed class ScanCacheFileEntry
{
public string FullPath { get; set; }
public long SizeBytes { get; set; }
public long LastWriteTimeUtcTicks { get; set; }
public int Attributes { get; set; }
public long LastSeenUtcTicks { get; set; }
}
private sealed class ScanCacheTreeEntry
{
public string Name { get; set; }
public string FullPath { get; set; }
public long SizeBytes { get; set; }
public bool IsDirectory { get; set; }
public List<ScanCacheTreeEntry> Children { get; set; }
}
}
}