-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathFileWatcherService.cs
273 lines (233 loc) · 10.4 KB
/
FileWatcherService.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
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
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Jering.Javascript.NodeJS
{
/// <summary>
/// Default implementation of <see cref="IFileWatcherService"/>.
/// </summary>
public class FileWatcherService : IFileWatcherService, IDisposable
{
// Logging
private readonly bool _debugLoggingEnabled;
private readonly bool _infoLoggingEnabled;
private readonly ILogger<FileWatcherService> _logger;
// Listeners
private event Action? _fileChanged;
// Options
private readonly NodeJSProcessOptions _nodeJSProcessOptions;
private readonly OutOfProcessNodeJSServiceOptions _outOfProcessNodeJSServiceOptions;
// Watcher
private volatile FileSystemWatcher? _fileSystemWatcher = null; // Volatile since used in double checked lock
// Concurrency
private readonly SemaphoreSlim _createFileSystemWatcherLock = new(1, 1);
private CancellationTokenSource? _cancellationTokenSource;
private readonly object _cancellationTokenSourceLock = new();
// Filters
private ReadOnlyCollection<Regex>? _filters;
// Disposal
private bool _disposed;
/// <summary>
/// Creates a <see cref="FileWatcherService"/>.
/// </summary>
/// <param name="nodeJSProcessOptionsAccessor"></param>
/// <param name="outOfProcessNodeJSServiceOptions"></param>
/// <param name="logger"></param>
public FileWatcherService(IOptions<NodeJSProcessOptions> nodeJSProcessOptionsAccessor,
IOptions<OutOfProcessNodeJSServiceOptions> outOfProcessNodeJSServiceOptions,
ILogger<FileWatcherService> logger)
{
_nodeJSProcessOptions = nodeJSProcessOptionsAccessor.Value;
_outOfProcessNodeJSServiceOptions = outOfProcessNodeJSServiceOptions.Value;
_debugLoggingEnabled = logger.IsEnabled(LogLevel.Debug);
_infoLoggingEnabled = logger.IsEnabled(LogLevel.Information);
_logger = logger;
}
/// <summary>
/// Add a listener for file changes.
/// </summary>
/// <param name="fileChanged">The listener.</param>
public async Task AddFileChangedListenerAsync(Action fileChanged)
{
// Double checked lock so only one thread creates the file watcher
if (_fileSystemWatcher == null)
{
await _createFileSystemWatcherLock.WaitAsync().ConfigureAwait(false);
_fileSystemWatcher ??= CreateFileSystemWatcher();
_createFileSystemWatcherLock.Release();
}
// Add listener
_fileChanged += fileChanged;
}
internal virtual FileSystemWatcher CreateFileSystemWatcher()
{
// Filters for checking whether files are watched
_filters = ResolveFilters(_outOfProcessNodeJSServiceOptions.WatchFileNamePatterns);
// Create FileSystemWatcher instance
string directoryPath = ResolveDirectoryPath(_outOfProcessNodeJSServiceOptions.WatchPath, _nodeJSProcessOptions.ProjectPath);
var fileSystemWatcher = new FileSystemWatcher(directoryPath)
{
IncludeSubdirectories = _outOfProcessNodeJSServiceOptions.WatchSubdirectories,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName
};
// Register handlers for FileSystemWatcher events
fileSystemWatcher.Changed += InternalFileChangedHandler;
fileSystemWatcher.Created += InternalFileChangedHandler;
fileSystemWatcher.Deleted += InternalFileChangedHandler;
fileSystemWatcher.Renamed += InternalFileRenamedHandler;
fileSystemWatcher.EnableRaisingEvents = true;
return fileSystemWatcher;
}
internal virtual void InternalFileChangedHandler(object _, FileSystemEventArgs fileSystemEventArgs)
{
if (IsPathWatched(fileSystemEventArgs.FullPath))
{
#pragma warning disable CS4014 // No need to await
InternalFileHandlerCoreAsync(fileSystemEventArgs.FullPath);
#pragma warning restore CS4014
}
}
internal virtual void InternalFileRenamedHandler(object _, RenamedEventArgs renamedEventArgs)
{
// If both new and old paths watched, pass new path
string path;
if (IsPathWatched(renamedEventArgs.FullPath))
{
path = renamedEventArgs.FullPath;
}
else if (IsPathWatched(renamedEventArgs.OldFullPath))
{
path = renamedEventArgs.OldFullPath;
}
else
{
return; // Not watched
}
#pragma warning disable CS4014 // No need to await
InternalFileHandlerCoreAsync(path);
#pragma warning restore CS4014
}
internal virtual async Task InternalFileHandlerCoreAsync(string path)
{
if (_debugLoggingEnabled)
{
_logger.LogDebug(string.Format(Strings.LogDebug_InternalFileChangedHandlerCalled, path));
}
if (_fileChanged == null)
{
return; // No listeners
}
// Debounce by cancelling until an invocation occurs with no subsequent invocations for 1ms
CancellationTokenSource cancellationTokenSource = CancelExistingAndGetNewCancellationTokenSource();
try
{
CancellationToken cancellationToken = cancellationTokenSource.Token;
await Task.Delay(1).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
{
if (_debugLoggingEnabled)
{
_logger.LogDebug(string.Format(Strings.LogDebug_InternalFileChangedHandlerCallDebounced, path));
}
return;
}
// Invoke handlers
if (_infoLoggingEnabled)
{
_logger.LogInformation(string.Format(Strings.LogInformation_InvokingRegisteredFileChangedHandlers, path));
}
_fileChanged();
}
finally
{
DisposeAndRemoveCancellationTokenSource(cancellationTokenSource);
}
}
internal virtual CancellationTokenSource CancelExistingAndGetNewCancellationTokenSource()
{
// Lock to avoid synchronization issues with DisposeCancellationTokenSourceAndClear
lock (_cancellationTokenSourceLock)
{
_cancellationTokenSource?.Cancel();
return _cancellationTokenSource = new CancellationTokenSource();
}
}
internal virtual void DisposeAndRemoveCancellationTokenSource(CancellationTokenSource cancellationTokenSource)
{
// Lock to avoid synchronization issues with CancelExistingAndGetNewCancellationTokenSource
lock (_cancellationTokenSourceLock)
{
cancellationTokenSource.Dispose();
if (cancellationTokenSource == _cancellationTokenSource)
{
_cancellationTokenSource = null;
}
}
}
internal virtual bool IsPathWatched(string path)
{
if (_filters == null || string.IsNullOrWhiteSpace(path))
{
return false;
}
// TODO netstandard2.1+ use span returning method - https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netcore-3.1#System_IO_Path_GetFileName_System_ReadOnlySpan_System_Char__
string fileName = Path.GetFileName(path);
// TODO netstandard2.1+ use FileSystemName.MatchesSimpleExpression - https://docs.microsoft.com/en-us/dotnet/api/system.io.enumeration.filesystemname.matchessimpleexpression?view=netstandard-2.1
return _filters.Any(regex => regex.IsMatch(fileName));
}
internal virtual string ResolveDirectoryPath(string? directoryPath, string projectPath)
{
return string.IsNullOrWhiteSpace(directoryPath) ? projectPath : directoryPath!;
}
internal virtual ReadOnlyCollection<Regex> ResolveFilters(IEnumerable<string> fileNamePatterns)
{
int count = fileNamePatterns.Count();
var regexes = new Regex[count];
for (int i = 0; i < count; i++)
{
string fileNamePattern = fileNamePatterns.ElementAt(i);
// Note that CreateRegex may get called multiple times for the same fileNamePattern - https://github.com/dotnet/runtime/issues/24293.
// This is fine for now since it doesn't do much.
regexes[i] = CreateRegex(fileNamePattern);
}
return new ReadOnlyCollection<Regex>(regexes);
}
internal virtual Regex CreateRegex(string fileNamePattern)
{
string regexPattern = "^" + Regex.Escape(fileNamePattern).Replace("\\*", ".*").Replace("\\?", ".?") + "$";
return new Regex(regexPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
/// <summary>
/// Disposes the <see cref="FileSystemWatcher"/> instance.
/// </summary>
/// <param name="disposing">True if the object is disposing or false if it is finalizing.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_fileSystemWatcher?.Dispose();
_createFileSystemWatcherLock?.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
_disposed = true;
}
/// <summary>
/// Disposes the <see cref="FileSystemWatcher"/> instance.
/// </summary>
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}