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
//! We expect most callers to interact with Kismet via the [`Cache`]
//! struct defined here. A [`Cache`] hides the difference in
//! behaviour between [`crate::plain::Cache`] and
//! [`crate::sharded::Cache`] via late binding, and lets callers
//! transparently handle misses by looking in a series of secondary
//! cache directories.
use std::borrow::Cow;
use std::fs::File;
use std::io::Error;
use std::io::ErrorKind;
use std::io::Result;
use std::path::Path;
use std::sync::Arc;
use derivative::Derivative;
use tempfile::NamedTempFile;
use crate::plain::Cache as PlainCache;
use crate::sharded::Cache as ShardedCache;
use crate::Key;
use crate::ReadOnlyCache;
use crate::ReadOnlyCacheBuilder;
/// A `ConsistencyChecker` function compares cached values for the
/// same key and returns `Err` when the values are incompatible.
type ConsistencyChecker = Arc<
dyn Fn(&mut File, &mut File) -> Result<()>
+ Sync
+ Send
+ std::panic::RefUnwindSafe
+ std::panic::UnwindSafe,
>;
/// The `FullCache` trait exposes both read and write operations as
/// implemented by sharded and plain caches.
trait FullCache:
std::fmt::Debug + Sync + Send + std::panic::RefUnwindSafe + std::panic::UnwindSafe
{
/// Returns a read-only file for `key` in the cache directory if
/// it exists, or None if there is no such file.
///
/// Implicitly "touches" the cached file if it exists.
fn get(&self, key: Key) -> Result<Option<File>>;
/// Returns a temporary directory suitable for temporary files
/// that will be published as `key`.
fn temp_dir(&self, key: Key) -> Result<Cow<Path>>;
/// Inserts or overwrites the file at `value` as `key` in the
/// sharded cache directory.
///
/// Always consumes the file at `value` on success; may consume it
/// on error.
fn set(&self, key: Key, value: &Path) -> Result<()>;
/// Inserts the file at `value` as `key` in the cache directory if
/// there is no such cached entry already, or touches the cached
/// file if it already exists.
///
/// Always consumes the file at `value` on success; may consume it
/// on error.
fn put(&self, key: Key, value: &Path) -> Result<()>;
/// Marks the cached file `key` as newly used, if it exists.
///
/// Returns whether a file for `key` exists in the cache.
fn touch(&self, key: Key) -> Result<bool>;
}
impl FullCache for PlainCache {
fn get(&self, key: Key) -> Result<Option<File>> {
PlainCache::get(self, key.name)
}
fn temp_dir(&self, _key: Key) -> Result<Cow<Path>> {
PlainCache::temp_dir(self)
}
fn set(&self, key: Key, value: &Path) -> Result<()> {
PlainCache::set(self, key.name, value)
}
fn put(&self, key: Key, value: &Path) -> Result<()> {
PlainCache::put(self, key.name, value)
}
fn touch(&self, key: Key) -> Result<bool> {
PlainCache::touch(self, key.name)
}
}
impl FullCache for ShardedCache {
fn get(&self, key: Key) -> Result<Option<File>> {
ShardedCache::get(self, key)
}
fn temp_dir(&self, key: Key) -> Result<Cow<Path>> {
ShardedCache::temp_dir(self, Some(key))
}
fn set(&self, key: Key, value: &Path) -> Result<()> {
ShardedCache::set(self, key, value)
}
fn put(&self, key: Key, value: &Path) -> Result<()> {
ShardedCache::put(self, key, value)
}
fn touch(&self, key: Key) -> Result<bool> {
ShardedCache::touch(self, key)
}
}
/// Construct a [`Cache`] with this builder. The resulting cache will
/// always first access its write-side cache (if defined), and, on
/// misses, will attempt to service [`Cache::get`] and
/// [`Cache::touch`] calls by iterating over the read-only caches.
#[derive(Derivative)]
#[derivative(Debug)]
pub struct CacheBuilder {
write_side: Option<Arc<dyn FullCache>>,
auto_sync: bool,
#[derivative(Debug = "ignore")]
consistency_checker: Option<ConsistencyChecker>,
read_side: ReadOnlyCacheBuilder,
}
impl Default for CacheBuilder {
fn default() -> CacheBuilder {
CacheBuilder {
write_side: None,
auto_sync: true,
consistency_checker: None,
read_side: Default::default(),
}
}
}
/// A [`Cache`] wraps either up to one plain or sharded read-write
/// cache in a convenient interface, and may optionally fulfill read
/// operations by deferring to a list of read-only cache when the
/// read-write cache misses.
///
/// The default cache has no write-side and an empty stack of backup
/// read-only caches.
///
/// [`Cache`] objects are cheap to clone and lock-free; don't put an
/// [`Arc`] on them. Avoid opening multiple caches for the same set
/// of directories: using the same [`Cache`] object improves the
/// accuracy of the write cache's lock-free in-memory statistics, when
/// it's a sharded cache.
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct Cache {
// The write-side cache services writes and is the cache of first
// resort for `get` and `touch`.
write_side: Option<Arc<dyn FullCache>>,
// Whether to automatically sync file contents before publishing
// them to the write-side cache.
auto_sync: bool,
// If provided, `Kismet` will compare results to make sure all
// cache levels that have a value for a given key agree ( the
// checker function returns `Ok(())`).
#[derivative(Debug = "ignore")]
consistency_checker: Option<ConsistencyChecker>,
// The read-side cache (a list of read-only caches) services `get`
// and `touch` calls when we fail to find something in the
// write-side cache.
read_side: ReadOnlyCache,
}
impl Default for Cache {
fn default() -> Cache {
Cache {
write_side: None,
auto_sync: true,
consistency_checker: None,
read_side: Default::default(),
}
}
}
/// Where does a cache hit come from: the primary read-write cache, or
/// one of the secondary read-only caches?
pub enum CacheHit<'a> {
/// The file was found in the primary read-write cache; promoting
/// it is a no-op.
Primary(&'a mut File),
/// The file was found in one of the secondary read-only caches.
/// Promoting it to the primary cache will require a full copy.
Secondary(&'a mut File),
}
/// What to do with a cache hit in a [`Cache::get_or_update`] call?
pub enum CacheHitAction {
/// Return the cache hit as is.
Accept,
/// Return the cache hit after promoting it to the current write
/// cache directory, if necessary.
Promote,
/// Replace with and return a new file.
Replace,
}
impl CacheBuilder {
/// Returns a fresh empty builder.
pub fn new() -> Self {
Self::default()
}
/// Sets the consistency checker function: when the function is
/// provided, the `ReadOnlyCache` will keep searching after the
/// first cache hit, and compare subsequent hits with the first
/// one by calling `checker`. The `checker` function should
/// return `Ok(())` if the two files are compatible (identical),
/// and `Err` otherwise.
///
/// Kismet will propagate the error on mismatch.
pub fn consistency_checker(
&mut self,
checker: impl Fn(&mut File, &mut File) -> Result<()>
+ Sync
+ Send
+ std::panic::RefUnwindSafe
+ std::panic::UnwindSafe
+ Sized
+ 'static,
) -> &mut Self {
self.arc_consistency_checker(Some(Arc::new(checker)))
}
/// Sets the consistency checker function to
/// [`crate::byte_equality_checker`]: the contents of all cache
/// hits must be bytewise identical, without considering any
/// metadata.
pub fn byte_equality_checker(&mut self) -> &mut Self {
self.consistency_checker(crate::byte_equality_checker)
}
/// Sets the consistency checker function to
/// [`crate::panicking_byte_equality_checker`]: the contents of
/// all cache hits must be bytewise identical, without considering
/// any metadata, and the call will panic on mismatch.
pub fn panicking_byte_equality_checker(&mut self) -> &mut Self {
self.consistency_checker(crate::panicking_byte_equality_checker)
}
/// Removes the consistency checker function, if any.
pub fn clear_consistency_checker(&mut self) -> &mut Self {
self.arc_consistency_checker(None)
}
/// Sets the consistency checker function. `None` clears the
/// checker function. See [`CacheBuilder::consistency_checker`].
#[allow(clippy::type_complexity)] // We want the public type to be transparent
pub fn arc_consistency_checker(
&mut self,
checker: Option<
Arc<
dyn Fn(&mut File, &mut File) -> Result<()>
+ Sync
+ Send
+ std::panic::RefUnwindSafe
+ std::panic::UnwindSafe,
>,
>,
) -> &mut Self {
self.consistency_checker = checker.clone();
self.read_side.arc_consistency_checker(checker);
self
}
/// Sets the read-write cache directory to `path`.
///
/// The read-write cache will be a plain cache directory if
/// `num_shards <= 1`, and a sharded directory otherwise.
pub fn writer(
&mut self,
path: impl AsRef<Path>,
num_shards: usize,
total_capacity: usize,
) -> &mut Self {
if num_shards <= 1 {
self.plain_writer(path, total_capacity)
} else {
self.sharded_writer(path, num_shards, total_capacity)
}
}
/// Sets the read-write cache directory to a plain directory at
/// `path`, with a target file count of up to `capacity`.
pub fn plain_writer(&mut self, path: impl AsRef<Path>, capacity: usize) -> &mut Self {
let _ = self.write_side.insert(Arc::new(PlainCache::new(
path.as_ref().to_owned(),
capacity,
)));
self
}
/// Sets the read-write cache directory to a sharded directory at
/// `path`, with `num_shards` subdirectories and a target file
/// count of up to `capacity` for the entire cache.
pub fn sharded_writer(
&mut self,
path: impl AsRef<Path>,
num_shards: usize,
total_capacity: usize,
) -> &mut Self {
let _ = self.write_side.insert(Arc::new(ShardedCache::new(
path.as_ref().to_owned(),
num_shards,
total_capacity,
)));
self
}
/// Sets whether files published read-write cache will be
/// automatically flushed to disk with [`File::sync_all`]
/// before sending them to the cache directory.
///
/// Defaults to true, for safety. Even when `auto_sync` is
/// enabled, Kismet does not `fsync` cache directories; after a
/// kernel or hardware crash, caches may partially revert to an
/// older state, but should not contain incomplete files.
///
/// An application may want to disable `auto_sync` because it
/// already synchronises files, or because the cache directories
/// do not survive crashes: they might be erased after each boot,
/// e.g., via
/// [tmpfiles.d](https://www.freedesktop.org/software/systemd/man/tmpfiles.d.html),
/// or tagged with a [boot id](https://man7.org/linux/man-pages/man3/sd_id128_get_machine.3.html).
pub fn auto_sync(&mut self, sync: bool) -> &mut Self {
self.auto_sync = sync;
self
}
/// Adds a new read-only cache directory at `path` to the end of the
/// cache builder's search list.
///
/// Adds a plain cache directory if `num_shards <= 1`, and a sharded
/// directory otherwise.
pub fn reader(&mut self, path: impl AsRef<Path>, num_shards: usize) -> &mut Self {
self.read_side.cache(path, num_shards);
self
}
/// Adds a new plain (unsharded) read-only cache directory at
/// `path` to the end of the cache builder's search list.
pub fn plain_reader(&mut self, path: impl AsRef<Path>) -> &mut Self {
self.read_side.plain(path);
self
}
/// Adds a new plain cache read-only directory for each path in
/// `paths`. The caches are appended in order to the end of the
/// cache builder's search list.
pub fn plain_readers(
&mut self,
paths: impl IntoIterator<Item = impl AsRef<Path>>,
) -> &mut Self {
self.read_side.plain_caches(paths);
self
}
/// Adds a new sharded read-only cache directory at `path` to the
/// end of the cache builder's search list.
pub fn sharded_reader(&mut self, path: impl AsRef<Path>, num_shards: usize) -> &mut Self {
self.read_side.sharded(path, num_shards);
self
}
/// Returns the contents of `self` as a fresh value; `self` is
/// reset to the default empty builder state. This makes it
/// possible to declare simple configurations in a single
/// expression, with `.take().build()`.
pub fn take(&mut self) -> Self {
std::mem::take(self)
}
/// Returns a fresh [`Cache`] for the builder's write cache and
/// additional search list of read-only cache directories.
pub fn build(self) -> Cache {
Cache {
write_side: self.write_side,
auto_sync: self.auto_sync,
consistency_checker: self.consistency_checker,
read_side: self.read_side.build(),
}
}
}
/// Attempts to set the permissions on `file` to `0444`: the tempfile
/// crate always overrides to 0600 when possible, but that doesn't
/// really make sense for kismet: we don't want cache entries we can
/// tell exist, but can't access. Access control should happen via
/// permissions on the cache directory.
#[cfg(target_family = "unix")]
fn fix_tempfile_permissions(file: &NamedTempFile) -> Result<()> {
use std::fs::Permissions;
use std::os::unix::fs::PermissionsExt;
file.as_file()
.set_permissions(Permissions::from_mode(0o444))
}
#[cfg(not(target_family = "unix"))]
fn fix_tempfile_permissions(_: &NamedTempFile) -> Result<()> {
Ok(())
}
impl Cache {
/// Calls [`File::sync_all`] on `file` if `Cache::auto_sync`
/// is true.
#[inline]
fn maybe_sync(&self, file: &File) -> Result<()> {
if self.auto_sync {
file.sync_all()
} else {
Ok(())
}
}
/// Opens `path` and calls [`File::sync_all`] on the resulting
/// file, if `Cache::auto_sync` is true.
///
/// Panics when [`File::sync_all`] fails. See
/// https://wiki.postgresql.org/wiki/Fsync_Errors or
/// Rebello et al's "Can Applications Recover from fsync Failures?"
/// (https://www.usenix.org/system/files/atc20-rebello.pdf)
/// for an idea of the challenges associated with handling
/// fsync failures on persistent files.
fn maybe_sync_path(&self, path: &Path) -> Result<()> {
if self.auto_sync {
// It's really not clear what happens to a file's content
// if we open it just before fsync, and fsync fails. It
// should be safe to just unlink the file
std::fs::File::open(path)?
.sync_all()
.expect("auto_sync failed, and failure semantics are unclear for fsync");
}
Ok(())
}
/// Attempts to open a read-only file for `key`. The `Cache` will
/// query each its write cache (if any), followed by the list of
/// additional read-only cache, in definition order, and return a
/// read-only file for the first hit.
///
/// Fails with [`ErrorKind::InvalidInput`] if `key.name` is invalid
/// (empty, or starts with a dot or a forward or back slash).
///
/// Returns [`None`] if no file for `key` can be found in any of the
/// constituent caches, and bubbles up the first I/O error
/// encountered, if any.
///
/// In the worst case, each call to `get` attempts to open two
/// files for the [`Cache`]'s read-write directory and for each
/// read-only backup directory.
pub fn get<'a>(&self, key: impl Into<Key<'a>>) -> Result<Option<File>> {
fn doit(
write_side: Option<&dyn FullCache>,
checker: Option<&ConsistencyChecker>,
read_side: &ReadOnlyCache,
key: Key,
) -> Result<Option<File>> {
use std::io::Seek;
use std::io::SeekFrom;
if let Some(write) = write_side {
if let Some(mut ret) = write.get(key)? {
if let Some(checker) = checker {
if let Some(mut read_hit) = read_side.get(key)? {
checker(&mut ret, &mut read_hit)?;
ret.seek(SeekFrom::Start(0))?;
}
}
return Ok(Some(ret));
}
}
read_side.get(key)
}
doit(
self.write_side.as_ref().map(AsRef::as_ref),
self.consistency_checker.as_ref(),
&self.read_side,
key.into(),
)
}
/// Attempts to find a cache entry for `key`. If there is none,
/// populates the cache with a file filled by `populate`. Returns
/// a file in all cases (unless the call fails with an error).
///
/// Always invokes `populate` for a consistency check when a
/// consistency check function is provided. The `populate`
/// function can return `ErrorKind::NotFound` to skip the
/// comparison without failing the whole call.
///
/// Fails with [`ErrorKind::InvalidInput`] if `key.name` is
/// invalid (empty, or starts with a dot or a forward or back slash).
///
/// See [`Cache::get_or_update`] for more control over the operation.
pub fn ensure<'a>(
&self,
key: impl Into<Key<'a>>,
populate: impl FnOnce(&mut File) -> Result<()>,
) -> Result<File> {
fn judge(_: CacheHit) -> CacheHitAction {
CacheHitAction::Promote
}
self.get_or_update(key, judge, |dst, _| populate(dst))
}
/// Attempts to find a cache entry for `key`. If there is none,
/// populates the write cache (if possible) with a file, once
/// filled by `populate`; otherwise obeys the value returned by
/// `judge` to determine what to do with the hit.
///
/// Always invokes `populate` for a consistency check when a
/// consistency check function is provided. The `populate`
/// function can return `ErrorKind::NotFound` to skip the
/// comparison without failing the whole call.
///
/// Fails with [`ErrorKind::InvalidInput`] if `key.name` is
/// invalid (empty, or starts with a dot or a forward or back slash).
///
/// When we need to populate a new file, `populate` is called with
/// a mutable reference to the destination file, and the old
/// cached file (in whatever state `judge` left it), if available.
///
/// See [`Cache::ensure`] for a simpler interface.
///
/// In the worst case, each call to `get_or_update` attempts to
/// open two files for the [`Cache`]'s read-write directory and
/// for each read-only backup directory, and fails to find
/// anything. `get_or_update` then publishes a new cached file
/// (in a constant number of file operations), but not before
/// triggering a second chance maintenance (time linearithmic in
/// the number of files in the directory chosen for maintenance,
/// but amortised to logarithmic).
pub fn get_or_update<'a>(
&self,
key: impl Into<Key<'a>>,
judge: impl FnOnce(CacheHit) -> CacheHitAction,
populate: impl FnOnce(&mut File, Option<File>) -> Result<()>,
) -> Result<File> {
use std::io::Seek;
use std::io::SeekFrom;
// Promotes `file` to `cache`.
fn promote(cache: &dyn FullCache, sync: bool, key: Key, mut file: File) -> Result<File> {
let mut tmp = NamedTempFile::new_in(cache.temp_dir(key)?)?;
std::io::copy(&mut file, tmp.as_file_mut())?;
fix_tempfile_permissions(&tmp)?;
// Force the destination file's contents to disk before
// adding it to the read-write cache, if we're supposed to
// sync files automatically.
if sync {
tmp.as_file().sync_all()?;
}
cache.put(key, tmp.path())?;
// We got a read-only file. Rewind it before returning.
file.seek(SeekFrom::Start(0))?;
Ok(file)
}
let cache_or = self.write_side.as_ref().map(Arc::as_ref);
let key: Key = key.into();
let get_tempfile = || {
if let Some(cache) = cache_or {
tempfile::tempfile_in(cache.temp_dir(key)?)
} else {
tempfile::tempfile()
}
};
let mut old = None; // Overwritten with `Some(file)` when replacing `file`.
if let Some(mut file) = cache_or
.and_then(|cache| cache.get(key).transpose())
.transpose()?
{
if let Some(checker) = self.consistency_checker.as_ref() {
if let Some(mut read) = self.read_side.get(key)? {
checker(&mut file, &mut read)?;
file.seek(SeekFrom::Start(0))?;
}
}
match judge(CacheHit::Primary(&mut file)) {
// Promote is a no-op if the file is already in the write cache.
CacheHitAction::Accept | CacheHitAction::Promote => {
file.seek(SeekFrom::Start(0))?;
if let Some(checker) = self.consistency_checker.as_ref() {
let mut tmp = get_tempfile()?;
match populate(&mut tmp, None) {
Err(e) if e.kind() == ErrorKind::NotFound => {
return Ok(file);
}
ret => ret?,
};
tmp.seek(SeekFrom::Start(0))?;
checker(&mut file, &mut tmp)?;
file.seek(SeekFrom::Start(0))?;
}
return Ok(file);
}
CacheHitAction::Replace => old = Some(file),
}
} else if let Some(mut file) = self.read_side.get(key)? {
match judge(CacheHit::Secondary(&mut file)) {
j @ CacheHitAction::Accept | j @ CacheHitAction::Promote => {
file.seek(SeekFrom::Start(0))?;
if let Some(checker) = self.consistency_checker.as_ref() {
let mut tmp = get_tempfile()?;
match populate(&mut tmp, None) {
Err(e) if e.kind() == ErrorKind::NotFound => {
return Ok(file);
}
ret => ret?,
};
tmp.seek(SeekFrom::Start(0))?;
checker(&mut file, &mut tmp)?;
file.seek(SeekFrom::Start(0))?;
}
return if matches!(j, CacheHitAction::Accept) {
Ok(file)
} else if let Some(cache) = cache_or {
promote(cache, self.auto_sync, key, file)
} else {
Ok(file)
};
}
CacheHitAction::Replace => old = Some(file),
}
}
let cache = match cache_or {
Some(cache) => cache,
None => {
// If there's no write-side cache, satisfy the cache miss
// without saving the result anywhere.
let mut tmp = tempfile::tempfile()?;
populate(&mut tmp, old)?;
tmp.seek(SeekFrom::Start(0))?;
return Ok(tmp);
}
};
let replace = old.is_some();
// We either have to replace or ensure there is a cache entry.
// Either way, start by populating a temporary file.
let mut tmp = NamedTempFile::new_in(cache.temp_dir(key)?)?;
populate(tmp.as_file_mut(), old)?;
fix_tempfile_permissions(&tmp)?;
self.maybe_sync(tmp.as_file())?;
// Grab a read-only return value before publishing the file.
let path = tmp.path();
let mut ret = File::open(path)?;
if replace {
cache.set(key, path)?;
} else {
cache.put(key, path)?;
// Return the now-cached file, if we can get it.
if let Ok(Some(file)) = cache.get(key) {
ret = file;
}
}
Ok(ret)
}
fn set_impl(&self, key: Key, value: &Path) -> Result<()> {
match self.write_side.as_ref() {
Some(write) => write.set(key, value),
None => Err(Error::new(
ErrorKind::Unsupported,
"no kismet write cache defined",
)),
}
}
/// Inserts or overwrites the file at `value` as `key` in the
/// write cache directory. This will always fail with
/// [`ErrorKind::Unsupported`] if no write cache was defined.
/// The path at `value` must be in the same filesystem as the
/// write cache directory: we rely on atomic file renames.
///
/// Fails with [`ErrorKind::InvalidInput`] if `key.name` is invalid
/// (empty, or starts with a dot or a forward or back slash).
///
/// Always consumes the file at `value` on success; may consume it
/// on error.
///
/// When `auto_sync` is enabled (the default), the file at `value`
/// will always be [`File::sync_all`]ed before publishing to the
/// cache. Kismet will **panic** when the [`File::sync_all`] call
/// itself fails: retrying the same call to [`Cache::set`] could
/// erroneously succeed, since some filesystems clear internal I/O
/// failure flag after the first `fsync`.
///
/// Executes in a bounded number of file operations, except for
/// the lock-free maintenance, which needs time linearithmic in
/// the number of files in the directory chosen for maintenance,
/// amortised to logarithmic, and constant number of file operations.
pub fn set<'a>(&self, key: impl Into<Key<'a>>, value: impl AsRef<Path>) -> Result<()> {
fn doit(this: &Cache, key: Key, value: &Path) -> Result<()> {
this.maybe_sync_path(value)?;
this.set_impl(key, value)
}
doit(self, key.into(), value.as_ref())
}
/// Invokes [`Cache::set`] on a [`tempfile::NamedTempFile`].
///
/// See [`Cache::set`] for more details. The only difference is
/// that `set_temp_file` does not panic when `auto_sync` is enabled
/// and we fail to [`File::sync_all`] the [`NamedTempFile`] value.
pub fn set_temp_file<'a>(&self, key: impl Into<Key<'a>>, value: NamedTempFile) -> Result<()> {
fn doit(this: &Cache, key: Key, value: NamedTempFile) -> Result<()> {
fix_tempfile_permissions(&value)?;
this.maybe_sync(value.as_file())?;
this.set_impl(key, value.path())
}
doit(self, key.into(), value)
}
fn put_impl(&self, key: Key, value: &Path) -> Result<()> {
match self.write_side.as_ref() {
Some(write) => write.put(key, value),
None => Err(Error::new(
ErrorKind::Unsupported,
"no kismet write cache defined",
)),
}
}
/// Inserts the file at `value` as `key` in the cache directory if
/// there is no such cached entry already, or touches the cached
/// file if it already exists. This will always fail with
/// [`ErrorKind::Unsupported`] if no write cache was defined.
/// The path at `value` must be in the same filesystem as the
/// write cache directory: we rely on atomic file hard linkage.
///
/// Fails with [`ErrorKind::InvalidInput`] if `key.name` is invalid
/// (empty, or starts with a dot or a forward or back slash).
///
/// Always consumes the file at `value` on success; may consume it
/// on error.
///
/// When `auto_sync` is enabled (the default), the file at `value`
/// will always be [`File::sync_all`]ed before publishing to the
/// cache. Kismet will **panic** when the [`File::sync_all`] call
/// itself fails: retrying the same call to [`Cache::put`] could
/// erroneously succeed, since some filesystems clear internal I/O
/// failure flag after the first `fsync`.
///
/// Executes in a bounded number of file operations, except for
/// the lock-free maintenance, which needs time linearithmic in
/// the number of files in the directory chosen for maintenance,
/// amortised to logarithmic, and constant number of file operations.
pub fn put<'a>(&self, key: impl Into<Key<'a>>, value: impl AsRef<Path>) -> Result<()> {
fn doit(this: &Cache, key: Key, value: &Path) -> Result<()> {
this.maybe_sync_path(value)?;
this.put_impl(key, value)
}
doit(self, key.into(), value.as_ref())
}
/// Invokes [`Cache::put`] on a [`tempfile::NamedTempFile`].
///
/// See [`Cache::put`] for more details. The only difference is
/// that `put_temp_file` does not panic when `auto_sync` is enabled
/// and we fail to [`File::sync_all`] the [`NamedTempFile`] value.
pub fn put_temp_file<'a>(&self, key: impl Into<Key<'a>>, value: NamedTempFile) -> Result<()> {
fn doit(this: &Cache, key: Key, value: NamedTempFile) -> Result<()> {
fix_tempfile_permissions(&value)?;
this.maybe_sync(value.as_file())?;
this.put_impl(key, value.path())
}
doit(self, key.into(), value)
}
/// Marks a cache entry for `key` as accessed (read). The [`Cache`]
/// will touch the same file that would be returned by `get`.
///
/// Fails with [`ErrorKind::InvalidInput`] if `key.name` is invalid
/// (empty, or starts with a dot or a forward or back slash).
///
/// Returns whether a file for `key` could be found, and bubbles
/// up the first I/O error encountered, if any.
///
/// In the worst case, each call to `touch` attempts to update the
/// access time on two files for each cache directory in the
/// `ReadOnlyCache` stack.
pub fn touch<'a>(&self, key: impl Into<Key<'a>>) -> Result<bool> {
fn doit(
write_side: Option<&dyn FullCache>,
read_side: &ReadOnlyCache,
key: Key,
) -> Result<bool> {
if let Some(write) = write_side {
if write.touch(key)? {
return Ok(true);
}
}
read_side.touch(key)
}
doit(
self.write_side.as_ref().map(AsRef::as_ref),
&self.read_side,
key.into(),
)
}
}
#[cfg(test)]
mod test {
use std::fs::File;
use std::io::ErrorKind;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use crate::plain::Cache as PlainCache;
use crate::sharded::Cache as ShardedCache;
use crate::Cache;
use crate::CacheBuilder;
use crate::CacheHit;
use crate::CacheHitAction;
use crate::Key;
struct TestKey {
key: String,
}
impl TestKey {
fn new(key: &str) -> TestKey {
TestKey {
key: key.to_string(),
}
}
}
impl<'a> From<&'a TestKey> for Key<'a> {
fn from(x: &'a TestKey) -> Key<'a> {
Key::new(&x.key, 0, 1)
}
}
fn byte_equality_checker(
counter: Arc<AtomicU64>,
) -> impl 'static + Fn(&mut File, &mut File) -> std::io::Result<()> {
move |x: &mut File, y: &mut File| {
counter.fetch_add(1, Ordering::Relaxed);
crate::byte_equality_checker(x, y)
}
}
// No cache defined -> read calls should successfully do nothing,
// write calls should fail.
#[test]
fn empty() {
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp().create("foo", FileType::RandomFile(10));
let cache: Cache = Default::default();
assert!(matches!(cache.get(&TestKey::new("foo")), Ok(None)));
// Ensure also succeeds: the temporary value is recreated for
// each miss.
assert!(matches!(
cache.ensure(&TestKey::new("foo"), |_| Ok(())),
Ok(_)
));
assert!(matches!(cache.set(&TestKey::new("foo"), &temp.path("foo")),
Err(e) if e.kind() == ErrorKind::Unsupported));
assert!(matches!(cache.put(&TestKey::new("foo"), &temp.path("foo")),
Err(e) if e.kind() == ErrorKind::Unsupported));
assert!(matches!(cache.touch(&TestKey::new("foo")), Ok(false)));
}
// Disable autosync; we should get an `Unsupported` error even if the
// input file does not exist.
#[test]
fn empty_no_auto_sync() {
let cache = CacheBuilder::new().auto_sync(false).take().build();
assert!(matches!(cache.get(&TestKey::new("foo")), Ok(None)));
assert!(matches!(
cache.ensure(&TestKey::new("foo"), |_| Ok(())),
Ok(_)
));
assert!(
matches!(cache.set(&TestKey::new("foo"), "/no-such-tmp/foo"),
Err(e) if e.kind() == ErrorKind::Unsupported)
);
assert!(
matches!(cache.put(&TestKey::new("foo"), "/no-such-tmp/foo"),
Err(e) if e.kind() == ErrorKind::Unsupported)
);
assert!(matches!(cache.touch(&TestKey::new("foo")), Ok(false)));
}
/// Populate two plain caches and set a consistency checker. We
/// should access both.
#[test]
fn consistency_checker_success() {
use std::io::Error;
use std::io::ErrorKind;
use std::io::Read;
use std::io::Write;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/0", FileType::ZeroFile(2))
.create("first/1", FileType::ZeroFile(1))
.create("second/2", FileType::ZeroFile(3))
.create("second/3", FileType::ZeroFile(3))
.create("second/4", FileType::ZeroFile(4));
let counter = Arc::new(AtomicU64::new(0));
let cache = CacheBuilder::new()
.plain_writer(temp.path("first"), 100)
.plain_reader(temp.path("second"))
.consistency_checker(byte_equality_checker(counter.clone()))
.take()
.build();
// Find a hit in both caches. The checker should be invoked.
{
let mut hit = cache
.get(&TestKey::new("0"))
.expect("must succeed")
.expect("must exist");
assert_eq!(counter.load(Ordering::Relaxed), 1);
let mut contents = Vec::new();
hit.read_to_end(&mut contents).expect("read should succeed");
assert_eq!(contents, "00".as_bytes());
}
// Do the same via `ensure`.
{
counter.store(0, Ordering::Relaxed);
let mut populated = cache
.ensure(&TestKey::new("0"), |dst| {
dst.write_all("00".as_bytes())?;
Ok(())
})
.expect("ensure must succeed");
assert_eq!(counter.load(Ordering::Relaxed), 2);
let mut contents = Vec::new();
populated
.read_to_end(&mut contents)
.expect("read should succeed");
assert_eq!(contents, "00".as_bytes());
}
// Now return `NotFound` from the `populate` callback,
// we should still succeed.
{
counter.store(0, Ordering::Relaxed);
let mut populated = cache
.ensure(&TestKey::new("0"), |_| {
Err(Error::new(ErrorKind::NotFound, "not found"))
})
.expect("ensure must succeed");
assert_eq!(counter.load(Ordering::Relaxed), 1);
let mut contents = Vec::new();
populated
.read_to_end(&mut contents)
.expect("read should succeed");
assert_eq!(contents, "00".as_bytes());
}
counter.store(0, Ordering::Relaxed);
let _ = cache
.get(&TestKey::new("1"))
.expect("must succeed")
.expect("must exist");
// Only found in the writer, there's nothing to check.
assert_eq!(counter.load(Ordering::Relaxed), 0);
// Do the same via `ensure`.
{
let mut populated = cache
.ensure(&TestKey::new("1"), |dst| {
dst.write_all("0".as_bytes())?;
Ok(())
})
.expect("ensure must succeed");
assert_eq!(counter.load(Ordering::Relaxed), 1);
let mut contents = Vec::new();
populated
.read_to_end(&mut contents)
.expect("read should succeed");
assert_eq!(contents, "0".as_bytes());
}
counter.store(0, Ordering::Relaxed);
let _ = cache
.get(&TestKey::new("2"))
.expect("must succeed")
.expect("must exist");
// Only found in the read cache, there's nothing to check.
assert_eq!(counter.load(Ordering::Relaxed), 0);
// Do the same via `ensure`.
{
counter.store(0, Ordering::Relaxed);
let mut populated = cache
.ensure(&TestKey::new("2"), |dst| {
dst.write_all("000".as_bytes())?;
Ok(())
})
.expect("ensure must succeed");
assert_eq!(counter.load(Ordering::Relaxed), 1);
let mut contents = Vec::new();
populated
.read_to_end(&mut contents)
.expect("read should succeed");
assert_eq!(contents, "000".as_bytes());
}
{
counter.store(0, Ordering::Relaxed);
let mut populated = cache
.get_or_update(
&TestKey::new("3"),
|_| CacheHitAction::Accept,
|dst, _| {
dst.write_all("000".as_bytes())?;
Ok(())
},
)
.expect("get_or_update must succeed");
assert_eq!(counter.load(Ordering::Relaxed), 1);
let mut contents = Vec::new();
populated
.read_to_end(&mut contents)
.expect("read should succeed");
assert_eq!(contents, "000".as_bytes());
}
// Again, but now the `populate` callback returns `NotFound`.
{
counter.store(0, Ordering::Relaxed);
let mut populated = cache
.get_or_update(
&TestKey::new("4"),
|_| CacheHitAction::Accept,
|_, _| Err(Error::new(ErrorKind::NotFound, "not found")),
)
.expect("get_or_update must succeed");
assert_eq!(counter.load(Ordering::Relaxed), 0);
let mut contents = Vec::new();
populated
.read_to_end(&mut contents)
.expect("read should succeed");
assert_eq!(contents, "0000".as_bytes());
}
// Make sure we succeed on plain misses.
{
counter.store(0, Ordering::Relaxed);
let mut populated = cache
.get_or_update(
&TestKey::new("no-such-key"),
|_| CacheHitAction::Accept,
|dst, _| {
dst.write_all("fresh data".as_bytes())?;
Ok(())
},
)
.expect("get_or_update must succeed");
assert_eq!(counter.load(Ordering::Relaxed), 0);
let mut contents = Vec::new();
populated
.read_to_end(&mut contents)
.expect("read should succeed");
assert_eq!(contents, "fresh data".as_bytes());
}
}
/// Populate two plain caches and set a consistency checker. We
/// should error on mismatch.
#[test]
fn consistency_checker_failure() {
use std::io::Write;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/0", FileType::ZeroFile(3))
.create("first/1", FileType::ZeroFile(1))
.create("second/2", FileType::ZeroFile(4));
let counter = Arc::new(AtomicU64::new(0));
let cache = CacheBuilder::new()
.plain_writer(temp.path("first"), 100)
.plain_reader(temp.path("second"))
.consistency_checker(byte_equality_checker(counter))
.take()
.build();
// This call should error.
assert!(cache.get(&TestKey::new("0")).is_err());
// The call should also error through `ensure`.
assert!(cache
.ensure(&TestKey::new("0"), |_| {
unreachable!("should detect read-cache mismatch first");
})
.is_err());
// Do the same for the files that are only in one of the two
// caches.
assert!(cache
.ensure(&TestKey::new("1"), |dst| {
dst.write_all("0000".as_bytes())?;
Ok(())
})
.is_err());
assert!(cache
.ensure(&TestKey::new("2"), |dst| {
dst.write_all("0".as_bytes())?;
Ok(())
})
.is_err());
// Same with `get_or_update`.
assert!(cache
.get_or_update(
&TestKey::new("2"),
|_| CacheHitAction::Accept,
|dst, _| {
dst.write_all("0".as_bytes())?;
Ok(())
}
)
.is_err());
}
/// Populate two plain caches and unset the consistency checker. We
/// should not error.
#[test]
fn consistency_checker_silent_failure() {
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/0", FileType::ZeroFile(3))
.create("first/1", FileType::ZeroFile(1))
.create("second/2", FileType::ZeroFile(4));
let counter = Arc::new(AtomicU64::new(0));
let cache = CacheBuilder::new()
.plain_writer(temp.path("first"), 100)
.plain_reader(temp.path("second"))
.consistency_checker(byte_equality_checker(counter.clone()))
.clear_consistency_checker()
.take()
.build();
// This call should not error.
let _ = cache
.get(&TestKey::new("0"))
.expect("must succeed")
.expect("must exist");
// And same for `ensure` calls.
let _ = cache
.ensure(&TestKey::new("0"), |_| {
unreachable!("should not be called");
})
.expect("must succeed");
let _ = cache
.ensure(&TestKey::new("1"), |_| {
unreachable!("should not be called");
})
.expect("must succeed");
let _ = cache
.ensure(&TestKey::new("2"), |_| {
unreachable!("should not be called");
})
.expect("must succeed");
let _ = cache
.get_or_update(
&TestKey::new("2"),
|_| CacheHitAction::Accept,
|_, _| {
unreachable!("should not be called");
},
)
.expect("must succeed");
// There should be no call to the checker function.
assert_eq!(counter.load(Ordering::Relaxed), 0);
}
/// Populate two plain caches. We should read from both.
#[test]
fn two_plain_caches() {
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/1", FileType::ZeroFile(3));
let ro = CacheBuilder::new()
.plain_readers(["first", "second"].iter().map(|p| temp.path(p)))
.take()
.build();
// We should find 0 and 1.
let _ = ro
.get(&TestKey::new("0"))
.expect("must succeed")
.expect("must exist");
let _ = ro
.get(&TestKey::new("1"))
.expect("must succeed")
.expect("must exist");
// But not 2.
assert!(ro.get(&TestKey::new("2")).expect("must succeed").is_none());
}
// Fail to find a file, ensure it, then see that we can get it.
#[test]
fn test_ensure() {
use std::io::{Read, Write};
use test_dir::{DirBuilder, TestDir};
let temp = TestDir::temp();
// Get some coverage for no-auto_sync config.
let cache = CacheBuilder::new()
.writer(temp.path("."), 1, 10)
.auto_sync(false)
.take()
.build();
let key = TestKey::new("foo");
// The file doesn't exist initially.
assert!(matches!(cache.get(&key), Ok(None)));
{
let mut populated = cache
.ensure(&key, |file| file.write_all(b"test"))
.expect("ensure must succeed");
let mut dst = Vec::new();
populated.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"test");
}
// And now get the file again.
{
let mut fetched = cache
.get(&key)
.expect("get must succeed")
.expect("file must be found");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"test");
}
// And make sure a later `ensure` call just grabs the file.
{
let mut populated = cache
.ensure(&key, |_| {
unreachable!("should not be called for an extant file")
})
.expect("ensure must succeed");
let mut dst = Vec::new();
populated.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"test");
}
}
// Use a two-level cache, and make sure `ensure` promotes copies from
// the backup to the primary location.
#[test]
fn test_ensure_promote() {
use std::io::{Read, Write};
use tempfile::NamedTempFile;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("cache", FileType::Dir)
.create("extra_plain", FileType::Dir);
// Populate the plain cache in `extra_plain` with one file.
{
let cache = PlainCache::new(temp.path("extra_plain"), 10);
let tmp = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"initial")
.expect("write must succeed");
cache.put("foo", tmp.path()).expect("put must succeed");
}
let cache = CacheBuilder::new()
.writer(temp.path("cache"), 1, 10)
.plain_reader(temp.path("extra_plain"))
.take()
.build();
let key = TestKey::new("foo");
// The file is found initially.
{
let mut fetched = cache
.get(&key)
.expect("get must succeed")
.expect("file must be found");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"initial");
}
{
let mut populated = cache
.ensure(&key, |_| {
unreachable!("should not be called for an extant file")
})
.expect("ensure must succeed");
let mut dst = Vec::new();
populated.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"initial");
}
// And now get the file again, and make sure it doesn't come from the
// backup location.
{
let new_cache = CacheBuilder::new()
.writer(temp.path("cache"), 1, 10)
.take()
.build();
let mut fetched = new_cache
.get(&key)
.expect("get must succeed")
.expect("file must be found");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"initial");
}
}
// Use a two-level cache, get_or_update with an `Accept` judgement.
// We should leave everything where it is.
#[test]
fn test_get_or_update_accept() {
use std::io::{Read, Write};
use tempfile::NamedTempFile;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("cache", FileType::Dir)
.create("extra_plain", FileType::Dir);
// Populate the plain cache in `extra_plain` with one file.
{
let cache = PlainCache::new(temp.path("extra_plain"), 10);
let tmp = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"initial")
.expect("write must succeed");
cache.put("foo", tmp.path()).expect("put must succeed");
}
let cache = CacheBuilder::new()
// Make it sharded, because why not?
.writer(temp.path("cache"), 2, 10)
.plain_reader(temp.path("extra_plain"))
.take()
.build();
let key = TestKey::new("foo");
let key2 = TestKey::new("bar");
// The file is found initially, in the backup cache.
{
let mut fetched = cache
.get_or_update(
&key,
|hit| {
assert!(matches!(hit, CacheHit::Secondary(_)));
CacheHitAction::Accept
},
|_, _| unreachable!("should not have to fill an extant file"),
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"initial");
}
// Let's try again with a file that does not exist yet.
{
let mut fetched = cache
.get_or_update(
&key2,
|_| unreachable!("should not be called"),
|file, old| {
assert!(old.is_none());
file.write_all(b"updated")
},
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"updated");
}
// The new file is now found.
{
let mut fetched = cache
.get_or_update(
&key2,
|hit| {
assert!(matches!(hit, CacheHit::Primary(_)));
CacheHitAction::Accept
},
|_, _| unreachable!("should not have to fill an extant file"),
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"updated");
}
// And now get the files again, and make sure they don't
// come from the backup location.
{
let new_cache = CacheBuilder::new()
.writer(temp.path("cache"), 2, 10)
.take()
.build();
// The new cache shouldn't have the old key.
assert!(matches!(new_cache.touch(&key), Ok(false)));
// But it should have `key2`.
let mut fetched = new_cache
.get(&key2)
.expect("get must succeed")
.expect("file must be found");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"updated");
}
}
// Use a two-level cache, get_or_update with a `Replace` judgement.
// We should always overwrite everything to the write cache.
#[test]
fn test_get_or_update_replace() {
use std::io::{Read, Write};
use tempfile::NamedTempFile;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("cache", FileType::Dir)
.create("extra_plain", FileType::Dir);
// Populate the plain cache in `extra_plain` with one file.
{
let cache = PlainCache::new(temp.path("extra_plain"), 10);
let tmp = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"initial")
.expect("write must succeed");
cache.put("foo", tmp.path()).expect("put must succeed");
}
let cache = CacheBuilder::new()
// Make it sharded, because why not?
.writer(temp.path("cache"), 2, 10)
.plain_reader(temp.path("extra_plain"))
.take()
.build();
let key = TestKey::new("foo");
{
let mut fetched = cache
.get_or_update(
&key,
|hit| {
assert!(matches!(hit, CacheHit::Secondary(_)));
CacheHitAction::Replace
},
|file, old| {
// Make sure the `old` file is the "initial" file.
let mut prev = old.expect("must have old data");
let mut dst = Vec::new();
prev.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"initial");
file.write_all(b"replace1")
},
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"replace1");
}
// Re-read the file.
{
let mut fetched = cache
.get(&key)
.expect("get must succeed")
.expect("file should be found");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"replace1");
}
// Update it again.
{
let mut fetched = cache
.get_or_update(
&key,
|hit| {
assert!(matches!(hit, CacheHit::Primary(_)));
CacheHitAction::Replace
},
|file, old| {
// Make sure the `old` file is the "initial" file.
let mut prev = old.expect("must have old data");
let mut dst = Vec::new();
prev.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"replace1");
file.write_all(b"replace2")
},
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"replace2");
}
// The new file is now found.
{
let mut fetched = cache
.get_or_update(
&key,
|hit| {
assert!(matches!(hit, CacheHit::Primary(_)));
CacheHitAction::Replace
},
|file, old| {
// Make sure the `old` file is the "replace2" file.
let mut prev = old.expect("must have old data");
let mut dst = Vec::new();
prev.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"replace2");
file.write_all(b"replace3")
},
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"replace3");
}
// And now get the same file again, and make sure it doesn't
// come from the backup location.
{
let new_cache = CacheBuilder::new()
.writer(temp.path("cache"), 2, 10)
.take()
.build();
// But it should have `key2`.
let mut fetched = new_cache
.get(&key)
.expect("get must succeed")
.expect("file must be found");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"replace3");
}
}
// Use a one-level cache, without any write-side cache. We should
// still be able to `ensure` (or `get_or_update`), by calling the
// `populate` function for all misses.
#[test]
fn test_ensure_no_write_side() {
use std::io::{Read, Write};
use tempfile::NamedTempFile;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp().create("extra_plain", FileType::Dir);
// Populate the plain cache in `extra_plain` with one file.
{
let cache = PlainCache::new(temp.path("extra_plain"), 10);
let tmp = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"initial")
.expect("write must succeed");
cache.put("foo", tmp.path()).expect("put must succeed");
}
let cache = CacheBuilder::new()
.plain_reader(temp.path("extra_plain"))
.take()
.build();
let key = TestKey::new("foo");
let key2 = TestKey::new("bar");
// The file is found initially, in the backup cache.
{
let mut fetched = cache
.get_or_update(
&key,
|hit| {
assert!(matches!(hit, CacheHit::Secondary(_)));
CacheHitAction::Accept
},
|_, _| unreachable!("should not have to fill an extant file"),
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"initial");
}
// Let's try again with a file that does not exist yet.
{
let mut fetched = cache
.get_or_update(
&key2,
|_| unreachable!("should not be called"),
|file, old| {
assert!(old.is_none());
file.write_all(b"updated")
},
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"updated");
}
// Let's try again with the same file file.
{
let mut fetched = cache
.get_or_update(
&key2,
|_| unreachable!("should not be called"),
|file, old| {
assert!(old.is_none());
file.write_all(b"updated2")
},
)
.expect("get_or_update must succeed");
let mut dst = Vec::new();
fetched.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"updated2");
}
}
/// Use a byte equality checker with two different cache files for
/// the same key. We should find an error.
#[test]
fn test_byte_equality_checker() {
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/0", FileType::ZeroFile(3));
let cache = CacheBuilder::new()
.plain_readers(["first", "second"].iter().map(|p| temp.path(p)))
.byte_equality_checker()
.take()
.build();
assert!(cache.get(&TestKey::new("0")).is_err());
}
/// Use a panicking byte equality checker with two different cache
/// files for the same key. We should find an error.
#[test]
#[should_panic(expected = "file contents do not match")]
fn test_panicking_byte_equality_checker() {
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/0", FileType::ZeroFile(3));
let cache = CacheBuilder::new()
.plain_readers(["first", "second"].iter().map(|p| temp.path(p)))
.panicking_byte_equality_checker()
.take()
.build();
// We should fail before returning Err.
assert!(cache.get(&TestKey::new("0")).is_ok());
}
// Smoke test a wrapped plain cache.
#[test]
fn smoke_test_plain() {
use std::io::{Read, Write};
use tempfile::NamedTempFile;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("cache", FileType::Dir)
.create("extra", FileType::Dir);
// Populate the plain cache in `extra` with two files, "b" and "c".
{
let cache = PlainCache::new(temp.path("extra"), 10);
let tmp = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"extra")
.expect("write must succeed");
cache.put("b", tmp.path()).expect("put must succeed");
let tmp2 = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp2.as_file()
.write_all(b"extra2")
.expect("write must succeed");
cache.put("c", tmp2.path()).expect("put must succeed");
}
let cache = CacheBuilder::new()
.writer(temp.path("cache"), 1, 10)
.reader(temp.path("extra"), 1)
.take()
.build();
// There shouldn't be anything for "a"
assert!(matches!(cache.get(&TestKey::new("a")), Ok(None)));
assert!(matches!(cache.touch(&TestKey::new("a")), Ok(false)));
// We should be able to touch "b"
assert!(matches!(cache.touch(&TestKey::new("b")), Ok(true)));
// And its contents should match that of the "extra" cache dir.
{
let mut b_file = cache
.get(&TestKey::new("b"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
b_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"extra");
}
// Now populate "a" and "b" in the cache.
{
let tmp = NamedTempFile::new_in(temp.path(".")).expect("new temp file must succeed");
tmp.as_file()
.write_all(b"write")
.expect("write must succeed");
cache
.put(&TestKey::new("a"), tmp.path())
.expect("put must succeed");
}
{
let tmp = NamedTempFile::new_in(temp.path(".")).expect("new temp file must succeed");
tmp.as_file()
.write_all(b"write2")
.expect("write must succeed");
// Exercise put_temp_file as well.
cache
.put_temp_file(&TestKey::new("b"), tmp)
.expect("put must succeed");
}
// And overwrite "a"
{
let tmp = NamedTempFile::new_in(temp.path(".")).expect("new temp file must succeed");
tmp.as_file()
.write_all(b"write3")
.expect("write must succeed");
cache
.set(&TestKey::new("a"), tmp.path())
.expect("set must succeed");
}
// We should find:
// a => write3
// b => write2
// c => extra2
// So we should be able to touch everything.
assert!(matches!(cache.touch(&TestKey::new("a")), Ok(true)));
assert!(matches!(cache.touch(&TestKey::new("b")), Ok(true)));
assert!(matches!(cache.touch(&TestKey::new("c")), Ok(true)));
// And read the expected contents.
{
let mut a_file = cache
.get(&TestKey::new("a"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
a_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"write3");
}
{
let mut b_file = cache
.get(&TestKey::new("b"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
b_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"write2");
}
{
let mut c_file = cache
.get(&TestKey::new("c"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
c_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"extra2");
}
}
// Smoke test a wrapped sharded cache.
#[test]
fn smoke_test_sharded() {
use std::io::{Read, Write};
use tempfile::NamedTempFile;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("cache", FileType::Dir)
.create("extra_plain", FileType::Dir)
.create("extra_sharded", FileType::Dir);
// Populate the plain cache in `extra_plain` with one file, "b".
{
let cache = PlainCache::new(temp.path("extra_plain"), 10);
let tmp = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"extra_plain")
.expect("write must succeed");
cache.put("b", tmp.path()).expect("put must succeed");
}
// And now add "c" in the sharded `extra_sharded` cache.
{
let cache = ShardedCache::new(temp.path("extra_sharded"), 10, 10);
let tmp = NamedTempFile::new_in(cache.temp_dir(None).expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"extra_sharded")
.expect("write must succeed");
cache
.put((&TestKey::new("c")).into(), tmp.path())
.expect("put must succeed");
}
let cache = CacheBuilder::new()
.plain_writer(temp.path("cache"), 10)
// Override the writer with a sharded cache
.writer(temp.path("cache"), 10, 10)
.plain_reader(temp.path("extra_plain"))
.sharded_reader(temp.path("extra_sharded"), 10)
.take()
.build();
// There shouldn't be anything for "a"
assert!(matches!(cache.get(&TestKey::new("a")), Ok(None)));
assert!(matches!(cache.touch(&TestKey::new("a")), Ok(false)));
// We should be able to touch "b"
assert!(matches!(cache.touch(&TestKey::new("b")), Ok(true)));
// And its contents should match that of the "extra" cache dir.
{
let mut b_file = cache
.get(&TestKey::new("b"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
b_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"extra_plain");
}
// Similarly for "c"
{
let mut c_file = cache
.get(&TestKey::new("c"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
c_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"extra_sharded");
}
// Now populate "a" and "b" in the cache.
{
let tmp = NamedTempFile::new_in(temp.path(".")).expect("new temp file must succeed");
tmp.as_file()
.write_all(b"write")
.expect("write must succeed");
cache
.set(&TestKey::new("a"), tmp.path())
.expect("set must succeed");
}
{
let tmp = NamedTempFile::new_in(temp.path(".")).expect("new temp file must succeed");
tmp.as_file()
.write_all(b"write2")
.expect("write must succeed");
// Exercise set_temp_file.
cache
.set_temp_file(&TestKey::new("b"), tmp)
.expect("set must succeed");
}
// And fail to update "a" with a put.
{
let tmp = NamedTempFile::new_in(temp.path(".")).expect("new temp file must succeed");
tmp.as_file()
.write_all(b"write3")
.expect("write must succeed");
cache
.put(&TestKey::new("a"), tmp.path())
.expect("put must succeed");
}
// We should find:
// a => write
// b => write2
// c => extra_sharded
// So we should be able to touch everything.
assert!(matches!(cache.touch(&TestKey::new("a")), Ok(true)));
assert!(matches!(cache.touch(&TestKey::new("b")), Ok(true)));
assert!(matches!(cache.touch(&TestKey::new("c")), Ok(true)));
// And read the expected contents.
{
let mut a_file = cache
.get(&TestKey::new("a"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
a_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"write");
}
{
let mut b_file = cache
.get(&TestKey::new("b"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
b_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"write2");
}
{
let mut c_file = cache
.get(&TestKey::new("c"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
c_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"extra_sharded");
}
}
}