-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
LastSyncedFileManager.cs
89 lines (75 loc) · 2.63 KB
/
LastSyncedFileManager.cs
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
using System.Globalization;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Sync;
public sealed class LastSyncedFileManager
{
private readonly IHostingEnvironment _hostingEnvironment;
private string? _distCacheFile;
private int _lastId;
private object? _lastIdLock;
private bool _lastIdReady;
public LastSyncedFileManager(IHostingEnvironment hostingEnvironment)
=> _hostingEnvironment = hostingEnvironment;
/// <summary>
/// Returns the last-synced id.
/// </summary>
public int LastSyncedId => LazyInitializer.EnsureInitialized(
ref _lastId,
ref _lastIdReady,
ref _lastIdLock,
() =>
{
// On first load, read from file, else it will return the in-memory _lastId value
var distCacheFilePath = DistCacheFilePath;
if (File.Exists(distCacheFilePath))
{
var content = File.ReadAllText(distCacheFilePath);
if (int.TryParse(content, NumberStyles.Integer, CultureInfo.InvariantCulture, out var last))
{
return last;
}
}
return -1;
});
/// <summary>
/// Gets the dist cache file path (once).
/// </summary>
/// <returns></returns>
public string DistCacheFilePath => LazyInitializer.EnsureInitialized(ref _distCacheFile, () =>
{
var fileName = (Environment.MachineName + _hostingEnvironment.ApplicationId).GenerateHash() + "-lastsynced.txt";
var distCacheFilePath = Path.Combine(_hostingEnvironment.LocalTempPath, "DistCache", fileName);
// ensure the folder exists
var folder = Path.GetDirectoryName(distCacheFilePath);
if (folder == null)
{
throw new InvalidOperationException("The folder could not be determined for the file " + distCacheFilePath);
}
if (Directory.Exists(folder) == false)
{
Directory.CreateDirectory(folder);
}
return distCacheFilePath;
});
/// <summary>
/// Persists the last-synced id to file.
/// </summary>
/// <param name="id">The id.</param>
public void SaveLastSyncedId(int id)
{
if (_lastIdLock is null)
{
return;
}
lock (_lastIdLock)
{
if (!_lastIdReady)
{
throw new InvalidOperationException("Cannot save the last synced id before it is read");
}
File.WriteAllText(DistCacheFilePath, id.ToString(CultureInfo.InvariantCulture));
_lastId = id;
}
}
}