askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_object_sources_cache.py · 14.0 KB · 382 lines
| 1 | """iter_object_sources keeps its listing only while the directories prove it current. |
| 2 | |
| 3 | The listing is a recursive glob (about 16 ms on a 57-package install) that |
| 4 | ran on every page routed through the site_routes table. It is now re-used |
| 5 | while every directory it walked still has the same stat. The server is not |
| 6 | the only writer of object files (other workers, the daemon, the package |
| 7 | installer, an operator's editor), so nothing here relies on being told about |
| 8 | a write: every test changes the disk directly and asks again. |
| 9 | |
| 10 | `_list_object_sources` is the uncached listing, unchanged from before the |
| 11 | cache existed, so it is the oracle throughout. |
| 12 | """ |
| 13 | |
| 14 | import os |
| 15 | import random |
| 16 | import shutil |
| 17 | import threading |
| 18 | import time |
| 19 | from pathlib import Path |
| 20 | |
| 21 | import pytest |
| 22 | |
| 23 | import object_namespace |
| 24 | from object_namespace import iter_object_sources, resolve_object_id |
| 25 | |
| 26 | SOURCE = "def GET(request):\n return {}\n" |
| 27 | |
| 28 | |
| 29 | def write(path: Path, text: str = SOURCE) -> Path: |
| 30 | path.parent.mkdir(parents=True, exist_ok=True) |
| 31 | path.write_text(text) |
| 32 | return path |
| 33 | |
| 34 | |
| 35 | def settle() -> None: |
| 36 | """Wait until a listing taken now may be kept (see _SOURCES_CACHE_RACY_NS).""" |
| 37 | time.sleep(object_namespace._SOURCES_CACHE_RACY_NS / 1e9 + 0.03) |
| 38 | |
| 39 | |
| 40 | def ids(root: Path) -> list[str]: |
| 41 | return [source.object_id for source in iter_object_sources([root])] |
| 42 | |
| 43 | |
| 44 | def uncached(root: Path) -> list: |
| 45 | return object_namespace._list_object_sources([root], object_namespace.get_override_root()) |
| 46 | |
| 47 | |
| 48 | @pytest.fixture |
| 49 | def listings(monkeypatch): |
| 50 | """Counts real directory listings, so a test can tell a re-used listing |
| 51 | from a fresh one.""" |
| 52 | calls = [] |
| 53 | real = object_namespace._list_object_sources |
| 54 | |
| 55 | def counting(roots, override_root): |
| 56 | calls.append(1) |
| 57 | return real(roots, override_root) |
| 58 | |
| 59 | monkeypatch.setattr(object_namespace, "_list_object_sources", counting) |
| 60 | return calls |
| 61 | |
| 62 | |
| 63 | @pytest.fixture |
| 64 | def root(tmp_path): |
| 65 | root = tmp_path / "objects" |
| 66 | write(root / "site" / "home.py") |
| 67 | write(root / "site" / "about.py") |
| 68 | write(root / "action" / "nav_entries.py") |
| 69 | write(root / "deep" / "er" / "thing.py") |
| 70 | write(root / "users" / "42" / "deals.py") |
| 71 | write(root / "rootlevel.py") |
| 72 | return root |
| 73 | |
| 74 | |
| 75 | def test_a_settled_tree_is_listed_once_and_every_caller_gets_its_own_list(root, listings): |
| 76 | settle() |
| 77 | first = iter_object_sources([root]) |
| 78 | assert len(listings) == 1 |
| 79 | second = iter_object_sources([root]) |
| 80 | third = iter_object_sources([root]) |
| 81 | assert len(listings) == 1, "an unchanged tree must not be listed again" |
| 82 | assert first == second == third |
| 83 | assert first is not second and second is not third |
| 84 | assert [s.object_id for s in first] == [ |
| 85 | "action_nav_entries", "deep_er_thing", "rootlevel", "site_about", "site_home", "u_42_deals", |
| 86 | ] |
| 87 | # The cache must not hand out its own list: a caller that sorts or |
| 88 | # filters in place would otherwise change what the next request sees. |
| 89 | expected = list(first) |
| 90 | first.clear() # the list the listing call itself returned |
| 91 | second.clear() |
| 92 | third.reverse() |
| 93 | assert iter_object_sources([root]) == expected |
| 94 | assert len(listings) == 1 |
| 95 | |
| 96 | |
| 97 | def test_the_cached_listing_is_what_an_uncached_listing_returns(root): |
| 98 | settle() |
| 99 | assert iter_object_sources([root]) == uncached(root) |
| 100 | assert iter_object_sources([root]) == uncached(root) |
| 101 | |
| 102 | |
| 103 | def test_an_object_file_created_is_in_the_next_listing(root, listings): |
| 104 | """Installing a package, or an operator dropping a file in, with no |
| 105 | hook into this process.""" |
| 106 | settle() |
| 107 | assert "site_new" not in ids(root) |
| 108 | write(root / "site" / "new.py") |
| 109 | assert "site_new" in ids(root) |
| 110 | assert iter_object_sources([root]) == uncached(root) |
| 111 | |
| 112 | |
| 113 | def test_an_object_file_deleted_is_gone_from_the_next_listing(root): |
| 114 | settle() |
| 115 | assert "site_about" in ids(root) |
| 116 | (root / "site" / "about.py").unlink() |
| 117 | assert "site_about" not in ids(root) |
| 118 | assert resolve_object_id("site_about", [root]) is None |
| 119 | |
| 120 | |
| 121 | def test_an_object_file_renamed_is_seen_under_its_new_name(root): |
| 122 | settle() |
| 123 | assert "site_about" in ids(root) |
| 124 | (root / "site" / "about.py").rename(root / "site" / "contact.py") |
| 125 | listed = ids(root) |
| 126 | assert "site_about" not in listed and "site_contact" in listed |
| 127 | |
| 128 | |
| 129 | def test_a_file_in_a_new_directory_is_in_the_next_listing(root): |
| 130 | """The new directory was not walked when the listing was taken; its |
| 131 | parent's stat is what gives it away.""" |
| 132 | settle() |
| 133 | ids(root) |
| 134 | write(root / "webhook" / "stripe.py") |
| 135 | assert "webhook_stripe" in ids(root) |
| 136 | settle() |
| 137 | ids(root) |
| 138 | write(root / "deep" / "er" / "est" / "leaf.py") |
| 139 | assert "deep_er_est_leaf" in ids(root) |
| 140 | settle() |
| 141 | ids(root) |
| 142 | write(root / "users" / "7" / "ledger.py") |
| 143 | assert "u_7_ledger" in ids(root) |
| 144 | |
| 145 | |
| 146 | def test_a_file_created_deep_in_an_existing_directory_is_in_the_next_listing(root): |
| 147 | settle() |
| 148 | ids(root) |
| 149 | write(root / "deep" / "er" / "other.py") |
| 150 | assert "deep_er_other" in ids(root) |
| 151 | |
| 152 | |
| 153 | def test_a_removed_directory_takes_its_objects_out_of_the_next_listing(root): |
| 154 | settle() |
| 155 | assert "deep_er_thing" in ids(root) |
| 156 | shutil.rmtree(root / "deep") |
| 157 | assert "deep_er_thing" not in ids(root) |
| 158 | assert iter_object_sources([root]) == uncached(root) |
| 159 | |
| 160 | |
| 161 | def test_a_deep_object_resolves_and_stops_resolving_with_its_file(root): |
| 162 | """resolve_object_id falls back to the listing for an id whose path is |
| 163 | not the conventional one. A stale listing there serves a page for an |
| 164 | object that was removed, or 404s one that was just installed.""" |
| 165 | settle() |
| 166 | assert resolve_object_id("deep_er_thing", [root]) == root / "deep" / "er" / "thing.py" |
| 167 | assert resolve_object_id("deep_er_fresh", [root]) is None |
| 168 | write(root / "deep" / "er" / "fresh.py") |
| 169 | assert resolve_object_id("deep_er_fresh", [root]) == root / "deep" / "er" / "fresh.py" |
| 170 | (root / "deep" / "er" / "thing.py").unlink() |
| 171 | assert resolve_object_id("deep_er_thing", [root]) is None |
| 172 | |
| 173 | |
| 174 | def test_two_changes_in_the_same_instant_are_both_seen(root, listings): |
| 175 | """The racy window: a listing taken right after a change is not kept, |
| 176 | because a second change inside the filesystem's timestamp granularity |
| 177 | would leave the directory's stat exactly as it was.""" |
| 178 | settle() |
| 179 | ids(root) |
| 180 | write(root / "site" / "one.py") |
| 181 | before = len(listings) |
| 182 | assert "site_one" in ids(root) |
| 183 | assert "site_one" in ids(root) |
| 184 | assert len(listings) == before + 2, "a listing taken inside the racy window must not be re-used" |
| 185 | write(root / "site" / "two.py") |
| 186 | listed = ids(root) |
| 187 | assert "site_two" in listed |
| 188 | (root / "site" / "one.py").unlink() |
| 189 | assert "site_one" not in ids(root) |
| 190 | assert len(listings) == before + 4 |
| 191 | settle() |
| 192 | ids(root) |
| 193 | again = len(listings) |
| 194 | ids(root) |
| 195 | assert len(listings) == again, "once the tree has settled the listing is kept again" |
| 196 | |
| 197 | |
| 198 | def test_a_tree_holding_a_symlink_is_never_cached(root, listings, tmp_path): |
| 199 | """What a link resolves to is decided outside the directories walked, |
| 200 | so no stat of them can vouch for the listing.""" |
| 201 | outside = write(tmp_path / "elsewhere" / "linked.py") |
| 202 | os.symlink(outside, root / "site" / "linked.py") |
| 203 | settle() |
| 204 | for _ in range(3): |
| 205 | assert iter_object_sources([root]) == uncached(root) |
| 206 | assert len(listings) == 6 # 3 here + 3 from the oracle: none re-used |
| 207 | |
| 208 | |
| 209 | def test_a_root_swapped_for_another_directory_is_listed_afresh(root, tmp_path): |
| 210 | settle() |
| 211 | assert "site_home" in ids(root) |
| 212 | other = tmp_path / "other" |
| 213 | write(other / "billing" / "run.py") |
| 214 | settle() |
| 215 | root.rename(tmp_path / "old-objects") |
| 216 | other.rename(root) |
| 217 | assert ids(root) == ["billing_run"] |
| 218 | |
| 219 | |
| 220 | def test_a_root_swapped_for_a_directory_with_the_same_times_is_told_apart_by_inode(tmp_path, monkeypatch): |
| 221 | """On a filesystem with coarse timestamps two directories can carry the |
| 222 | same mtime and ctime. Simulated here by reporting fixed times for every |
| 223 | directory, which leaves inode and device as the only difference.""" |
| 224 | first = tmp_path / "first" |
| 225 | second = tmp_path / "second" |
| 226 | write(first / "site" / "in_first.py") |
| 227 | write(second / "site" / "in_second.py") |
| 228 | root = tmp_path / "objects" |
| 229 | |
| 230 | class FixedTimes: |
| 231 | def __getattr__(self, name): |
| 232 | return getattr(os, name) |
| 233 | |
| 234 | def stat(self, path, **kwargs): |
| 235 | real = os.stat(path, **kwargs) |
| 236 | |
| 237 | class Info: |
| 238 | st_mode, st_ino, st_dev = real.st_mode, real.st_ino, real.st_dev |
| 239 | st_mtime_ns = st_ctime_ns = 1_000_000_000 |
| 240 | |
| 241 | return Info |
| 242 | |
| 243 | monkeypatch.setattr(object_namespace, "os", FixedTimes()) |
| 244 | first.rename(root) |
| 245 | assert ids(root) == ["site_in_first"] |
| 246 | assert ids(root) == ["site_in_first"] |
| 247 | root.rename(first) |
| 248 | second.rename(root) |
| 249 | assert ids(root) == ["site_in_second"] |
| 250 | |
| 251 | |
| 252 | def test_a_missing_root_lists_nothing_until_it_exists(tmp_path): |
| 253 | root = tmp_path / "objects" |
| 254 | assert ids(root) == [] |
| 255 | settle() |
| 256 | assert ids(root) == [] |
| 257 | write(root / "site" / "home.py") |
| 258 | assert ids(root) == ["site_home"] |
| 259 | shutil.rmtree(root) |
| 260 | assert ids(root) == [] |
| 261 | |
| 262 | |
| 263 | def test_a_relative_root_follows_the_working_directory(tmp_path, monkeypatch): |
| 264 | """Roots default to the relative path "objects". Two directories of |
| 265 | that name must never share a listing.""" |
| 266 | write(tmp_path / "a" / "objects" / "site" / "in_a.py") |
| 267 | write(tmp_path / "b" / "objects" / "site" / "in_b.py") |
| 268 | settle() |
| 269 | monkeypatch.chdir(tmp_path / "a") |
| 270 | assert [s.object_id for s in iter_object_sources([Path("objects")])] == ["site_in_a"] |
| 271 | assert [s.object_id for s in iter_object_sources([Path("objects")])] == ["site_in_a"] |
| 272 | monkeypatch.chdir(tmp_path / "b") |
| 273 | assert [s.object_id for s in iter_object_sources([Path("objects")])] == ["site_in_b"] |
| 274 | |
| 275 | |
| 276 | def test_the_override_root_setting_is_part_of_what_is_cached(root, tmp_path, monkeypatch): |
| 277 | """`kind` depends on DBBASIC_OVERRIDES_DIR, and a handler under the |
| 278 | override root never fires (AGENTS.md), so a listing taken under one |
| 279 | setting must not answer for another.""" |
| 280 | overrides = tmp_path / "overrides" |
| 281 | write(overrides / "site" / "home.py") |
| 282 | settle() |
| 283 | monkeypatch.delenv(object_namespace.OVERRIDES_DIR_ENV, raising=False) |
| 284 | assert {s.kind for s in iter_object_sources([overrides])} == {"system"} |
| 285 | monkeypatch.setenv(object_namespace.OVERRIDES_DIR_ENV, str(overrides)) |
| 286 | assert {s.kind for s in iter_object_sources([overrides])} == {"override"} |
| 287 | assert [s.kind for s in iter_object_sources()][0] == "override" |
| 288 | monkeypatch.delenv(object_namespace.OVERRIDES_DIR_ENV) |
| 289 | assert {s.kind for s in iter_object_sources([overrides])} == {"system"} |
| 290 | |
| 291 | |
| 292 | def test_a_directory_whose_mtime_is_set_back_after_a_change_is_still_noticed(root): |
| 293 | """rsync -a and tar restore directory mtimes. ctime cannot be set, so |
| 294 | it is in the signature.""" |
| 295 | settle() |
| 296 | ids(root) |
| 297 | before = os.stat(root / "site") |
| 298 | write(root / "site" / "restored.py") |
| 299 | os.utime(root / "site", ns=(before.st_atime_ns, before.st_mtime_ns)) |
| 300 | assert os.stat(root / "site").st_mtime_ns == before.st_mtime_ns |
| 301 | assert "site_restored" in ids(root) |
| 302 | |
| 303 | |
| 304 | @pytest.mark.skipif(os.geteuid() == 0, reason="root reads any directory") |
| 305 | def test_a_directory_made_unreadable_drops_out_like_an_uncached_listing(root): |
| 306 | settle() |
| 307 | assert "deep_er_thing" in ids(root) |
| 308 | os.chmod(root / "deep" / "er", 0) |
| 309 | try: |
| 310 | assert iter_object_sources([root]) == uncached(root) |
| 311 | finally: |
| 312 | os.chmod(root / "deep" / "er", 0o755) |
| 313 | assert "deep_er_thing" in ids(root) |
| 314 | |
| 315 | |
| 316 | def test_a_random_run_of_changes_never_disagrees_with_an_uncached_listing(tmp_path): |
| 317 | """Create, delete, rename, add and remove directories, sometimes inside |
| 318 | the racy window and sometimes after the tree has settled, and compare |
| 319 | with the uncached listing after every step.""" |
| 320 | rng = random.Random(20261128) |
| 321 | root = tmp_path / "objects" |
| 322 | write(root / "site" / "home.py") |
| 323 | dirs = ["site", "action", "deep/er", "users/3", "hook", "webhook/in"] |
| 324 | names = ["a", "b", "c", "d"] |
| 325 | for step in range(120): |
| 326 | directory = root / rng.choice(dirs) |
| 327 | target = directory / f"{rng.choice(names)}.py" |
| 328 | move = rng.random() |
| 329 | if move < 0.45: |
| 330 | write(target) |
| 331 | elif move < 0.70: |
| 332 | target.unlink(missing_ok=True) |
| 333 | elif move < 0.82 and target.exists(): |
| 334 | target.rename(directory / f"{rng.choice(names)}.py") |
| 335 | elif move < 0.90: |
| 336 | shutil.rmtree(directory, ignore_errors=True) |
| 337 | if rng.random() < 0.12: |
| 338 | settle() |
| 339 | assert iter_object_sources([root]) == uncached(root), f"step {step}" |
| 340 | if rng.random() < 0.5: |
| 341 | assert iter_object_sources([root]) == uncached(root), f"step {step} (second look)" |
| 342 | |
| 343 | |
| 344 | def test_listing_from_several_threads_while_files_come_and_go(root): |
| 345 | """Threaded workers share the cache. No listing may raise, name a file |
| 346 | that never existed, or miss one that was there the whole time; and the |
| 347 | last word must be the truth.""" |
| 348 | stop = threading.Event() |
| 349 | problems: list[str] = [] |
| 350 | stable = {"action_nav_entries", "deep_er_thing", "rootlevel", "site_about", "site_home", "u_42_deals"} |
| 351 | churn = {f"hook_t{n}" for n in range(8)} |
| 352 | |
| 353 | def reader() -> None: |
| 354 | while not stop.is_set(): |
| 355 | try: |
| 356 | seen = {source.object_id for source in iter_object_sources([root])} |
| 357 | except Exception as exc: # noqa: BLE001 |
| 358 | problems.append(repr(exc)) |
| 359 | return |
| 360 | if not stable <= seen or not seen <= stable | churn: |
| 361 | problems.append(f"impossible listing: {sorted(seen)}") |
| 362 | return |
| 363 | |
| 364 | def writer() -> None: |
| 365 | for round_ in range(40): |
| 366 | name = f"t{round_ % 8}" |
| 367 | write(root / "hook" / f"{name}.py") |
| 368 | if round_ % 3 == 0: |
| 369 | time.sleep(0.07) |
| 370 | (root / "hook" / f"{name}.py").unlink() |
| 371 | |
| 372 | threads = [threading.Thread(target=reader) for _ in range(4)] |
| 373 | for thread in threads: |
| 374 | thread.start() |
| 375 | writer() |
| 376 | stop.set() |
| 377 | for thread in threads: |
| 378 | thread.join() |
| 379 | assert problems == [] |
| 380 | assert {s.object_id for s in iter_object_sources([root])} == stable |
| 381 | settle() |
| 382 | assert {s.object_id for s in iter_object_sources([root])} == stable |