Fray Engine
Loading...
Searching...
No Matches
file_watcher.hpp
Go to the documentation of this file.
1#ifndef FRAY_FILE_WATCHER_HPP
2#define FRAY_FILE_WATCHER_HPP
3
4#include <chrono>
5#include <cstdint>
6#include <deque>
7#include <filesystem>
8#include <functional>
9#include <map>
10#include <mutex>
11#include <string>
12#include <utility>
13#include <vector>
14
15#ifdef _WIN32
16#ifndef NOMINMAX
17#define NOMINMAX
18#endif
19#ifndef WIN32_LEAN_AND_MEAN
20#define WIN32_LEAN_AND_MEAN
21#endif
22#include <windows.h>
23#else
24#include <sys/stat.h>
25#endif
26
27#include "thread_manager.hpp"
28
29namespace fray
30{
31 namespace watch
32 {
36 struct FileId
37 {
41 std::uint64_t device = 0;
45 std::uint64_t index = 0;
46
50 bool valid() const { return device != 0 || index != 0; }
57 const FileId& other) const { return device == other.device && index == other.index; }
58
64 const FileId& other) const { return !(*this == other); }
65
71 const FileId& other) const
72 {
73 return device != other.device ? device < other.device : index < other.index;
74 }
75 };
76
83 inline bool fileId(
84 const std::filesystem::path& path,
85 FileId& id)
86 {
87#ifdef _WIN32
88 HANDLE handle = CreateFileW(path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
89 nullptr, OPEN_EXISTING,
90 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
91 if (handle == INVALID_HANDLE_VALUE)
92 return false;
93 BY_HANDLE_FILE_INFORMATION info;
94 const bool ok = GetFileInformationByHandle(handle, &info) != 0;
95 CloseHandle(handle);
96 if (!ok)
97 return false;
98 id.device = info.dwVolumeSerialNumber;
99 id.index = (static_cast<std::uint64_t>(info.nFileIndexHigh) << 32) | info.nFileIndexLow;
100#else
101 struct stat status;
102 if (::lstat(path.c_str(), &status) != 0)
103 return false;
104 id.device = static_cast<std::uint64_t>(status.st_dev);
105 id.index = static_cast<std::uint64_t>(status.st_ino);
106#endif
107 return id.valid();
108 }
109
114
118 struct Change
119 {
127 std::filesystem::path path;
131 std::filesystem::path previousPath;
135 std::string relative;
139 std::string previousRelative;
143 bool directory = false;
147 bool root = false;
152 };
153
160 {
161 public:
166 using Filter = std::function<bool(const Change&)>;
171 using Handler = std::function<void(const Change&)>;
175 using Subscription = std::uint64_t;
176
177 private:
181 struct Entry
182 {
190 std::uintmax_t size = 0;
194 std::filesystem::file_time_type time;
198 bool directory = false;
199 };
200
203 using Snapshot = std::map<std::string, Entry>;
222
226 mutable std::recursive_mutex _scan;
230 std::filesystem::path _root;
238 bool _watching = false;
243
247 std::mutex _queueMutex;
251 std::deque<Change> _queue;
255 std::vector<Subscriber> _subscribers;
263 std::function<void()> _notify;
264
272 const std::filesystem::path& root)
273 {
274 Snapshot snapshot;
275 std::error_code error;
276 std::filesystem::recursive_directory_iterator it(
277 root, std::filesystem::directory_options::skip_permission_denied, error), end;
278 for (; !error && it != end; it.increment(error))
279 {
280 std::error_code entryError;
281 const auto status = it->symlink_status(entryError);
282 if (entryError)
283 continue;
284 Entry entry;
285 entry.directory = std::filesystem::is_directory(status);
286 if (!fileId(it->path(), entry.id))
287 continue;
288 if (!entry.directory)
289 {
290 entry.size = it->is_regular_file(entryError) ? it->file_size(entryError) : 0;
291 entry.time = std::filesystem::last_write_time(it->path(), entryError);
292 }
293 snapshot[it->path().lexically_relative(root).generic_string()] = entry;
294 }
295 return snapshot;
296 }
297
304 static bool inside(
305 const std::string& path,
306 const std::string& folder)
307 {
308 return path.size() > folder.size() && path.compare(0, folder.size(), folder) == 0 &&
309 path[folder.size()] == '/';
310 }
311
317 std::vector<Change>& changes)
318 {
319 if (changes.empty())
320 return;
321 std::lock_guard<std::mutex> lock(_queueMutex);
322 for (auto& change : changes)
323 _queue.push_back(std::move(change));
324 }
325
333 void diff(
334 const Snapshot& before,
335 const Snapshot& after,
336 std::vector<Change>& changes) const
337 {
338 std::map<FileId, std::string> added;
339 for (const auto& entry : after)
340 if (before.find(entry.first) == before.end())
341 added[entry.second.id] = entry.first;
342
343 std::vector<std::pair<std::string, std::string>> folderRenames;
344 std::vector<Change> renames, removals, additions, modifications;
345 std::map<std::string, bool> matched;
346 for (const auto& entry : before)
347 {
348 const auto now = after.find(entry.first);
349 if (now != after.end())
350 {
351 const Entry& was = entry.second;
352 const Entry& is = now->second;
353 if (was.id != is.id || (!is.directory && (was.size != is.size || was.time != is.time)))
354 {
355 Change change;
356 change.kind = ChangeKind::Modified;
357 change.relative = entry.first;
358 change.directory = is.directory;
359 change.id = is.id;
360 modifications.push_back(std::move(change));
361 }
362 continue;
363 }
364 const auto moved = added.find(entry.second.id);
365 Change change;
366 change.relative = entry.first;
367 change.directory = entry.second.directory;
368 if (moved == added.end())
369 {
370 change.kind = ChangeKind::Removed;
371 removals.push_back(std::move(change));
372 continue;
373 }
374 change.kind = ChangeKind::Renamed;
375 change.previousRelative = entry.first;
376 change.relative = moved->second;
377 change.id = entry.second.id;
378 matched[moved->second] = true;
379 if (change.directory)
380 folderRenames.emplace_back(change.previousRelative, change.relative);
381 renames.push_back(std::move(change));
382 }
383 for (const auto& entry : after)
384 {
385 if (before.find(entry.first) != before.end() || matched.count(entry.first))
386 continue;
387 Change change;
388 change.kind = ChangeKind::Added;
389 change.relative = entry.first;
390 change.directory = entry.second.directory;
391 change.id = entry.second.id;
392 additions.push_back(std::move(change));
393 }
394 const std::size_t first = changes.size();
395 // Children of a renamed folder moved with it; report only the folder.
396 for (auto& change : renames)
397 {
398 bool carried = false;
399 for (const auto& folder : folderRenames)
400 if (inside(change.previousRelative, folder.first) &&
401 change.relative == folder.second + change.previousRelative.substr(folder.first.size()))
402 carried = true;
403 if (!carried)
404 changes.push_back(std::move(change));
405 }
406 for (auto* group : {&removals, &additions, &modifications})
407 for (auto& change : *group)
408 changes.push_back(std::move(change));
409 for (std::size_t i = first; i < changes.size(); ++i)
410 {
411 Change& change = changes[i];
412 change.path = _root / std::filesystem::path(change.relative);
413 if (change.kind == ChangeKind::Renamed)
414 change.previousPath = _root / std::filesystem::path(change.previousRelative);
415 }
416 }
417
418 public:
422 FileWatcher() = default;
427 const FileWatcher&) = delete;
432 const FileWatcher&) = delete;
433
440 bool watch(
441 const std::filesystem::path& root)
442 {
443 std::lock_guard<std::recursive_mutex> lock(_scan);
444 FileId id;
445 if (!fileId(root, id))
446 return false;
447 _root = root;
448 _rootId = id;
449 _snapshot = scanFolder(root);
450 _watching = true;
451 return true;
452 }
453
457 void unwatch()
458 {
459 std::lock_guard<std::recursive_mutex> lock(_scan);
460 _watching = false;
461 _snapshot.clear();
462 }
463
468 std::unique_lock<std::recursive_mutex> hold() { return std::unique_lock<std::recursive_mutex>(_scan); }
469
477 Filter filter,
478 Handler handler)
479 {
480 std::lock_guard<std::mutex> lock(_queueMutex);
481 const Subscription id = _nextSubscription++;
482 _subscribers.push_back({id, std::move(filter), std::move(handler)});
483 return id;
484 }
485
492 Subscription id)
493 {
494 std::lock_guard<std::mutex> lock(_queueMutex);
495 for (auto it = _subscribers.begin(); it != _subscribers.end(); ++it)
496 if (it->id == id)
497 {
498 _subscribers.erase(it);
499 return;
500 }
501 }
502
509 std::function<void()> notify)
510 {
511 std::lock_guard<std::mutex> lock(_queueMutex);
512 _notify = std::move(notify);
513 }
514
521 std::size_t poll()
522 {
523 std::vector<Change> changes;
524 {
525 std::lock_guard<std::recursive_mutex> lock(_scan);
526 if (!_watching)
527 return 0;
528 FileId current;
529 if (!fileId(_root, current) || current != _rootId)
530 {
531 // The folder is gone from this path; look for it under a new name next to it.
532 std::filesystem::path moved;
533 std::error_code error;
534 std::filesystem::directory_iterator it(_root.parent_path(), error), end;
535 for (; !error && it != end; it.increment(error))
536 {
537 FileId candidate;
538 if (fileId(it->path(), candidate) && candidate == _rootId)
539 {
540 moved = it->path();
541 break;
542 }
543 }
544 Change change;
545 change.root = true;
546 change.directory = true;
547 change.id = _rootId;
548 change.previousPath = _root;
549 if (moved.empty())
550 {
551 change.kind = ChangeKind::Removed;
552 change.path = _root;
553 _watching = false;
554 changes.push_back(std::move(change));
555 enqueue(changes);
556 return 1;
557 }
558 change.kind = ChangeKind::Renamed;
559 change.path = moved;
560 _root = moved;
561 changes.push_back(std::move(change));
562 }
563 Snapshot after = scanFolder(_root);
564 diff(_snapshot, after, changes);
565 _snapshot = std::move(after);
566 enqueue(changes);
567 }
568 return changes.size();
569 }
570
576 std::size_t dispatch()
577 {
578 std::deque<Change> changes;
579 std::vector<Subscriber> subscribers;
580 {
581 std::lock_guard<std::mutex> lock(_queueMutex);
582 changes.swap(_queue);
583 subscribers = _subscribers;
584 }
585 for (const auto& change : changes)
586 for (const auto& subscriber : subscribers)
587 if (!subscriber.filter || subscriber.filter(change))
588 subscriber.handler(change);
589 return changes.size();
590 }
591
600 void run(
601 const threads::StopToken& token,
602 std::function<void()> tick = nullptr,
603 std::chrono::milliseconds interval = std::chrono::milliseconds(1000))
604 {
605 while (!token.waitFor(interval))
606 {
607 const std::size_t changes = poll();
608 if (tick)
609 tick();
610 if (changes == 0)
611 continue;
612 std::function<void()> notify;
613 {
614 std::lock_guard<std::mutex> lock(_queueMutex);
615 notify = _notify;
616 }
617 if (notify)
618 notify();
619 }
620 }
621 };
622 }
623}
624
625#endif
Cooperative cancellation shared by every copy of a token. Copies share one state guarded by an intern...
bool waitFor(const std::chrono::duration< Rep, Period > &duration) const
Sleeps for up to duration; returns true as soon as a stop is requested.
void unwatch()
Stops scanning and clears the snapshot under _scan; queued changes remain available.
void run(const threads::StopToken &token, std::function< void()> tick=nullptr, std::chrono::milliseconds interval=std::chrono::milliseconds(1000))
Polls repeatedly on the calling thread until the stop token signals. Intended for a ThreadManager thr...
FileWatcher & operator=(const FileWatcher &)=delete
Copy assignment is disabled for this synchronized watcher.
std::filesystem::path _root
Current watched root path, updated when the root is renamed.
std::unique_lock< std::recursive_mutex > hold()
Returns an owning _scan lock that blocks polling until released. Use around filesystem changes and a ...
std::vector< Subscriber > _subscribers
Registered subscribers, protected by _queueMutex.
void setNotify(std::function< void()> notify)
Replaces the run-loop notification callback under _queueMutex. run() copies and invokes it on the pol...
std::deque< Change > _queue
Pending changes awaiting dispatch, protected by _queueMutex.
std::mutex _queueMutex
Protects the change queue, subscribers, subscription counter and notify callback.
void diff(const Snapshot &before, const Snapshot &after, std::vector< Change > &changes) const
Appends changes between snapshots, suppressing child renames carried by a folder rename....
static bool inside(const std::string &path, const std::string &folder)
Tests whether a generic relative path is a strict descendant of a folder path.
std::map< std::string, Entry > Snapshot
Map of root-relative generic paths to scanned entry metadata.
std::size_t dispatch()
Drains queued changes and delivers them to a snapshot of subscribers on the calling thread....
Subscription subscribe(Filter filter, Handler handler)
Registers callbacks under _queueMutex for future dispatch snapshots.
std::function< bool(const Change &)> Filter
Predicate receiving a change and returning true to deliver it; an empty filter accepts all changes....
std::function< void()> _notify
Optional run-loop notification callback, protected by _queueMutex.
Subscription _nextSubscription
Next subscription identifier, protected by _queueMutex.
bool watch(const std::filesystem::path &root)
Starts or restarts watching with a silent baseline, also acknowledging owner-made changes....
std::function< void(const Change &)> Handler
Callback receiving a delivered change on the dispatch() caller’s thread. It runs without the queue mu...
FileWatcher()=default
Constructs an inactive watcher.
void unsubscribe(Subscription id)
Removes a subscription under _queueMutex, if present. A dispatch already holding a copied subscriber ...
void enqueue(std::vector< Change > &changes)
Moves changes into the pending queue while holding _queueMutex.
std::recursive_mutex _scan
Protects watch state and snapshots; hold() exposes a scoped lock for owner operations.
bool _watching
Whether polling has an active baseline.
std::uint64_t Subscription
Identifier used to unregister a subscriber.
static Snapshot scanFolder(const std::filesystem::path &root)
Scans a folder tree, skipping entries whose status or identity cannot be read. Iteration stops on an ...
std::size_t poll()
Compares the watched tree with its baseline and enqueues detected changes. Holds _scan during scannin...
Snapshot _snapshot
Most recent tree snapshot, protected by _scan.
FileWatcher(const FileWatcher &)=delete
Copy construction is disabled for this synchronized watcher.
FileId _rootId
Identity used to detect root removal or sibling rename.
ChangeKind
Identifies an added, removed, renamed or modified entry.
bool fileId(const std::filesystem::path &path, FileId &id)
Reads the entry identity without following a symbolic link.
Describes a detected change to the watched root or one of its entries.
std::filesystem::path previousPath
Previous path for a rename; root removals also record the old root here.
ChangeKind kind
Kind of change detected.
bool root
Whether the change describes the watched root itself.
std::filesystem::path path
Path of the changed entry when detected, based on the watched root.
FileId id
Entry identity when available; ordinary entry removals leave it unset.
std::string previousRelative
Previous root-relative entry path for a rename.
std::string relative
Entry path relative to the watched root, empty for root changes.
bool directory
Whether the changed entry is a directory.
Filesystem identity surviving renames: device and inode, or volume and file index.
std::uint64_t index
Inode number or file index.
bool operator!=(const FileId &other) const
Tests two identities for inequality.
bool operator<(const FileId &other) const
Orders identities by device and then index.
std::uint64_t device
Device number or volume serial number.
bool operator==(const FileId &other) const
Tests two identities for equality.
bool valid() const
Returns whether either identity component is nonzero.
Snapshot metadata for one filesystem entry.
std::filesystem::file_time_type time
Last-write time used for non-directory modification detection.
std::uintmax_t size
File size used for modification detection; zero for directories.
FileId id
Filesystem identity of the entry.
bool directory
Whether the entry is a directory.
Subscription identifier and callbacks copied for dispatch.
Filter filter
Optional predicate controlling delivery.
Subscription id
Identifier assigned at subscription.
Handler handler
Handler invoked for matching changes.