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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
#![doc(html_favicon_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo-icon.png")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo.png")]
//!
//! File system events and service.
//!
//! # Crate
//!
#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
// suppress nag about very simple boxed closure signatures.
#![allow(clippy::type_complexity)]
#![warn(unused_extern_crates)]
#![warn(missing_docs)]
use std::{
collections::{hash_map, HashMap},
fmt, fs,
io::{self, Write as _},
mem, ops,
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, AtomicU64},
Arc,
},
thread,
time::{Duration, SystemTime},
};
use atomic::{Atomic, Ordering};
use fs4::FileExt;
use notify::Watcher;
use parking_lot::Mutex;
use path_absolutize::Absolutize;
use zng_app::{
app_hn_once,
event::{event, event_args, EventHandle},
handler::{AppHandler, FilterAppHandler},
timer::{DeadlineHandle, TIMERS},
update::EventUpdate,
view_process::raw_events::LOW_MEMORY_EVENT,
AppExtension, DInstant, INSTANT,
};
use zng_app_context::{app_local, LocalContext};
use zng_clone_move::clmv;
use zng_handle::{Handle, HandleOwner};
use zng_txt::Txt;
use zng_unit::TimeUnits;
use zng_var::{
types::WeakArcVar, var, AnyVar, AnyVarHookArgs, AnyWeakVar, ArcVar, ReadOnlyArcVar, Var, VarUpdateId, VarValue, WeakVar, VARS,
};
use zng_task as task;
/// Application extension that provides file system change events and service.
///
/// # Events
///
/// Events this extension provides.
///
/// * [`FS_CHANGES_EVENT`]
///
/// # Services
///
/// Services this extension provides.
///
/// * [`WATCHER`]
#[derive(Default)]
pub struct FsWatcherManager {}
impl AppExtension for FsWatcherManager {
fn init(&mut self) {
WATCHER_SV.write().init_watcher();
}
fn event_preview(&mut self, update: &mut EventUpdate) {
if let Some(args) = FS_CHANGES_EVENT.on(update) {
WATCHER_SV.write().event(args);
} else if LOW_MEMORY_EVENT.on(update).is_some() {
WATCHER_SV.write().low_memory();
}
}
fn update_preview(&mut self) {
WATCHER_SV.write().update();
}
fn deinit(&mut self) {
let mut flush = WATCHER_SV.write().shutdown();
for v in &mut flush {
v.flush_shutdown();
}
}
}
/// File system watcher service.
///
/// This is mostly a wrapper around the [`notify`](https://docs.rs/notify) crate, integrating it with events and variables.
pub struct WATCHER;
impl WATCHER {
/// Gets a read-write variable that defines interval awaited between each [`FS_CHANGES_EVENT`]. If
/// a watched path is constantly changing an event will be emitted every elapse of this interval,
/// the event args will contain a list of all the changes observed during the interval.
///
/// Note that the first event notifies immediately, only subsequent events within this interval are debounced.
///
/// Is `100.ms()` by default.
pub fn debounce(&self) -> ArcVar<Duration> {
WATCHER_SV.read().debounce.clone()
}
/// Gets a read-write variable that defines interval awaited between each [`sync`] write.
///
/// Is `100.ms()` by default.
///
/// [`sync`]: WATCHER::sync
pub fn sync_debounce(&self) -> ArcVar<Duration> {
WATCHER_SV.read().debounce.clone()
}
/// Gets a read-write variable that defines the fallback poll watcher interval.
///
/// When an efficient watcher cannot be used a poll watcher fallback is used, the poll watcher reads
/// the directory or path every elapse of this interval. The poll watcher is also used for paths that
/// do not exist yet, that is also affected by this interval.
///
/// Is `1.secs()` by default.
pub fn poll_interval(&self) -> ArcVar<Duration> {
WATCHER_SV.read().poll_interval.clone()
}
/// Maximum time the service keeps the process alive to process pending IO operations when the app shuts down.
///
/// Is 1 minute by default.
pub fn shutdown_timeout(&self) -> ArcVar<Duration> {
WATCHER_SV.read().shutdown_timeout.clone()
}
/// Enable file change events for the `file`.
///
/// Returns a handle that will stop the file watch when dropped, if there is no other active handler for the same file.
///
/// Note that this is implemented by actually watching the parent directory and filtering the events, this is done
/// to ensure the watcher survives operations that remove the file and then move another file to the same path.
///
/// See [`watch_dir`] for more details.
///
/// [`watch_dir`]: WATCHER::watch_dir
pub fn watch(&self, file: impl Into<PathBuf>) -> WatcherHandle {
WATCHER_SV.write().watch(file.into())
}
/// Enable file change events for files inside `dir`, also include inner directories if `recursive` is `true`.
///
/// Returns a handle that will stop the dir watch when dropped, if there is no other active handler for the same directory.
///
/// The directory will be watched using an OS specific efficient watcher provided by the [`notify`](https://docs.rs/notify) crate. If there is
/// any error creating the watcher, such as if the directory does not exist yet a slower polling watcher will retry periodically
/// until the efficient watcher can be created or the handle is dropped.
pub fn watch_dir(&self, dir: impl Into<PathBuf>, recursive: bool) -> WatcherHandle {
WATCHER_SV.write().watch_dir(dir.into(), recursive)
}
/// Read a file into a variable, the `init` value will start the variable and the `read` closure will be called
/// once immediately and every time the file changes, if the closure returns `Some(O)` the variable updates with the new value.
///
/// Dropping the variable drops the read watch. The `read` closure is non-blocking, it is called in a [`task::wait`]
/// background thread.
///
/// [`task::wait`]: zng_task::wait
pub fn read<O: VarValue>(
&self,
file: impl Into<PathBuf>,
init: O,
read: impl FnMut(io::Result<WatchFile>) -> Option<O> + Send + 'static,
) -> ReadOnlyArcVar<O> {
WATCHER_SV.write().read(file.into(), init, read)
}
/// Same operation as [`read`] but also tracks the operation status in a second var.
///
/// The status variable is set to [`WatcherReadStatus::reading`] as soon as `read` starts and
/// is set to [`WatcherReadStatus::idle`] only when it updates with new read value.
///
/// [`read`]: Self::read
pub fn read_status<O, S, E>(
&self,
file: impl Into<PathBuf>,
init: O,
read: impl FnMut(io::Result<WatchFile>) -> Result<Option<O>, E> + Send + 'static,
) -> (ReadOnlyArcVar<O>, ReadOnlyArcVar<S>)
where
O: VarValue,
S: WatcherReadStatus<E>,
{
WATCHER_SV.write().read_status(file.into(), init, read)
}
/// Read a directory into a variable, the `init` value will start the variable and the `read` closure will be called
/// once immediately and every time any changes happen inside the dir, if the closure returns `Some(O)` the variable updates with the new value.
///
/// The `read` closure parameter is a directory walker from the [`walkdir`](https://docs.rs/walkdir) crate.
///
/// The directory walker is pre-configured to skip the `dir` itself and to have a max-depth of 1 if not `recursive`, these configs can.
///
/// Dropping the variable drops the read watch. The `read` closure is non-blocking, it is called in a [`task::wait`]
/// background thread.
///
/// [`task::wait`]: zng_task::wait
pub fn read_dir<O: VarValue>(
&self,
dir: impl Into<PathBuf>,
recursive: bool,
init: O,
read: impl FnMut(walkdir::WalkDir) -> Option<O> + Send + 'static,
) -> ReadOnlyArcVar<O> {
WATCHER_SV.write().read_dir(dir.into(), recursive, init, read)
}
/// Same operation as [`read_dir`] but also tracks the operation status in a second var.
///
/// The status variable is set to [`WatcherReadStatus::reading`] as soon as `read` starts and
/// is set to [`WatcherReadStatus::idle`] only when it updates with new read value.
///
/// [`read_dir`]: Self::read_dir
pub fn read_dir_status<O, S, E>(
&self,
dir: impl Into<PathBuf>,
recursive: bool,
init: O,
read: impl FnMut(walkdir::WalkDir) -> Result<Option<O>, E> + Send + 'static,
) -> (ReadOnlyArcVar<O>, ReadOnlyArcVar<S>)
where
O: VarValue,
S: WatcherReadStatus<E>,
{
WATCHER_SV.write().read_dir_status(dir.into(), recursive, init, read)
}
/// Bind a file with a variable, the `file` will be `read` when it changes and be `write` when the variable changes,
/// writes are only applied on success and will not cause a `read` on the same sync task. The `init` value is used to
/// create the variable, if the `file` exists it will be `read` once at the beginning.
///
/// Dropping the variable drops the read watch. The `read` and `write` closures are non-blocking, they are called in a [`task::wait`]
/// background thread.
///
/// # Sync
///
/// The file synchronization ensures that the file is only actually modified when writing is finished by writing
/// to a temporary file and committing a replace only if the write succeeded. The file is write-locked for the duration
/// of `write` call, but the contents are not touched until commit. See [`WriteFile`] for more details.
///
/// The [`FsWatcherManager`] blocks on app exit until all writes commit or cancel.
///
/// ## Read Errors
///
/// Not-found errors are handled by the watcher by calling `write` using the current variable value, other read errors
/// are passed to `read`. If `read` returns a value for an error the `write` closure is called to override the file,
/// otherwise only the variable is set and this variable update does not cause a `write`.
///
/// ## Write Errors
///
/// If `write` fails the file is not touched and the temporary file is removed, if the file path
/// does not exit all missing parent folders and the file will be created automatically before the `write`
/// call.
///
/// Note that [`WriteFile::commit`] must be called to flush the temporary file and attempt to rename
/// it, if the file is dropped without commit it will cancel and log an error, you must call [`WriteFile::cancel`]
/// to correctly avoid writing.
///
/// If the cleanup after commit fails the error is logged and ignored.
///
/// If write fails to even create the file and/or acquire a write lock on it this error is the input for
/// the `write` closure.
///
/// ## Error Handling
///
/// You can call services or set other variables from inside the `read` and `write` closures, this can be
/// used to get a signal out that perhaps drops the sync var (to stop watching), alert the user that the
/// file is out of sync and initiate some sort of recovery routine.
///
/// If the file synchronization is not important you can just ignore it, the watcher will try again
/// on the next variable or file update.
///
/// ## Status
///
/// Note that `read` and `write` run in background task threads, so if you are tracking the operation
/// status in a separate variable you may end-up with synchronization bugs between th status variable
/// and the actual result variable, you can use [`sync_status`] to implement racing-free status tracking.
///
/// [`sync_status`]: Self::sync_status
/// [`task::wait`]: zng_task::wait
pub fn sync<O: VarValue>(
&self,
file: impl Into<PathBuf>,
init: O,
read: impl FnMut(io::Result<WatchFile>) -> Option<O> + Send + 'static,
write: impl FnMut(O, io::Result<WriteFile>) + Send + 'static,
) -> ArcVar<O> {
WATCHER_SV.write().sync(file.into(), init, read, write)
}
/// Same operation as [`sync`] but also tracks the operation status in a second var.
///
/// The status variable is set to [`WatcherSyncStatus::writing`] as soon as it updates and
/// is set to [`WatcherReadStatus::idle`] only when the new sync value is available, either
/// by update or because read the same value.
///
/// [`sync`]: Self::sync
pub fn sync_status<O, S, ER, EW>(
&self,
file: impl Into<PathBuf>,
init: O,
read: impl FnMut(io::Result<WatchFile>) -> Result<Option<O>, ER> + Send + 'static,
write: impl FnMut(O, io::Result<WriteFile>) -> Result<(), EW> + Send + 'static,
) -> (ArcVar<O>, ReadOnlyArcVar<S>)
where
O: VarValue,
S: WatcherSyncStatus<ER, EW>,
{
WATCHER_SV.write().sync_status(file.into(), init, read, write)
}
/// Watch `file` and calls `handler` every time it changes.
///
/// Note that the `handler` is blocking, use [`async_app_hn!`] and [`task::wait`] to run IO without
/// blocking the app.
///
/// [`async_app_hn!`]: macro@zng_app::handler::async_app_hn
/// [`task::wait`]: zng_task::wait
pub fn on_file_changed(&self, file: impl Into<PathBuf>, handler: impl AppHandler<FsChangesArgs>) -> EventHandle {
let file = file.into();
let handle = self.watch(file.clone());
FS_CHANGES_EVENT.on_event(FilterAppHandler::new(handler, move |args| {
let _handle = &handle;
args.events_for_path(&file).next().is_some()
}))
}
/// Watch `dir` and calls `handler` every time something inside it changes.
///
/// Note that the `handler` is blocking, use [`async_app_hn!`] and [`task::wait`] to run IO without
/// blocking the app.
///
/// [`async_app_hn!`]: macro@zng_app::handler::async_app_hn
/// [`task::wait`]: zng_task::wait
pub fn on_dir_changed(&self, dir: impl Into<PathBuf>, recursive: bool, handler: impl AppHandler<FsChangesArgs>) -> EventHandle {
let dir = dir.into();
let handle = self.watch_dir(dir.clone(), recursive);
FS_CHANGES_EVENT.on_event(FilterAppHandler::new(handler, move |args| {
let _handle = &handle;
args.events_for_path(&dir).next().is_some()
}))
}
/// Push a `note` that will be cloned on all subsequent change events until it the returned handle is dropped.
///
/// This can be used to tag all events that happened over a period of time, something you can't do just
/// by receiving the events due to async delays caused by debounce.
///
/// Note that the underlying system events the [`notify`](https://docs.rs/notify) crate uses are not guaranteed to be synchronous.
pub fn annotate(&self, note: Arc<dyn FsChangeNote>) -> FsChangeNoteHandle {
WATCHER_SV.write().annotate(note)
}
}
/// Represents a status type for [`WATCHER.sync_status`].
///
/// [`WATCHER.sync_status`]: WATCHER::sync_status
pub trait WatcherSyncStatus<ER = io::Error, EW = io::Error>: WatcherReadStatus<ER> {
/// New writing value.
fn writing() -> Self;
/// New write error value.
fn write_error(e: EW) -> Self;
}
/// Represents a status type for [`WATCHER`] read-only operations.
pub trait WatcherReadStatus<ER = io::Error>: VarValue + PartialEq {
/// New idle value.
fn idle() -> Self;
/// New reading value.
fn reading() -> Self;
/// New read error value.
fn read_error(e: ER) -> Self;
}
/// Represents an open read-only file provided by [`WATCHER.read`].
///
/// This type is a thin wrapper around the [`std::fs::File`] with some convenience parsing methods.
///
/// [`WATCHER.read`]: WATCHER::read
#[derive(Debug)]
pub struct WatchFile(fs::File);
impl WatchFile {
/// Open read the file.
pub fn open(file: impl AsRef<Path>) -> io::Result<Self> {
Self::try_open_non_empty(file.as_ref(), true)
}
fn try_open_non_empty(path: &Path, retry: bool) -> io::Result<Self> {
let file = fs::File::open(path)?;
if retry && file.metadata()?.len() == 0 {
// some apps create an empty file unlocked, then write.
let _ = file;
std::thread::sleep(5.ms());
return Self::try_open_non_empty(path, false);
}
lock_shared(&file, Duration::from_secs(10))?;
Ok(Self(file))
}
/// Read the file contents as a text string.
pub fn text(&mut self) -> io::Result<Txt> {
self.string().map(Txt::from)
}
/// Read the file contents as a string.
pub fn string(&mut self) -> io::Result<String> {
use std::io::Read;
let mut s = String::new();
self.0.read_to_string(&mut s)?;
Ok(s)
}
/// Deserialize the file contents as JSON.
#[cfg(feature = "json")]
pub fn json<O>(&mut self) -> serde_json::Result<O>
where
O: serde::de::DeserializeOwned,
{
serde_json::from_reader(io::BufReader::new(&mut self.0))
}
/// Deserialize the file contents as TOML.
#[cfg(feature = "toml")]
pub fn toml<O>(&mut self) -> io::Result<O>
where
O: serde::de::DeserializeOwned,
{
use std::io::Read;
let mut buf = io::BufReader::new(&mut self.0);
let mut toml_str = String::new();
buf.read_to_string(&mut toml_str)?;
toml::de::from_str(&toml_str).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
/// Deserialize the file content as RON.
#[cfg(feature = "ron")]
pub fn ron<O>(&mut self) -> Result<O, ron::de::SpannedError>
where
O: serde::de::DeserializeOwned,
{
ron::de::from_reader(io::BufReader::new(&mut self.0))
}
/// Deserialize the file content as YAML.
#[cfg(feature = "yaml")]
pub fn yaml<O>(&mut self) -> serde_yaml::Result<O>
where
O: serde::de::DeserializeOwned,
{
serde_yaml::from_reader(io::BufReader::new(&mut self.0))
}
/// Read file and parse it.
pub fn parse<O: std::str::FromStr>(&mut self) -> Result<O, WatchFileParseError<O::Err>> {
use std::io::Read;
let mut s = String::new();
self.0.read_to_string(&mut s)?;
O::from_str(&s).map_err(WatchFileParseError::Parse)
}
}
impl ops::Deref for WatchFile {
type Target = fs::File;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for WatchFile {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Drop for WatchFile {
fn drop(&mut self) {
let _ = self.0.unlock();
}
}
const TRANSACTION_GUID: &str = "6eIw3bYMS0uKaQMkTIQacQ";
const TRANSACTION_LOCK_EXT: &str = "6eIw3bYMS0uKaQMkTIQacQ-lock.tmp";
/// Represents an open write file provided by [`WATCHER.sync`].
///
/// This type actually writes to a temporary file and rename it over the actual file on commit only.
/// The dereferenced [`fs::File`] is the temporary file, not the actual one.
///
/// # Transaction
///
/// To minimize the risk of file corruption exclusive locks are used, both the target file and the temp file
/// are locked. An empty lock file is also used to cover the moment when both files are unlocked for the rename operation
/// and the moment the temp file is acquired.
///
/// The temp file is the actual file path with file extension replaced with `{path/.file-name.ext}.{GUID}-{n}.tmp`, the `n` is a
/// number from 0 to 999, if a temp file exists unlocked it will be reused.
///
/// The lock file is `{path/.file-name.ext}.{GUID}-lock.tmp`. Note that this
/// lock file only helps for apps that use [`WriteFile`], but even without it the risk is minimal as the slow
/// write operations are already flushed when it is time to commit.
///
/// [`WATCHER.sync`]: WATCHER::sync
pub struct WriteFile {
temp_file: Option<fs::File>,
actual_file: Option<fs::File>,
transaction_lock: Option<fs::File>,
actual_path: PathBuf,
temp_path: PathBuf,
transaction_path: PathBuf,
cleaned: bool,
}
impl Drop for WriteFile {
fn drop(&mut self) {
if !self.cleaned {
tracing::error!("dropped sync write file without commit or cancel");
self.clean();
}
}
}
impl ops::Deref for WriteFile {
type Target = fs::File;
fn deref(&self) -> &Self::Target {
self.temp_file.as_ref().unwrap()
}
}
impl ops::DerefMut for WriteFile {
fn deref_mut(&mut self) -> &mut Self::Target {
self.temp_file.as_mut().unwrap()
}
}
impl WriteFile {
/// Open or create the file.
pub fn open(path: PathBuf) -> io::Result<Self> {
let actual_path = path.absolutize()?.into_owned();
if !actual_path.exists() {
if let Some(parent) = actual_path.parent() {
std::fs::create_dir_all(parent)?;
}
}
let hidden_name = match actual_path.file_name() {
Some(n) => format!(".{}", n.to_string_lossy()),
None => return Err(io::Error::new(io::ErrorKind::InvalidInput, "expected file name")),
};
let transaction_path = actual_path.with_file_name(format!("{hidden_name}.{TRANSACTION_LOCK_EXT}"));
let transaction_lock = fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(&transaction_path)?;
const TIMEOUT: Duration = Duration::from_secs(10);
lock_exclusive(&transaction_lock, TIMEOUT)?;
let actual_file = fs::OpenOptions::new().write(true).create(true).truncate(false).open(&actual_path)?;
lock_exclusive(&actual_file, TIMEOUT)?;
let mut n = 0;
let mut temp_path = actual_path.with_file_name(format!("{hidden_name}.{TRANSACTION_GUID}-{n}.tmp"));
let temp_file = loop {
if let Ok(f) = fs::OpenOptions::new().write(true).create(true).truncate(true).open(&temp_path) {
if f.try_lock_exclusive().is_ok() {
break f;
}
}
n += 1;
temp_path = actual_path.with_file_name(format!("{hidden_name}.{TRANSACTION_GUID}-{n}.tmp"));
n += 1;
if n > 1000 {
return Err(io::Error::new(io::ErrorKind::AlreadyExists, "cannot create temporary file"));
}
};
Ok(Self {
actual_file: Some(actual_file),
temp_file: Some(temp_file),
transaction_lock: Some(transaction_lock),
actual_path,
temp_path,
transaction_path,
cleaned: false,
})
}
/// Write the text string.
pub fn write_text(&mut self, txt: &str) -> io::Result<()> {
self.write_all(txt.as_bytes())
}
/// Serialize and write.
///
/// If `pretty` is `true` the JSON is formatted for human reading.
#[cfg(feature = "json")]
pub fn write_json<O: serde::Serialize>(&mut self, value: &O, pretty: bool) -> io::Result<()> {
let mut buf = io::BufWriter::new(ops::DerefMut::deref_mut(self));
if pretty {
serde_json::to_writer_pretty(&mut buf, value)?;
} else {
serde_json::to_writer(&mut buf, value)?;
}
buf.flush()
}
/// Serialize and write.
///
/// If `pretty` is `true` the TOML is formatted for human reading.
#[cfg(feature = "toml")]
pub fn write_toml<O: serde::Serialize>(&mut self, value: &O, pretty: bool) -> io::Result<()> {
let toml = if pretty {
toml::ser::to_string_pretty(value)
} else {
toml::ser::to_string(value)
}
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
self.write_all(toml.as_bytes())
}
/// Serialize and write.
///
/// If `pretty` is `true` the RON if formatted for human reading using the default pretty config.
#[cfg(feature = "ron")]
pub fn write_ron<O: serde::Serialize>(&mut self, value: &O, pretty: bool) -> io::Result<()> {
let mut buf = io::BufWriter::new(ops::DerefMut::deref_mut(self));
if pretty {
ron::ser::to_writer_pretty(&mut buf, value, Default::default()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
} else {
ron::ser::to_writer(&mut buf, value).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
}
buf.flush()
}
/// Serialize and write.
#[cfg(feature = "yaml")]
pub fn write_yaml<O: serde::Serialize>(&mut self, value: &O) -> io::Result<()> {
let mut buf = io::BufWriter::new(ops::DerefMut::deref_mut(self));
serde_yaml::to_writer(&mut buf, value).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
buf.flush()
}
/// Commit write, flush and replace the actual file with the new one.
pub fn commit(mut self) -> io::Result<()> {
let r = self.replace_actual();
self.clean();
r
}
/// Cancel write, the file will not be updated.
pub fn cancel(mut self) {
self.clean();
}
fn replace_actual(&mut self) -> io::Result<()> {
let mut temp_file = self.temp_file.take().unwrap();
temp_file.flush()?;
temp_file.sync_all()?;
unlock_ok(&temp_file).unwrap();
drop(temp_file);
let actual_file = self.actual_file.take().unwrap();
unlock_ok(&actual_file)?;
drop(actual_file);
let mut retries = 0;
loop {
// commit by replacing the actual_path with already on disk temp_path file.
match fs::rename(&self.temp_path, &self.actual_path) {
Ok(()) => {
break;
}
Err(e) => match e.kind() {
io::ErrorKind::PermissionDenied => {
if retries == 5 {
// Give-up, we manage to write lock both temp and actual just
// before this, but now we can't replace actual and remove temp.
// Hardware issue? Or another process holding a lock for 1s+50ms*5.
return Err(e);
} else if retries > 0 {
// Second+ retries:
//
// probably a system issue.
//
// Windows sporadically returns ACCESS_DENIED for kernel!SetRenameInformationFile in
// other apps that use the same save pattern (write-tmp -> close-tmp -> rename).
// see GIMP issue: https://gitlab.gnome.org/GNOME/gimp/-/issues/1370
//
// I used procmon to trace all file operations, there is no other app trying to use
// the temp and actual files when the ACCESS_DENIED occurs, both files are unlocked and
// closed before the rename calls start. This might be a Windows bug.
std::thread::sleep(30.ms());
} else {
// first retry:
//
// probably another process reading the `actual_path`.
//
// Reacquire a write lock and unlock, just to wait the external app.
match std::fs::File::options().write(true).open(&self.actual_path) {
Ok(f) => {
if lock_exclusive(&f, 10.secs()).is_ok() {
// acquired actual ok, retry
let _ = unlock_ok(&f);
}
}
Err(e) => match e.kind() {
io::ErrorKind::NotFound => {
// all good, rename will create actual
continue;
}
_ => {
// unknown error, let retry handle it
std::thread::sleep(30.ms());
}
},
}
}
retries += 1;
}
_ => return Err(e),
},
}
}
Ok(())
}
fn clean(&mut self) {
self.cleaned = true;
if let Some(tmp) = self.temp_file.take() {
let _ = tmp.unlock();
}
if let Err(e) = fs::remove_file(&self.temp_path) {
tracing::debug!("failed to cleanup temp file, {e}")
}
if let Some(file) = self.actual_file.take() {
let _ = file.unlock();
}
let transaction = self.transaction_lock.take().unwrap();
let _ = transaction.unlock();
let _ = fs::remove_file(&self.transaction_path);
}
}
/// Error for [`WatchFile::parse`].
#[derive(Debug)]
pub enum WatchFileParseError<E> {
/// Error reading the file.
Io(io::Error),
/// Error parsing the file.
Parse(E),
}
impl<E> From<io::Error> for WatchFileParseError<E> {
fn from(value: io::Error) -> Self {
Self::Io(value)
}
}
impl<E: fmt::Display> fmt::Display for WatchFileParseError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WatchFileParseError::Io(e) => write!(f, "read error, {e}"),
WatchFileParseError::Parse(e) => write!(f, "parse error, {e}"),
}
}
}
impl<E: std::error::Error + 'static> std::error::Error for WatchFileParseError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
WatchFileParseError::Io(e) => Some(e),
WatchFileParseError::Parse(e) => Some(e),
}
}
}
/// Represents a [`FsChange`] note.
///
/// This trait is already implemented for types it applies.
#[diagnostic::on_unimplemented(note = "`FsChangeNote` is implemented for all `T: Debug + Any + Send + Sync`")]
pub trait FsChangeNote: fmt::Debug + std::any::Any + Send + Sync {
/// Access any.
fn as_any(&self) -> &dyn std::any::Any;
}
impl<T: fmt::Debug + std::any::Any + Send + Sync> FsChangeNote for T {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
/// Handle that holds a [`WATCHER.annotate`] note.
///
/// [`WATCHER.annotate`]: WATCHER::annotate
#[derive(Clone)]
#[must_use = "the note is removed when the handle is dropped"]
pub struct FsChangeNoteHandle(#[allow(dead_code)] Arc<Arc<dyn FsChangeNote>>);
/// Annotation for file watcher events and var update tags.
///
/// Identifies the [`WATCHER.sync`] file that is currently being written to.
///
/// [`WATCHER.sync`]: WATCHER::sync
#[derive(Debug, PartialEq, Eq)]
pub struct WatcherSyncWriteNote(PathBuf);
impl WatcherSyncWriteNote {
/// Deref.
pub fn as_path(&self) -> &Path {
self
}
}
impl ops::Deref for WatcherSyncWriteNote {
type Target = Path;
fn deref(&self) -> &Self::Target {
self.0.as_path()
}
}
/// File system change event types.
///
/// The event for each change is available in [`FsChange::event`].
///
/// This module re-exports types from the [`notify`](https://docs.rs/notify) crate.
pub mod fs_event {
pub use notify::event::{
AccessKind, AccessMode, CreateKind, DataChange, Event, EventKind, MetadataKind, ModifyKind, RemoveKind, RenameMode,
};
pub use notify::{Error, ErrorKind};
}
/// Represents a single file system change, annotated.
#[derive(Debug)]
pub struct FsChange {
/// All [`WATCHER.annotate`] that where set when this event happened.
///
/// [`WATCHER.annotate`]: WATCHER::annotate
pub notes: Vec<Arc<dyn FsChangeNote>>,
/// The actual notify event or error.
pub event: Result<fs_event::Event, fs_event::Error>,
}
impl FsChange {
/// If the change affects the `path`.
pub fn is_for_path(&self, path: &Path) -> bool {
if let Ok(ev) = &self.event {
return ev.paths.iter().any(|p| p.starts_with(path));
}
false
}
/// If the change affects any path matched by the glob pattern.
pub fn is_for_glob(&self, pattern: &glob::Pattern) -> bool {
if let Ok(ev) = &self.event {
return ev.paths.iter().any(|p| pattern.matches_path(p));
}
false
}
/// Iterate over all notes of the type `T`.
pub fn notes<T: FsChangeNote>(&self) -> impl Iterator<Item = &T> {
self.notes.iter().filter_map(|n| FsChangeNote::as_any(&**n).downcast_ref::<T>())
}
}
event_args! {
/// [`FS_CHANGES_EVENT`] arguments.
pub struct FsChangesArgs {
/// All notify changes since the last event.
pub changes: Arc<Vec<FsChange>>,
..
/// None, only app level handlers receive this event.
fn delivery_list(&self, list: &mut UpdateDeliveryList) {
let _ = list;
}
}
}
impl FsChangesArgs {
/// Iterate over all change events.
pub fn events(&self) -> impl Iterator<Item = &fs_event::Event> + '_ {
self.changes.iter().filter_map(|r| r.event.as_ref().ok())
}
/// Iterate over all file watcher errors.
pub fn errors(&self) -> impl Iterator<Item = ¬ify::Error> + '_ {
self.changes.iter().filter_map(|r| r.event.as_ref().err())
}
/// Returns `true` is some events where lost.
///
/// This indicates either a lapse in the events or a change in the filesystem such that events
/// received so far can no longer be relied on to represent the state of the filesystem now.
///
/// An application that simply reacts to file changes may not care about this. An application
/// that keeps an in-memory representation of the filesystem will need to care, and will need
/// to refresh that representation directly from the filesystem.
pub fn rescan(&self) -> bool {
self.events().any(|e| e.need_rescan())
}
/// Iterate over all changes that affects paths selected by the `glob` pattern.
pub fn changes_for(&self, glob: &str) -> Result<impl Iterator<Item = &FsChange> + '_, glob::PatternError> {
let glob = glob::Pattern::new(glob)?;
Ok(self.changes.iter().filter(move |c| c.is_for_glob(&glob)))
}
/// Iterate over all changes that affects paths that are equal to `path` or inside it.
pub fn changes_for_path<'a>(&'a self, path: &'a Path) -> impl Iterator<Item = &FsChange> + 'a {
self.changes.iter().filter(move |c| c.is_for_path(path))
}
/// Iterate over all change events that affects that are equal to `path` or inside it.
pub fn events_for(&self, glob: &str) -> Result<impl Iterator<Item = &fs_event::Event> + '_, glob::PatternError> {
let glob = glob::Pattern::new(glob)?;
Ok(self.events().filter(move |ev| ev.paths.iter().any(|p| glob.matches_path(p))))
}
/// Iterate over all change events that affects paths that are equal to `path` or inside it.
pub fn events_for_path<'a>(&'a self, path: &'a Path) -> impl Iterator<Item = &fs_event::Event> + 'a {
self.events().filter(move |ev| ev.paths.iter().any(|p| p.starts_with(path)))
}
}
event! {
/// Event sent by the [`WATCHER`] service on directories or files that are watched.
pub static FS_CHANGES_EVENT: FsChangesArgs;
}
/// Represents an active file or directory watcher in [`WATCHER`].
#[derive(Clone)]
#[must_use = "the watcher is dropped if the handle is dropped"]
pub struct WatcherHandle(Handle<()>);
impl WatcherHandle {
/// Handle to no watcher.
pub fn dummy() -> Self {
Self(Handle::dummy(()))
}
/// If [`perm`](Self::perm) was called in another clone of this handle.
///
/// If `true` the resource will stay in memory for the duration of the app, unless [`force_drop`](Self::force_drop)
/// is also called.
pub fn is_permanent(&self) -> bool {
self.0.is_permanent()
}
/// Force drops the watcher, meaning it will be dropped even if there are other handles active.
pub fn force_drop(self) {
self.0.force_drop()
}
/// If the watcher is dropped.
pub fn is_dropped(&self) -> bool {
self.0.is_dropped()
}
/// Drop the handle without dropping the watcher, the watcher will stay active for the
/// duration of the app process.
pub fn perm(self) {
self.0.perm()
}
}
app_local! {
static WATCHER_SV: WatcherService = WatcherService::new();
}
struct WatcherService {
debounce: ArcVar<Duration>,
sync_debounce: ArcVar<Duration>,
poll_interval: ArcVar<Duration>,
shutdown_timeout: ArcVar<Duration>,
watcher: Watchers,
debounce_oldest: DInstant,
debounce_buffer: Vec<FsChange>,
debounce_timer: Option<DeadlineHandle>,
read_to_var: Vec<ReadToVar>,
sync_with_var: Vec<SyncWithVar>,
notes: Vec<std::sync::Weak<Arc<dyn FsChangeNote>>>,
}
impl WatcherService {
fn new() -> Self {
Self {
debounce: var(100.ms()),
sync_debounce: var(100.ms()),
poll_interval: var(1.secs()),
shutdown_timeout: var(1.minutes()),
watcher: Watchers::new(),
debounce_oldest: INSTANT.now(),
debounce_buffer: vec![],
debounce_timer: None,
read_to_var: vec![],
sync_with_var: vec![],
notes: vec![],
}
}
fn init_watcher(&mut self) {
self.watcher.init();
}
fn event(&mut self, args: &FsChangesArgs) {
self.read_to_var.retain_mut(|f| f.on_event(args));
self.sync_with_var.retain_mut(|f| f.on_event(args));
}
fn low_memory(&mut self) {
self.read_to_var.retain_mut(|v| v.retain());
let sync_debounce = self.sync_debounce.get();
self.sync_with_var.retain_mut(|v| v.retain(sync_debounce));
}
fn update(&mut self) {
if let Some(n) = self.poll_interval.get_new() {
self.watcher.set_poll_interval(n);
}
if !self.debounce_buffer.is_empty() {
if let Some(n) = self.debounce.get_new() {
if self.debounce_oldest.elapsed() >= n {
self.notify();
}
}
}
self.read_to_var.retain_mut(|f| f.retain());
let sync_debounce = self.sync_debounce.get();
self.sync_with_var.retain_mut(|f| f.retain(sync_debounce));
}
fn watch(&mut self, file: PathBuf) -> WatcherHandle {
self.watcher.watch(file)
}
fn watch_dir(&mut self, dir: PathBuf, recursive: bool) -> WatcherHandle {
self.watcher.watch_dir(dir, recursive)
}
fn read<O: VarValue>(
&mut self,
file: PathBuf,
init: O,
read: impl FnMut(io::Result<WatchFile>) -> Option<O> + Send + 'static,
) -> ReadOnlyArcVar<O> {
let handle = self.watch(file.clone());
fn open(p: &Path) -> io::Result<WatchFile> {
WatchFile::open(p)
}
let (read, var) = ReadToVar::new(handle, file, init, open, read, || {});
self.read_to_var.push(read);
var
}
fn read_status<O, S, E>(
&mut self,
file: PathBuf,
init: O,
mut read: impl FnMut(io::Result<WatchFile>) -> Result<Option<O>, E> + Send + 'static,
) -> (ReadOnlyArcVar<O>, ReadOnlyArcVar<S>)
where
O: VarValue,
S: WatcherReadStatus<E>,
{
let handle = self.watch(file.clone());
fn open(p: &Path) -> io::Result<WatchFile> {
WatchFile::open(p)
}
let status = var(S::reading());
let (read, var) = ReadToVar::new(
handle,
file,
init,
open,
// read
clmv!(status, |d| {
status.set(S::reading());
match read(d) {
Ok(r) => {
if r.is_none() {
status.set(S::idle());
}
r
}
Err(e) => {
status.set(S::read_error(e));
None
}
}
}),
// on_modify
clmv!(status, || {
status.set(S::idle());
}),
);
self.read_to_var.push(read);
(var, status.read_only())
}
fn read_dir<O: VarValue>(
&mut self,
dir: PathBuf,
recursive: bool,
init: O,
read: impl FnMut(walkdir::WalkDir) -> Option<O> + Send + 'static,
) -> ReadOnlyArcVar<O> {
let handle = self.watch_dir(dir.clone(), recursive);
fn open(p: &Path) -> walkdir::WalkDir {
walkdir::WalkDir::new(p).min_depth(1).max_depth(1)
}
fn open_recursive(p: &Path) -> walkdir::WalkDir {
walkdir::WalkDir::new(p).min_depth(1)
}
let (read, var) = ReadToVar::new(handle, dir, init, if recursive { open_recursive } else { open }, read, || {});
self.read_to_var.push(read);
var
}
fn read_dir_status<O, S, E>(
&mut self,
dir: PathBuf,
recursive: bool,
init: O,
mut read: impl FnMut(walkdir::WalkDir) -> Result<Option<O>, E> + Send + 'static,
) -> (ReadOnlyArcVar<O>, ReadOnlyArcVar<S>)
where
O: VarValue,
S: WatcherReadStatus<E>,
{
let status = var(S::reading());
let handle = self.watch_dir(dir.clone(), recursive);
fn open(p: &Path) -> walkdir::WalkDir {
walkdir::WalkDir::new(p).min_depth(1).max_depth(1)
}
fn open_recursive(p: &Path) -> walkdir::WalkDir {
walkdir::WalkDir::new(p).min_depth(1)
}
let (read, var) = ReadToVar::new(
handle,
dir,
init,
if recursive { open_recursive } else { open },
// read
clmv!(status, |d| {
status.set(S::reading());
match read(d) {
Ok(r) => {
if r.is_none() {
status.set(S::idle());
}
r
}
Err(e) => {
status.set(S::read_error(e));
None
}
}
}),
// on_modify
clmv!(status, || {
status.set(S::idle());
}),
);
self.read_to_var.push(read);
(var, status.read_only())
}
fn sync<O: VarValue>(
&mut self,
file: PathBuf,
init: O,
read: impl FnMut(io::Result<WatchFile>) -> Option<O> + Send + 'static,
mut write: impl FnMut(O, io::Result<WriteFile>) + Send + 'static,
) -> ArcVar<O> {
let handle = self.watch(file.clone());
let (sync, var) = SyncWithVar::new(handle, file, init, read, move |o, _, f| write(o, f), |_| {});
self.sync_with_var.push(sync);
var
}
pub fn sync_status<O, S, ER, EW>(
&mut self,
file: PathBuf,
init: O,
mut read: impl FnMut(io::Result<WatchFile>) -> Result<Option<O>, ER> + Send + 'static,
mut write: impl FnMut(O, io::Result<WriteFile>) -> Result<(), EW> + Send + 'static,
) -> (ArcVar<O>, ReadOnlyArcVar<S>)
where
O: VarValue,
S: WatcherSyncStatus<ER, EW>,
{
let handle = self.watch(file.clone());
let latest_write = Arc::new(Atomic::new(VarUpdateId::never()));
let status = var(S::reading());
let (sync, var) = SyncWithVar::new(
handle,
file,
init,
// read
clmv!(status, |f| {
status.set(S::reading());
match read(f) {
Ok(r) => {
if r.is_none() {
status.set(S::idle());
}
r
}
Err(e) => {
status.set(S::read_error(e));
None
}
}
}),
// write
clmv!(status, latest_write, |o, o_id, f| {
status.set(S::writing()); // init write
match write(o, f) {
Ok(()) => {
if latest_write.load(Ordering::Relaxed) == o_id {
status.set(S::idle());
}
}
Err(e) => {
status.set(S::write_error(e));
}
}
}),
// hook&modify
clmv!(status, |is_read| {
status.set(if is_read {
S::idle()
} else {
let id = VARS.update_id();
latest_write.store(id, Ordering::Relaxed);
S::writing()
});
}),
);
self.sync_with_var.push(sync);
(var, status.read_only())
}
fn on_watcher(&mut self, r: Result<fs_event::Event, fs_event::Error>) {
if let Ok(r) = &r {
if !self.watcher.allow(r) {
// file parent watcher, file not affected.
return;
}
}
let notify = self.debounce_oldest.elapsed() >= self.debounce.get();
let mut notes = Vec::with_capacity(self.notes.len());
self.notes.retain(|n| match n.upgrade() {
Some(n) => {
notes.push(Arc::clone(&*n));
true
}
None => false,
});
self.debounce_buffer.push(FsChange { notes, event: r });
if notify {
self.notify();
} else if self.debounce_timer.is_none() {
self.debounce_timer = Some(TIMERS.on_deadline(
self.debounce.get(),
app_hn_once!(|_| {
WATCHER_SV.write().on_debounce_timer();
}),
));
}
}
fn annotate(&mut self, note: Arc<dyn FsChangeNote>) -> FsChangeNoteHandle {
let handle = Arc::new(note);
self.notes.push(Arc::downgrade(&handle));
FsChangeNoteHandle(handle)
}
fn on_debounce_timer(&mut self) {
if !self.debounce_buffer.is_empty() {
self.notify();
}
}
fn notify(&mut self) {
let changes = mem::take(&mut self.debounce_buffer);
let now = INSTANT.now();
self.debounce_oldest = now;
self.debounce_timer = None;
FS_CHANGES_EVENT.notify(FsChangesArgs::new(now, Default::default(), changes));
}
/// Deinit watcher, returns items to flush without a service lock.
fn shutdown(&mut self) -> Vec<SyncWithVar> {
self.watcher.deinit();
mem::take(&mut self.sync_with_var)
}
}
fn notify_watcher_handler() -> impl notify::EventHandler {
let mut ctx = LocalContext::capture();
move |r| ctx.with_context(|| WATCHER_SV.write().on_watcher(r))
}
struct ReadToVar {
read: Box<dyn Fn(&Arc<AtomicBool>, &WatcherHandle, ReadEvent) + Send + Sync>,
pending: Arc<AtomicBool>,
handle: WatcherHandle,
}
impl ReadToVar {
fn new<O: VarValue, R: 'static>(
handle: WatcherHandle,
mut path: PathBuf,
init: O,
load: fn(&Path) -> R,
read: impl FnMut(R) -> Option<O> + Send + 'static,
on_modify: impl Fn() + Send + Sync + 'static,
) -> (Self, ReadOnlyArcVar<O>) {
if let Ok(p) = path.absolutize() {
path = p.into_owned();
}
let path = Arc::new(path);
let var = var(init);
let on_modify = Arc::new(on_modify);
let pending = Arc::new(AtomicBool::new(false));
let read = Arc::new(Mutex::new(read));
let wk_var = var.downgrade();
// read task "drains" pending, drops handle if the var is dropped.
let read = Box::new(move |pending: &Arc<AtomicBool>, handle: &WatcherHandle, ev: ReadEvent| {
if wk_var.strong_count() == 0 {
handle.clone().force_drop();
return;
}
let spawn = match ev {
ReadEvent::Update => false,
ReadEvent::Event(args) => !pending.load(Ordering::Relaxed) && args.events_for_path(&path).next().is_some(),
ReadEvent::Init => true,
};
if !spawn {
return;
}
pending.store(true, Ordering::Relaxed);
if read.try_lock().is_none() {
// another task already running.
return;
}
task::spawn_wait(clmv!(read, wk_var, path, handle, pending, on_modify, || {
let mut read = read.lock();
while pending.swap(false, Ordering::Relaxed) {
if let Some(update) = read(load(path.as_path())) {
if let Some(var) = wk_var.upgrade() {
var.modify(clmv!(on_modify, |vm| {
vm.set(update);
on_modify();
}));
} else {
// var dropped
handle.force_drop();
break;
}
}
}
}));
});
read(&pending, &handle, ReadEvent::Init);
(Self { read, pending, handle }, var.read_only())
}
/// Match the event and flag variable update.
///
/// Returns if the variable is still alive.
pub fn on_event(&mut self, args: &FsChangesArgs) -> bool {
if !self.handle.is_dropped() {
(self.read)(&self.pending, &self.handle, ReadEvent::Event(args));
}
!self.handle.is_dropped()
}
/// Returns if the variable is still alive.
fn retain(&mut self) -> bool {
if !self.handle.is_dropped() {
(self.read)(&self.pending, &self.handle, ReadEvent::Update);
}
!self.handle.is_dropped()
}
}
enum ReadEvent<'a> {
Update,
Event(&'a FsChangesArgs),
Init,
}
struct SyncWithVar {
task: Box<dyn Fn(&WatcherHandle, SyncEvent) + Send + Sync>,
handle: WatcherHandle,
}
impl SyncWithVar {
fn new<O, R, W, U>(handle: WatcherHandle, mut file: PathBuf, init: O, read: R, write: W, var_hook_and_modify: U) -> (Self, ArcVar<O>)
where
O: VarValue,
R: FnMut(io::Result<WatchFile>) -> Option<O> + Send + 'static,
W: FnMut(O, VarUpdateId, io::Result<WriteFile>) + Send + 'static,
U: Fn(bool) + Send + Sync + 'static,
{
if let Ok(p) = file.absolutize() {
file = p.into_owned();
}
let path = Arc::new(WatcherSyncWriteNote(file));
let latest_from_read = Arc::new(AtomicBool::new(false));
let var_hook_and_modify = Arc::new(var_hook_and_modify);
let var = var(init);
var.hook_any(Box::new(clmv!(
path,
latest_from_read,
var_hook_and_modify,
|args: &AnyVarHookArgs| {
let is_read = args.downcast_tags::<Arc<WatcherSyncWriteNote>>().any(|n| n == &path);
latest_from_read.store(is_read, Ordering::Relaxed);
var_hook_and_modify(is_read);
true
}
)))
.perm();
type PendingFlag = u8;
const READ: PendingFlag = 0b01;
const WRITE: PendingFlag = 0b11;
struct TaskData<R, W, O: VarValue> {
pending: Atomic<PendingFlag>,
read_write: Mutex<(R, W)>,
wk_var: WeakArcVar<O>,
last_write: AtomicU64, // ms from epoch
}
let task_data = Arc::new(TaskData {
pending: Atomic::new(0),
read_write: Mutex::new((read, write)),
wk_var: var.downgrade(),
last_write: AtomicU64::new(0),
});
// task drains pending, drops handle if the var is dropped.
let task = Box::new(move |handle: &WatcherHandle, ev: SyncEvent| {
let var = match task_data.wk_var.upgrade() {
Some(v) => v,
None => {
handle.clone().force_drop();
return;
}
};
let mut debounce = None;
let mut pending = 0;
match ev {
SyncEvent::Update(sync_debounce) => {
if var.is_new() && !latest_from_read.load(Ordering::Relaxed) {
debounce = Some(sync_debounce);
pending |= WRITE;
} else {
return;
}
}
SyncEvent::Event(args) => {
if args.rescan() {
pending |= READ;
} else {
'ev: for ev in args.changes_for_path(&path) {
for note in ev.notes::<WatcherSyncWriteNote>() {
if path.as_path() == note.as_path() {
// we caused this event
continue 'ev;
}
}
pending |= READ;
break;
}
if pending == 0 {
return;
}
}
}
SyncEvent::Init => {
if path.exists() {
pending |= READ;
} else {
pending |= WRITE;
}
}
SyncEvent::FlushShutdown => {
let timeout = WATCHER_SV.read().shutdown_timeout.get();
if task_data.read_write.try_lock_for(timeout).is_none() {
tracing::error!("not all io operations finished on shutdown, timeout after {timeout:?}");
}
return;
}
};
drop(var);
task_data.pending.fetch_or(pending, Ordering::Relaxed);
if task_data.read_write.try_lock().is_none() {
// another spawn is already applying
return;
}
task::spawn_wait(clmv!(task_data, path, var_hook_and_modify, handle, || {
let mut read_write = task_data.read_write.lock();
let (read, write) = &mut *read_write;
loop {
let pending = task_data.pending.swap(0, Ordering::Relaxed);
if pending == WRITE {
if let Some(d) = debounce {
let now_ms = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let prev_ms = task_data.last_write.load(Ordering::Relaxed);
let elapsed = Duration::from_millis(now_ms - prev_ms);
if elapsed < d {
std::thread::sleep(d - elapsed);
}
task_data.last_write.store(now_ms, Ordering::Relaxed);
}
let (id, value) = if let Some(var) = task_data.wk_var.upgrade() {
(var.last_update(), var.get())
} else {
handle.force_drop();
return;
};
{
let _note = WATCHER.annotate(path.clone());
write(value, id, WriteFile::open(path.to_path_buf()));
}
if task_data.wk_var.strong_count() == 0 {
handle.force_drop();
return;
}
} else if pending == READ {
if task_data.wk_var.strong_count() == 0 {
handle.force_drop();
return;
}
if let Some(update) = read(WatchFile::open(path.as_path())) {
if let Some(var) = task_data.wk_var.upgrade() {
var.modify(clmv!(path, var_hook_and_modify, |vm| {
vm.set(update);
vm.push_tag(path);
var_hook_and_modify(true);
}));
} else {
handle.force_drop();
return;
}
}
} else {
return;
}
}
}));
});
task(&handle, SyncEvent::Init);
(Self { task, handle }, var)
}
/// Match the event and flag variable update.
///
/// Returns if the variable is still alive.
pub fn on_event(&mut self, args: &FsChangesArgs) -> bool {
if !self.handle.is_dropped() {
(self.task)(&self.handle, SyncEvent::Event(args));
}
!self.handle.is_dropped()
}
/// Returns if the variable is still alive.
fn retain(&mut self, sync_debounce: Duration) -> bool {
if !self.handle.is_dropped() {
(self.task)(&self.handle, SyncEvent::Update(sync_debounce));
}
!self.handle.is_dropped()
}
fn flush_shutdown(&mut self) {
if !self.handle.is_dropped() {
(self.task)(&self.handle, SyncEvent::FlushShutdown);
}
}
}
enum SyncEvent<'a> {
Update(Duration),
Event(&'a FsChangesArgs),
Init,
FlushShutdown,
}
struct Watchers {
dirs: HashMap<PathBuf, DirWatcher>,
watcher: Mutex<Box<dyn notify::Watcher + Send>>, // mutex for Sync only
// watcher for paths that the system watcher cannot watch yet.
error_watcher: Option<PollWatcher>,
poll_interval: Duration,
}
impl Watchers {
fn new() -> Self {
Self {
dirs: HashMap::default(),
watcher: Mutex::new(Box::new(notify::NullWatcher)),
error_watcher: None,
poll_interval: 1.secs(),
}
}
fn watch(&mut self, file: PathBuf) -> WatcherHandle {
self.watch_insert(file, WatchMode::File(std::ffi::OsString::new()))
}
fn watch_dir(&mut self, dir: PathBuf, recursive: bool) -> WatcherHandle {
self.watch_insert(dir, if recursive { WatchMode::Descendants } else { WatchMode::Children })
}
/// path can still contain the file name if mode is `WatchMode::File("")`
fn watch_insert(&mut self, mut path: PathBuf, mut mode: WatchMode) -> WatcherHandle {
use path_absolutize::*;
path = match path.absolutize() {
Ok(p) => p.to_path_buf(),
Err(e) => {
tracing::error!("cannot watch `{}`, failed to absolutize `{}`", path.display(), e);
return WatcherHandle::dummy();
}
};
if let WatchMode::File(name) = &mut mode {
if let Some(n) = path.file_name() {
*name = n.to_os_string();
path.pop();
} else {
tracing::error!("cannot watch file `{}`", path.display());
return WatcherHandle::dummy();
}
}
let w = self.dirs.entry(path.clone()).or_default();
for (m, handle) in &w.modes {
if m == &mode {
if let Some(h) = handle.weak_handle().upgrade() {
return WatcherHandle(h);
}
}
}
let (owner, handle) = Handle::new(());
let recursive = matches!(&mode, WatchMode::Descendants);
if w.modes.is_empty() {
if Self::inner_watch_dir(&mut **self.watcher.get_mut(), &path, recursive).is_err() {
Self::inner_watch_error_dir(&mut self.error_watcher, &path, recursive, self.poll_interval);
w.is_in_error_watcher = true;
}
} else {
let was_recursive = w.recursive();
if !was_recursive && recursive {
let watcher = &mut **self.watcher.get_mut();
if mem::take(&mut w.is_in_error_watcher) {
Self::inner_unwatch_dir(self.error_watcher.as_mut().unwrap(), &path);
} else {
Self::inner_unwatch_dir(watcher, &path);
}
if Self::inner_watch_dir(watcher, &path, recursive).is_err() {
Self::inner_watch_error_dir(&mut self.error_watcher, &path, recursive, self.poll_interval);
}
}
}
w.modes.push((mode, owner));
WatcherHandle(handle)
}
fn cleanup(&mut self) {
let watcher = &mut **self.watcher.get_mut();
self.dirs.retain(|k, v| {
let r = v.retain();
if !r {
if v.is_in_error_watcher {
Self::inner_unwatch_dir(self.error_watcher.as_mut().unwrap(), k);
} else {
Self::inner_unwatch_dir(watcher, k);
}
}
r
})
}
fn set_poll_interval(&mut self, interval: Duration) {
self.poll_interval = interval;
if let Err(e) = self
.watcher
.get_mut()
.configure(notify::Config::default().with_poll_interval(interval))
{
tracing::error!("error setting the watcher poll interval: {e}");
}
if let Some(w) = &mut self.error_watcher {
w.configure(notify::Config::default().with_poll_interval(interval)).unwrap();
}
}
fn init(&mut self) {
*self.watcher.get_mut() = match notify::recommended_watcher(notify_watcher_handler()) {
Ok(w) => Box::new(w),
Err(e) => {
tracing::error!("error creating watcher\n{e}\nfallback to slow poll watcher");
match PollWatcher::new(
notify_watcher_handler(),
notify::Config::default().with_poll_interval(self.poll_interval),
) {
Ok(w) => Box::new(w),
Err(e) => {
tracing::error!("error creating poll watcher\n{e}\nfs watching disabled");
Box::new(notify::NullWatcher)
}
}
}
};
self.cleanup();
let watcher = &mut **self.watcher.get_mut();
for (dir, w) in &mut self.dirs {
let recursive = w.recursive();
if Self::inner_watch_dir(watcher, dir.as_path(), recursive).is_err() {
Self::inner_watch_error_dir(&mut self.error_watcher, dir, recursive, self.poll_interval);
w.is_in_error_watcher = true;
}
}
}
fn deinit(&mut self) {
*self.watcher.get_mut() = Box::new(notify::NullWatcher);
}
/// Returns Ok, or Err `PathNotFound` or `MaxFilesWatch` that can be handled using the fallback watcher.
fn inner_watch_dir(watcher: &mut dyn notify::Watcher, dir: &Path, recursive: bool) -> Result<(), notify::ErrorKind> {
let recursive = if recursive {
notify::RecursiveMode::Recursive
} else {
notify::RecursiveMode::NonRecursive
};
if let Err(e) = watcher.watch(dir, recursive) {
match e.kind {
notify::ErrorKind::Generic(e) => {
if dir.try_exists().unwrap_or(true) {
tracing::error!("cannot watch dir `{}`, {e}", dir.display())
} else {
return Err(notify::ErrorKind::PathNotFound);
}
}
notify::ErrorKind::Io(e) => {
if let io::ErrorKind::NotFound = e.kind() {
return Err(notify::ErrorKind::PathNotFound);
} else if dir.try_exists().unwrap_or(true) {
tracing::error!("cannot watch dir `{}`, {e}", dir.display())
} else {
return Err(notify::ErrorKind::PathNotFound);
}
}
e @ notify::ErrorKind::PathNotFound | e @ notify::ErrorKind::MaxFilesWatch => return Err(e),
notify::ErrorKind::InvalidConfig(e) => unreachable!("{e:?}"),
notify::ErrorKind::WatchNotFound => unreachable!(),
}
}
Ok(())
}
fn inner_watch_error_dir(watcher: &mut Option<PollWatcher>, dir: &Path, recursive: bool, poll_interval: Duration) {
let watcher = watcher.get_or_insert_with(|| {
PollWatcher::new(
notify_watcher_handler(),
notify::Config::default().with_poll_interval(poll_interval),
)
.unwrap()
});
Self::inner_watch_dir(watcher, dir, recursive).unwrap();
}
fn inner_unwatch_dir(watcher: &mut dyn notify::Watcher, dir: &Path) {
if let Err(e) = watcher.unwatch(dir) {
match e.kind {
notify::ErrorKind::Generic(e) => {
tracing::error!("cannot unwatch dir `{}`, {e}", dir.display());
}
notify::ErrorKind::Io(e) => {
tracing::error!("cannot unwatch dir `{}`, {e}", dir.display());
}
notify::ErrorKind::PathNotFound => {} // ok?
notify::ErrorKind::WatchNotFound => {} // ok
notify::ErrorKind::InvalidConfig(_) => unreachable!(),
notify::ErrorKind::MaxFilesWatch => unreachable!(),
}
}
}
fn allow(&mut self, r: &fs_event::Event) -> bool {
if let notify::EventKind::Access(_) = r.kind {
if !r.need_rescan() {
return false;
}
}
for (dir, w) in &mut self.dirs {
let mut matched = false;
'modes: for (mode, _) in &w.modes {
match mode {
WatchMode::File(f) => {
for path in &r.paths {
if let Some(name) = path.file_name() {
if name == f {
if let Some(path) = path.parent() {
if path == dir {
// matched `dir/exact`
matched = true;
break 'modes;
}
}
}
}
}
}
WatchMode::Children => {
for path in &r.paths {
if let Some(path) = path.parent() {
if path == dir {
// matched `dir/*`
matched = true;
break 'modes;
}
}
}
}
WatchMode::Descendants => {
for path in &r.paths {
if path.starts_with(dir) {
// matched `dir/**`
matched = true;
break 'modes;
}
}
}
}
}
if matched {
if mem::take(&mut w.is_in_error_watcher) {
// poll watcher managed to reach the path without error, try to move to the
// more performant system watcher.
Self::inner_unwatch_dir(self.error_watcher.as_mut().unwrap(), dir);
let recursive = w.recursive();
if Self::inner_watch_dir(&mut **self.watcher.get_mut(), dir, recursive).is_err() {
// failed again
Self::inner_watch_error_dir(&mut self.error_watcher, dir, recursive, self.poll_interval);
w.is_in_error_watcher = true;
}
}
return true;
}
}
false
}
}
#[derive(PartialEq, Eq)]
enum WatchMode {
File(std::ffi::OsString),
Children,
Descendants,
}
#[derive(Default)]
struct DirWatcher {
is_in_error_watcher: bool,
modes: Vec<(WatchMode, HandleOwner<()>)>,
}
impl DirWatcher {
fn recursive(&self) -> bool {
self.modes.iter().any(|m| matches!(&m.0, WatchMode::Descendants))
}
fn retain(&mut self) -> bool {
self.modes.retain(|(_, h)| !h.is_dropped());
!self.modes.is_empty()
}
}
enum PollMsg {
Watch(PathBuf, bool),
Unwatch(PathBuf),
SetConfig(notify::Config),
}
/// Polling watcher.
///
/// We don't use the `notify` poll watcher to ignore path not found.
struct PollWatcher {
sender: flume::Sender<PollMsg>,
worker: Option<std::thread::JoinHandle<()>>,
}
impl PollWatcher {
fn send_msg(&mut self, msg: PollMsg) {
if self.sender.send(msg).is_err() {
if let Some(worker) = self.worker.take() {
if let Err(panic) = worker.join() {
std::panic::resume_unwind(panic);
}
}
}
}
}
impl notify::Watcher for PollWatcher {
fn new<F: notify::EventHandler>(mut event_handler: F, mut config: notify::Config) -> notify::Result<Self>
where
Self: Sized,
{
let (sender, rcv) = flume::unbounded();
let mut dirs = HashMap::<PathBuf, PollInfo, _>::new();
let worker = std::thread::Builder::new()
.name(String::from("poll-watcher"))
.spawn(move || loop {
match rcv.recv_timeout(config.poll_interval_v2().unwrap_or_default()) {
Ok(msg) => match msg {
PollMsg::Watch(d, r) => {
let info = PollInfo::new(&d, r);
dirs.insert(d, info);
}
PollMsg::Unwatch(d) => {
if dirs.remove(&d).is_none() {
event_handler.handle_event(Err(notify::Error {
kind: notify::ErrorKind::WatchNotFound,
paths: vec![d],
}))
}
}
PollMsg::SetConfig(c) => config = c,
},
Err(e) => match e {
flume::RecvTimeoutError::Timeout => {} // ok
flume::RecvTimeoutError::Disconnected => return, // stop thread
},
}
for (dir, info) in &mut dirs {
info.poll(dir, &mut event_handler);
}
})
.expect("failed to spawn poll-watcher thread");
Ok(Self {
sender,
worker: Some(worker),
})
}
fn watch(&mut self, path: &Path, recursive_mode: notify::RecursiveMode) -> notify::Result<()> {
let msg = PollMsg::Watch(path.to_path_buf(), matches!(recursive_mode, notify::RecursiveMode::Recursive));
self.send_msg(msg);
Ok(())
}
fn unwatch(&mut self, path: &Path) -> notify::Result<()> {
let msg = PollMsg::Unwatch(path.to_path_buf());
self.send_msg(msg);
Ok(())
}
fn configure(&mut self, option: notify::Config) -> notify::Result<bool> {
let msg = PollMsg::SetConfig(option);
self.send_msg(msg);
Ok(true)
}
fn kind() -> notify::WatcherKind
where
Self: Sized,
{
notify::WatcherKind::PollWatcher
}
}
#[derive(Default)]
struct PollInfo {
recursive: bool,
paths: HashMap<PathBuf, PollEntry>,
/// entries with `update_flag` not-eq this are removed.
update_flag: bool,
}
struct PollEntry {
modified: std::time::SystemTime,
/// flipped by `recursive_update` if visited.
update_flag: bool,
}
impl PollInfo {
fn new(path: &Path, recursive: bool) -> Self {
let mut paths = HashMap::new();
for entry in walkdir::WalkDir::new(path)
.min_depth(1)
.max_depth(if recursive { usize::MAX } else { 1 })
.into_iter()
.flatten()
{
if let Some(modified) = entry.metadata().ok().and_then(|m| m.modified().ok()) {
paths.insert(
entry.into_path(),
PollEntry {
modified,
update_flag: false,
},
);
}
}
Self {
recursive,
paths,
update_flag: false,
}
}
fn poll(&mut self, root: &Path, handler: &mut impl notify::EventHandler) {
self.update_flag = !self.update_flag;
for entry in walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(if self.recursive { usize::MAX } else { 1 })
.into_iter()
.flatten()
{
if let Some((is_dir, modified)) = entry.metadata().ok().and_then(|m| Some((m.is_dir(), m.modified().ok()?))) {
match self.paths.entry(entry.into_path()) {
hash_map::Entry::Occupied(mut e) => {
let info = e.get_mut();
info.update_flag = self.update_flag;
if info.modified != modified {
info.modified = modified;
handler.handle_event(Ok(fs_event::Event {
kind: notify::EventKind::Modify(notify::event::ModifyKind::Metadata(
notify::event::MetadataKind::WriteTime,
)),
paths: vec![e.key().clone()],
attrs: Default::default(),
}))
}
}
hash_map::Entry::Vacant(e) => {
handler.handle_event(Ok(fs_event::Event {
kind: notify::EventKind::Create(if is_dir {
notify::event::CreateKind::Folder
} else {
notify::event::CreateKind::File
}),
paths: vec![e.key().clone()],
attrs: Default::default(),
}));
e.insert(PollEntry {
modified,
update_flag: self.update_flag,
});
}
}
}
}
self.paths.retain(|k, e| {
let retain = e.update_flag == self.update_flag;
if !retain {
handler.handle_event(Ok(fs_event::Event {
kind: notify::EventKind::Remove(notify::event::RemoveKind::Any),
paths: vec![k.clone()],
attrs: Default::default(),
}));
}
retain
});
}
}
/// Calls [`fs4::FileExt::lock_exclusive`] with a timeout.
fn lock_exclusive(file: &impl fs4::FileExt, timeout: Duration) -> std::io::Result<()> {
lock_timeout(file, |f| f.try_lock_exclusive(), timeout)
}
/// Calls [`fs4::FileExt::lock_shared`] with a timeout.
fn lock_shared(file: &impl fs4::FileExt, timeout: Duration) -> std::io::Result<()> {
lock_timeout(file, |f| f.try_lock_shared(), timeout)
}
fn lock_timeout<F: fs4::FileExt>(file: &F, try_lock: impl Fn(&F) -> std::io::Result<()>, mut timeout: Duration) -> std::io::Result<()> {
let mut locked_error = None;
loop {
match try_lock(file) {
Ok(()) => return Ok(()),
Err(e) => {
if e.kind() != std::io::ErrorKind::WouldBlock
&& e.raw_os_error() != locked_error.get_or_insert_with(fs4::lock_contended_error).raw_os_error()
{
return Err(e);
}
const INTERVAL: Duration = Duration::from_millis(10);
timeout = timeout.saturating_sub(INTERVAL);
if timeout.is_zero() {
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, e));
} else {
thread::sleep(INTERVAL.min(timeout));
}
}
}
}
}
fn unlock_ok(file: &impl fs4::FileExt) -> std::io::Result<()> {
if let Err(e) = file.unlock() {
if let Some(code) = e.raw_os_error() {
#[cfg(windows)]
if code == 158 {
// ERROR_NOT_LOCKED
return Ok(());
}
#[cfg(unix)]
if code == 22 {
// EINVAL
return Ok(());
}
}
Err(e)
} else {
Ok(())
}
}