Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
FileSystemWatcher.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4
5#include "../Common/CompilerMacrosExport.h"
6#ifndef SC_EXPORT_LIBRARY_FILE_SYSTEM_WATCHER
7#define SC_EXPORT_LIBRARY_FILE_SYSTEM_WATCHER 0
8#endif
9#define SC_FILE_SYSTEM_WATCHER_EXPORT SC_COMPILER_LIBRARY_EXPORT(SC_EXPORT_LIBRARY_FILE_SYSTEM_WATCHER)
10
11#include "../Common/Assert.h"
12#include "../Common/CompilerOffsetOf.h"
13#include "../Common/Function.h"
14#include "../Common/IGrowableBufferStringPath.h"
15#include "../Common/OpaqueObject.h"
16#include "../Common/PlatformMacrosType.h"
17#include "../Common/Result.h"
18#include "FileSystemWatcherError.h"
19
20namespace SC
21{
22SC_DECLARE_ASSERT_PROVIDER(FileSystemWatcherAssert, SC_FILE_SYSTEM_WATCHER_EXPORT);
23
24#define SC_FILE_SYSTEM_WATCHER_ASSERT_RELEASE(e) SC_ASSERT_PROVIDER_RELEASE(SC::FileSystemWatcherAssert, e)
25#define SC_FILE_SYSTEM_WATCHER_ASSERT_DEBUG(e) SC_ASSERT_PROVIDER_DEBUG(SC::FileSystemWatcherAssert, e)
26#define SC_FILE_SYSTEM_WATCHER_TRUST_RESULT(expression) SC_FILE_SYSTEM_WATCHER_ASSERT_RELEASE(expression)
27
30
33
59
62{
63 private:
64 struct Internal;
65
66 struct InternalDefinition
67 {
68 static constexpr int Windows = 3 * sizeof(void*);
69 // The Apple backend keeps a Notification and structured result inline during event-loop handoff.
70 static constexpr int Apple = 61 * sizeof(void*);
71 static constexpr int Linux = 256;
72 static constexpr int Default = Linux;
73
74 static constexpr size_t Alignment = alignof(void*);
75
76 using Object = Internal;
77 };
78
79 public:
80 // Must be public to avoid GCC complaining
81 using InternalOpaque = OpaqueObject<InternalDefinition>;
82
83 private:
84 InternalOpaque internal;
85
86 //...
88 struct ThreadRunnerInternal;
89 struct ThreadRunnerDefinition
90 {
91 static constexpr int MaxWatchablePaths = 1024;
92
93 static constexpr int Windows = (2 * MaxWatchablePaths + 2) * sizeof(void*) + sizeof(uint64_t);
94 static constexpr int Apple = sizeof(void*);
95 static constexpr int Linux = sizeof(void*) * 6;
96 static constexpr int Default = Linux;
97
98 static constexpr size_t Alignment = alignof(void*);
99
100 using Object = ThreadRunnerInternal;
101 };
102
103 struct FolderWatcherInternal;
104 struct FolderWatcherSizes
105 {
106 static constexpr int MaxNumberOfSubdirs = 128; // Max number of subfolders tracked in a watcher
107 static constexpr int MaxChangesBufferSize = 16 * 1024;
108
109 static constexpr int Windows = MaxChangesBufferSize + sizeof(void*) + sizeof(void*);
110 static constexpr int Apple = sizeof(StringPath) + sizeof(void*);
111 static constexpr int Linux = 24 * MaxNumberOfSubdirs + 4096 + 40;
112 static constexpr int Default = Linux;
113
114 static constexpr size_t Alignment = alignof(void*);
115
116 using Object = FolderWatcherInternal;
117 };
118
119 public:
122 enum class Operation
123 {
124 Modified,
126 };
127
130 {
131 Change,
134 };
135
138 {
139 StringSpan basePath;
140 StringSpan relativePath;
141
144
146
150 ResultFileSystemWatcher getFullPath(StringPath& path) const;
151
152 private:
153 friend struct Internal;
154#if SC_PLATFORM_APPLE
155 StringSpan fullPath;
156#endif
157 };
158
163 {
168 FolderWatcher(Span<char> subFolderRelativePathsBuffer = {});
169
170 Function<void(const Notification&)> notifyCallback;
171
175
177 void setDebugName(const char* debugName);
178
179 private:
180 friend struct FileSystemWatcher;
181 template <typename T_AsyncEventLoop>
182 friend struct FileSystemWatcherAsyncT;
183#if SC_PLATFORM_WINDOWS
184#if SC_ASYNC_ENABLE_LOG
185 AlignedStorage<160> asyncStorage;
186#else
187 AlignedStorage<152> asyncStorage;
188#endif
189#endif
190 OpaqueObject<FolderWatcherSizes> internal;
191
192 FileSystemWatcher* parent = nullptr;
193 FolderWatcher* next = nullptr;
194 FolderWatcher* prev = nullptr;
195
196 StringPath path;
197
198#if SC_PLATFORM_LINUX
199 Span<char> subFolderRelativePathsBuffer;
200#endif
201 };
202
205 {
206 virtual ~EventLoopRunner() {}
207
208 protected:
209#if SC_PLATFORM_APPLE
210 virtual Result appleStartWakeUp() = 0;
211 virtual Result appleStopWakeUp() = 0;
212 virtual void appleSignalEventObject() = 0;
213 virtual void appleResetHandoff() = 0;
214 virtual Result appleWakeUpAndWait() = 0;
215
216#elif SC_PLATFORM_LINUX
217 // On failure, no readiness request may remain active or retain notifyFd.
218 virtual Result posixStartSharedFileReadiness() = 0;
219 virtual Result posixStopSharedFileReadiness() = 0;
220
221 int notifyFd = -1;
222
223#else
224 virtual Result windowsStartFolderExternalCompletion(FolderWatcher& watcher, void* handle) = 0;
225 virtual Result windowsRequestStopFolderExternalCompletion(FolderWatcher& watcher) = 0;
226 virtual Result windowsWaitFolderExternalCompletionStopped(FolderWatcher& watcher) = 0;
227 virtual Result windowsMarkFolderExternalCompletionPending(FolderWatcher& watcher) = 0;
228 virtual Result windowsClearFolderExternalCompletionPending(FolderWatcher& watcher) = 0;
229 virtual void* windowsGetOverlapped(FolderWatcher& watcher) = 0;
230#endif
231 friend struct Internal;
232 FileSystemWatcher* fileSystemWatcher = nullptr;
233
234 void internalInit(FileSystemWatcher& fsWatcher, int handle);
235 };
236
238 using ThreadRunner = OpaqueObject<ThreadRunnerDefinition>;
239
244
249
255
262 ResultFileSystemWatcher watch(FolderWatcher& watcher, StringSpan path);
263
264 bool asyncNotify(FolderWatcher* watcher, size_t bytesTransferred = 0);
265#if SC_PLATFORM_LINUX
266 void asyncNotifyFailure(Result failure);
267#elif SC_PLATFORM_WINDOWS
268 void asyncNotifyFailure(FolderWatcher& watcher, Result failure);
269#endif
270
271 private:
272 friend decltype(internal);
273 friend decltype(FolderWatcher::internal);
274 template <typename T_AsyncEventLoop>
275 friend struct FileSystemWatcherAsyncT;
276 // Trimmed duplicate of IntrusiveDoubleLinkedList<T>
277 struct WatcherLinkedList
278 {
279 FolderWatcher* back = nullptr; // has no next
280 FolderWatcher* front = nullptr; // has no prev
281
282 void queueBack(FolderWatcher& watcher);
283 void remove(FolderWatcher& watcher);
284 };
285 WatcherLinkedList watchers;
286};
287
294template <typename T_AsyncEventLoop>
296{
298
299 using T_AsyncLoopWakeUp = typename T_AsyncEventLoop::LoopWakeUp;
300 using T_AsyncFileReadiness = typename T_AsyncEventLoop::FileReadiness;
301 using T_AsyncExternalCompletion = typename T_AsyncEventLoop::ExternalCompletion;
302 using T_EventObject = typename T_AsyncEventLoop::EventObjectType;
303 using T_AsyncResult = typename T_AsyncEventLoop::ResultType;
304
305 void init(T_AsyncEventLoop& loop) { eventLoop = &loop; }
306
307 protected:
308 T_AsyncEventLoop* eventLoop = nullptr;
309
310#if SC_PLATFORM_APPLE
311 virtual Result appleStartWakeUp() override
312 {
313 if (eventLoop == nullptr or fileSystemWatcher == nullptr)
314 return Result::Error(FileSystemWatcherResultCategory, FileSystemWatcherError::NotInitialized);
315 T_AsyncLoopWakeUp& wakeUp = asyncWakeUp;
316 wakeUp.callback.template bind<Self, &Self::onEventLoopNotification>(*this);
317 return wakeUp.start(*eventLoop);
318 }
319
320 virtual void appleSignalEventObject() override { eventObject.signal(); }
321
322 virtual void appleResetHandoff() override
323 {
324 notificationGeneration++;
325 // The producer is quiescent. Consume any unused release signal.
326 eventObject.signal();
327 eventObject.wait();
328 }
329
330 virtual Result appleStopWakeUp() override
331 {
332 if (not asyncWakeUp.isFree())
333 {
334 SC_TRY(asyncWakeUp.stop(*eventLoop));
335 while (not asyncWakeUp.isFree())
336 {
337 SC_TRY(eventLoop->runNoWait());
338 }
339 }
340 appleResetHandoff();
341 return Result(true);
342 }
343
344 virtual Result appleWakeUpAndWait() override
345 {
346 const Result res = asyncWakeUp.wakeUp(*eventLoop);
347 eventObject.wait();
348 return res;
349 }
350
351 void onEventLoopNotification(typename T_AsyncLoopWakeUp::Result& result)
352 {
353 const size_t generation = notificationGeneration;
354 result.reactivateRequest(true);
355 const bool delivered = fileSystemWatcher->asyncNotify(nullptr);
356 if (delivered and generation == notificationGeneration)
357 {
358 eventObject.signal();
359 }
360 }
361
362 size_t notificationGeneration = 0;
363
364 T_AsyncLoopWakeUp asyncWakeUp = {};
365 T_EventObject eventObject = {};
366#elif SC_PLATFORM_LINUX
367 virtual Result posixStartSharedFileReadiness() override
368 {
369 if (eventLoop == nullptr or fileSystemWatcher == nullptr)
370 return Result::Error(FileSystemWatcherResultCategory, FileSystemWatcherError::NotInitialized);
371 SC_TRY(eventLoop->associateExternallyCreatedFileDescriptorHandle(notifyFd));
372 asyncPoll.callback.template bind<Self, &Self::onEventLoopNotification>(*this);
373 return asyncPoll.start(*eventLoop, notifyFd);
374 }
375
376 virtual Result posixStopSharedFileReadiness() override
377 {
378 if (posixDeliveryAlive != nullptr)
379 {
380 *posixDeliveryAlive = false;
381 posixDeliveryAlive = nullptr;
382 }
383 if (not asyncPoll.isFree())
384 {
385 SC_TRY(asyncPoll.stop(*eventLoop));
386 while (not asyncPoll.isFree())
387 {
388 SC_TRY(eventLoop->runNoWait());
389 }
390 }
391 return Result(true);
392 }
393
394 void onEventLoopNotification(typename T_AsyncFileReadiness::Result& result)
395 {
396 bool deliveryAlive = true;
397 posixDeliveryAlive = &deliveryAlive;
398
399 bool rearm = false;
400 if (result.isValid())
401 {
402 rearm = fileSystemWatcher->asyncNotify(nullptr);
403 }
404 else
405 {
406 fileSystemWatcher->asyncNotifyFailure(result.isValid());
407 }
408 if (deliveryAlive)
409 {
410 posixDeliveryAlive = nullptr;
411 if (rearm)
412 result.reactivateRequest(true);
413 }
414 }
415
416 bool* posixDeliveryAlive = nullptr;
417
418 T_AsyncFileReadiness asyncPoll = {};
419#else
421 virtual Result windowsStartFolderExternalCompletion(FolderWatcher& watcher, void* handle) override
422 {
423 if (eventLoop == nullptr or fileSystemWatcher == nullptr)
424 return Result::Error(FileSystemWatcherResultCategory, FileSystemWatcherError::NotInitialized);
425 T_AsyncExternalCompletion& completion =
426 watcher.asyncStorage.template reinterpret_as<T_AsyncExternalCompletion>();
427 placementNew(completion);
428 completion.setDebugName("FileSystemWatcherAsync Completion");
429 completion.callback.template bind<Self, &Self::onEventLoopNotification>(*this);
430 const Result started = completion.start(*eventLoop, handle);
431 if (not started)
432 completion.~T_AsyncExternalCompletion();
433 return started;
434 }
435
436 virtual Result windowsRequestStopFolderExternalCompletion(FolderWatcher& watcher) override
437 {
438 T_AsyncExternalCompletion& completion =
439 watcher.asyncStorage.template reinterpret_as<T_AsyncExternalCompletion>();
440
441 if (completion.isFree() and not completion.hasSubmissionPending())
442 return Result(true);
443 return completion.stop(*eventLoop);
444 }
445
446 virtual Result windowsWaitFolderExternalCompletionStopped(FolderWatcher& watcher) override
447 {
448 T_AsyncExternalCompletion& completion =
449 watcher.asyncStorage.template reinterpret_as<T_AsyncExternalCompletion>();
450 while (not completion.isFree())
451 {
452 SC_TRY(eventLoop->runOnce());
453 }
454 completion.~T_AsyncExternalCompletion();
455 return Result(true);
456 }
457
458 virtual Result windowsMarkFolderExternalCompletionPending(FolderWatcher& watcher) override
459 {
460 T_AsyncExternalCompletion& completion =
461 watcher.asyncStorage.template reinterpret_as<T_AsyncExternalCompletion>();
462 return completion.markSubmissionPending();
463 }
464
465 virtual Result windowsClearFolderExternalCompletionPending(FolderWatcher& watcher) override
466 {
467 T_AsyncExternalCompletion& completion =
468 watcher.asyncStorage.template reinterpret_as<T_AsyncExternalCompletion>();
469 return completion.clearSubmissionPending();
470 }
471
472 virtual void* windowsGetOverlapped(FolderWatcher& watcher) override
473 {
474 T_AsyncExternalCompletion& completion =
475 watcher.asyncStorage.template reinterpret_as<T_AsyncExternalCompletion>();
476 return completion.getWindowsOverlapped();
477 }
478
479 void onEventLoopNotification(typename T_AsyncExternalCompletion::Result& result)
480 {
481 SC_COMPILER_WARNING_PUSH_OFFSETOF;
482 auto& storage = reinterpret_cast<decltype(FolderWatcher::asyncStorage)&>(result.getAsync());
483 FolderWatcher& watcher = SC_COMPILER_FIELD_OFFSET(FolderWatcher, asyncStorage, storage);
484 if (result.isValid())
485 {
486 if (fileSystemWatcher->asyncNotify(&watcher, result.completionData.bytesTransferred))
487 result.reactivateRequest(true);
488 }
489 else
490 fileSystemWatcher->asyncNotifyFailure(watcher, result.isValid());
491 SC_COMPILER_WARNING_POP_OFFSETOF;
492 }
493
494#endif
495};
496
498} // namespace SC
FileSystemWatcherAsyncT is an implementation of SC::FileSystemWatcher that uses SC::Async.
Definition FileSystemWatcher.h:296
Abstract class to use event loop notifications (see SC::FileSystemWatcherAsync).
Definition FileSystemWatcher.h:205
Represents a single folder being watched.
Definition FileSystemWatcher.h:163
Function< void(const Notification &)> notifyCallback
Function that will be called on a notification.
Definition FileSystemWatcher.h:170
FolderWatcher(Span< char > subFolderRelativePathsBuffer={})
Constructs a folder watcher.
ResultFileSystemWatcher stopWatching()
Stop watching this directory.
void setDebugName(const char *debugName)
Sets debug name for AsyncExternalCompletion used on Windows (used only for debug purposes)
Notification holding type and path.
Definition FileSystemWatcher.h:138
NotificationKind kind
Change or monitoring status.
Definition FileSystemWatcher.h:143
StringSpan relativePath
Relative path of the file being notified from basePath
Definition FileSystemWatcher.h:140
Operation operation
Coarse change class.
Definition FileSystemWatcher.h:142
StringSpan basePath
Reference to the watched directory.
Definition FileSystemWatcher.h:139
ResultFileSystemWatcher failure
Failure when kind is WatchStopped; successful otherwise.
Definition FileSystemWatcher.h:145
ResultFileSystemWatcher getFullPath(StringPath &path) const
Get the full path of the file being watched.
Notifies about events (add, remove, rename, modified) on files and directories.
Definition FileSystemWatcher.h:62
ResultFileSystemWatcher watch(FolderWatcher &watcher, StringSpan path)
Starts watching a single directory, calling FolderWatcher::notifyCallback on file events.
ResultFileSystemWatcher close()
Stops all watchers and frees the ThreadRunner or EventLoopRunner passed in init.
Operation
Specifies the event classes.
Definition FileSystemWatcher.h:123
@ Modified
A file or directory has been modified in its contents and/or timestamp.
@ AddRemoveRename
A file or directory has been added, removed or renamed.
NotificationKind
Describes whether a notification represents a change or a loss of monitoring information.
Definition FileSystemWatcher.h:130
@ WatchStopped
Monitoring has stopped for this root; inspect Notification::failure before restarting.
@ RescanRequired
Changes were lost; rescan the watched tree and restore coverage if necessary.
@ Change
A file or directory may have changed.
ResultFileSystemWatcher init(ThreadRunner &runner)
Setup watcher to receive notifications from a background thread.
OpaqueObject< ThreadRunnerDefinition > ThreadRunner
Delivers notifications on a background thread.
Definition FileSystemWatcher.h:238
ResultFileSystemWatcher init(EventLoopRunner &runner)
Setup watcher to receive async notifications on an event loop.
FileSystemWatcher result retaining backend-stage and native-error context.
Definition FileSystemWatcherError.h:90