-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathXmlDataProviderDocumentWriter.cs
244 lines (200 loc) · 8.99 KB
/
XmlDataProviderDocumentWriter.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
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Composite.Core.Extensions;
using Composite.Core;
using Composite.Core.IO;
using System.IO;
using System.Threading;
using System.Xml;
using Composite.C1Console.Events;
namespace Composite.Plugins.Data.DataProviders.XmlDataProvider.Foundation
{
internal static class XmlDataProviderDocumentWriter
{
private static readonly ConcurrentQueue<FileRecord> _dirtyRecords = new ConcurrentQueue<FileRecord>();
private static readonly Dictionary<string, Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>>> _fileOrderers = new Dictionary<string, Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>>>();
private static readonly object _flushEnterLock = new object();
private static readonly object _flushExecuteLock = new object();
private static DateTime _activeFlushActivityStart = DateTime.MinValue;
private static readonly System.Timers.Timer _autoCommitTimer;
private static readonly TimeSpan _updateFrequency = TimeSpan.FromMilliseconds(1000);
private static readonly TimeSpan _fileIoDelay = TimeSpan.FromMilliseconds(10); // small pause between io operations to reduce asp.net appPool recycles due to FileWatcher buffer fills - edge case, but highly annoying
private const int NumberOfRetries = 30;
private static readonly string LogTitle = nameof(XmlDataProvider);
private static bool _forceImmediateWrite;
static XmlDataProviderDocumentWriter()
{
_autoCommitTimer = new System.Timers.Timer(_updateFrequency.TotalMilliseconds)
{
AutoReset = true
};
_autoCommitTimer.Elapsed += OnAutoCommitTimer;
_autoCommitTimer.Start();
GlobalEventSystemFacade.SubscribeToShutDownEvent(OnShutDownEvent);
}
private static void OnShutDownEvent(ShutDownEventArgs args)
{
_forceImmediateWrite = true;
Flush();
}
internal static void Save(FileRecord fileRecord)
{
_dirtyRecords.Enqueue(fileRecord);
if (_forceImmediateWrite)
{
Flush();
}
}
internal static void RegisterFileOrderer(string filename, Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>> orderer)
{
string key = filename.ToLowerInvariant();
if (_fileOrderers.ContainsKey(key))
{
_fileOrderers.Remove(key);
}
_fileOrderers.Add(key, orderer);
}
private static bool TryGetFileOrderer(out Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>> orderer, string filename)
{
string key = filename.ToLowerInvariant();
if (_fileOrderers.ContainsKey(key))
{
orderer = _fileOrderers[key];
return true;
}
orderer = null;
return false;
}
internal static void Flush()
{
lock (_flushEnterLock)
{
if (!_forceImmediateWrite && (DateTime.Now - _activeFlushActivityStart).TotalSeconds < 30)
{
return;
}
_activeFlushActivityStart = DateTime.Now;
}
FileRecord dirtyFileRecord;
List<FileRecord> fileRecords = new List<FileRecord>();
lock (_flushExecuteLock)
{
while (_dirtyRecords.TryDequeue(out dirtyFileRecord))
{
if (!fileRecords.Any(f => f.FilePath == dirtyFileRecord.FilePath))
{
fileRecords.Add(dirtyFileRecord);
}
}
foreach (var fileRecord in fileRecords)
{
try
{
DoSave(fileRecord);
}
catch (Exception ex)
{
if (ex is DirectoryNotFoundException)
{
Log.LogWarning(LogTitle, $"Failed to save file '{fileRecord.FilePath}' as the underlying directory does not exist.");
continue;
}
Log.LogCritical(LogTitle, $"Failed to save data to the file: '{fileRecord.FilePath}'");
Log.LogError(LogTitle, ex);
_dirtyRecords.Enqueue(fileRecord);
}
}
}
_activeFlushActivityStart = DateTime.MinValue;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotUseFileClass:DoNotUseFileClass", Justification = "This is what we want, to handle broken saves")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Composite.IO", "Composite.DoNotCallXmlWriterCreateWithPath:DoNotCallXmlWriterCreateWithPath", Justification = "This is what we want, to handle broken saves")]
private static void DoSave(FileRecord fileRecord)
{
var root = new XElement(GetRootElementName(fileRecord.ElementName));
var xDocument = new XDocument(root);
var recordSet = fileRecord.RecordSet;
var elements = new List<XElement>(recordSet.Index.GetValues());
Func<IEnumerable<XElement>, IOrderedEnumerable<XElement>> orderer;
if (TryGetFileOrderer(out orderer, fileRecord.FilePath))
{
var orderedElements = orderer(elements);
orderedElements.ForEach(root.Add);
}
else
{
elements.ForEach(root.Add);
}
Exception thrownException = null;
// Writing the file in the "catch" block in order to prevent chance of corrupting the file by experiencing ThreadAbortException.
try
{
}
finally
{
try
{
// Saving to temp file and file move to prevent broken saves
var xmlWriterSettings = new XmlWriterSettings
{
CheckCharacters = false,
Indent = true
};
using (XmlWriter xmlWriter = XmlWriter.Create(fileRecord.TempFilePath, xmlWriterSettings))
{
xDocument.Save(xmlWriter);
}
Thread.Sleep(_fileIoDelay);
bool failed = true;
Exception lastException = null;
for (int i = 0; i < NumberOfRetries; i++)
{
DateTime lastSuccessfulFileChange = fileRecord.FileModificationDate;
try
{
fileRecord.FileModificationDate = DateTime.MinValue;
File.Copy(fileRecord.TempFilePath, fileRecord.FilePath, true);
failed = false;
break;
}
catch (Exception ex)
{
fileRecord.FileModificationDate = lastSuccessfulFileChange;
lastException = ex;
Thread.Sleep(10 * (i + 1));
}
}
if (!failed)
{
Thread.Sleep(_fileIoDelay);
File.Delete(fileRecord.TempFilePath);
}
else
{
Log.LogCritical(LogTitle, "Failed deleting the file: " + fileRecord.FilePath);
if (lastException != null) throw lastException;
throw new InvalidOperationException("Failed to delete a file, this code shouldn't be reachable");
}
fileRecord.FileModificationDate = C1File.GetLastWriteTime(fileRecord.FilePath);
}
catch (Exception exception)
{
thrownException = exception;
}
}
// ThreadAbortException should have a higher priority, and therefore we're doing rethrow in a separate block
if (thrownException != null) throw thrownException;
}
internal static string GetRootElementName(string elementName)
{
return elementName + "Elements";
}
private static void OnAutoCommitTimer(object sender, System.Timers.ElapsedEventArgs e)
{
Flush();
}
}
}