Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions autonerves/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import yaml

from autonerves import parse_cache
from autonerves.directory_config import (
RecursiveConfig,
PriorConfigWrapper,
Expand Down Expand Up @@ -168,8 +169,7 @@ def logging_config(self) -> Optional[Dict]:
path = config.path
try:
if LOGGING_CONFIG_FILE in os.listdir(config.path):
with open(path / LOGGING_CONFIG_FILE) as f:
return yaml.safe_load(f)
return parse_cache.load_yaml(path / LOGGING_CONFIG_FILE)
except FileNotFoundError:
logger.debug(f"No configuration found at path {config.path}")
return None
Expand Down
5 changes: 2 additions & 3 deletions autonerves/directory_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import yaml

from autonerves import exc
from autonerves import exc, parse_cache


class AbstractConfig(ABC):
Expand Down Expand Up @@ -70,8 +70,7 @@ def items(self):

class YAMLConfig(AbstractConfig):
def __init__(self, path):
with open(path) as f:
self._dict = yaml.safe_load(f)
self._dict = parse_cache.load_yaml(path)

def _getitem(self, item):
value = self._dict[item]
Expand Down
12 changes: 6 additions & 6 deletions autonerves/json_prior/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import yaml

from autonerves import parse_cache
from autonerves.directory_config import family

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -149,15 +150,14 @@ def from_directory(cls, directory: str) -> "JSONPriorConfig":

config_path = Path(directory)

for suffix, parser in [
("json", json.load),
("yaml", yaml.safe_load),
("yml", yaml.safe_load),
for suffix, load in [
("json", parse_cache.load_json),
("yaml", parse_cache.load_yaml),
("yml", parse_cache.load_yaml),
]:
for file in config_path.rglob(f"*.{suffix}"):
parts = file.relative_to(config_path).with_suffix("").parts
with open(file) as f:
config_dict[".".join(parts)] = parser(f)
config_dict[".".join(parts)] = load(file)

return JSONPriorConfig(config_dict, directory=directory)

Expand Down
67 changes: 67 additions & 0 deletions autonerves/parse_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
Process-level cache of parsed configuration files.

``Config.push`` / ``Config.register`` invalidate the lazily-built config
dictionary and prior configuration, so before this cache every library import
re-read every YAML / JSON config file from disk: hundreds of parses per script
run for a few dozen distinct files.

Each file is parsed at most once per process while it is unchanged on disk. The
cache key is the absolute path and the parser kind; an entry is reused only
while the file's ``st_mtime_ns`` and ``st_size`` match, so editing a file
re-parses it exactly as before.

Callers get a deep copy of the cached object, so mutating a loaded config can
never leak into a later load — the result is identical to a fresh parse.
"""

import copy
import json
import os

import yaml

_cache = {}


def clear():
"""Drop every cached parse."""
_cache.clear()


def _parse_yaml(f):
# Looked up at call time so a hook on ``yaml.safe_load`` sees every real parse.
return yaml.safe_load(f)


def _parse_json(f):
return json.load(f)


_PARSERS = {"yaml": _parse_yaml, "json": _parse_json}


def _load(path, kind):
path = os.path.abspath(os.fspath(path))
stat = os.stat(path)
signature = (stat.st_mtime_ns, stat.st_size)
key = (path, kind)

entry = _cache.get(key)
if entry is None or entry[0] != signature:
with open(path) as f:
parsed = _PARSERS[kind](f)
entry = (signature, parsed)
_cache[key] = entry

return copy.deepcopy(entry[1])


def load_yaml(path):
"""The result of ``yaml.safe_load`` on the file at ``path``, parsed once."""
return _load(path, "yaml")


def load_json(path):
"""The result of ``json.load`` on the file at ``path``, parsed once."""
return _load(path, "json")
147 changes: 147 additions & 0 deletions test_autonerves/test_parse_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""
The config parse cache (``autonerves.parse_cache``) must be invisible: every
config object built through it compares equal to one built from fresh parses,
while each file is parsed at most once per process.
"""

import collections
import json
import os
from pathlib import Path

import pytest
import yaml

from autonerves import conf, parse_cache
from autonerves.json_prior.config import JSONPriorConfig

PACKAGE_ROOT = Path(__file__).parent.parent
CONFIG_SUFFIXES = (".yaml", ".yml", ".json", ".ini")


def _packaged_config_directories():
"""Every directory in the repo that ships config files (test fixtures included)."""
candidates = sorted((PACKAGE_ROOT / "test_autonerves" / "files").iterdir())
candidates += sorted(p for p in (PACKAGE_ROOT / "autonerves").iterdir())
return [
directory
for directory in candidates
if directory.is_dir()
and any(
f.endswith(CONFIG_SUFFIXES)
for _, _, files in os.walk(directory)
for f in files
)
]


PACKAGED = _packaged_config_directories()


def _plain(value):
if isinstance(value, conf.DictWrapper):
return {key: _plain(item) for key, item in value.items()}
return value


def _snapshot(directory):
"""Everything a Config over ``directory`` parses, as plain data."""
config = conf.Config(directory)
priors = JSONPriorConfig.from_directory(Path(directory) / "priors")
return {
"dict": _plain(config.dict),
"priors": priors.obj,
"logging": config.logging_config,
}


def _fresh_load(path, kind):
with open(path) as f:
return yaml.safe_load(f) if kind == "yaml" else json.load(f)


@pytest.fixture(autouse=True)
def _clear_cache():
parse_cache.clear()
yield
parse_cache.clear()


@pytest.fixture(name="parse_counter")
def make_parse_counter(monkeypatch):
counts = collections.Counter()
original = yaml.safe_load

def counting_safe_load(stream, *args, **kwargs):
counts[getattr(stream, "name", None)] += 1
return original(stream, *args, **kwargs)

monkeypatch.setattr(yaml, "safe_load", counting_safe_load)
return counts


def test_packaged_directories_found():
names = {d.name for d in PACKAGED}
assert {"config", "default", "config_flip"} <= names


@pytest.mark.parametrize("directory", PACKAGED, ids=lambda d: d.name)
def test_cached_parse_deep_equals_fresh_parse(directory, monkeypatch):
with monkeypatch.context() as m:
m.setattr(parse_cache, "_load", _fresh_load)
reference = _snapshot(directory)

cold = _snapshot(directory)
warm = _snapshot(directory)

assert cold == reference
assert warm == reference


def test_each_file_parsed_once_across_pushes(files_directory, parse_counter):
config = conf.Config(files_directory / "default")
for directory in ("config_flip", "config", "default", "config"):
config.push(files_directory / directory)
config.dict
config.prior_config.prior_configs[0].path_value_map

assert parse_counter
assert max(parse_counter.values()) == 1


def test_returned_objects_are_independent(tmp_path):
path = tmp_path / "general.yaml"
path.write_text("section:\n key: [1, 2]\n")

first = parse_cache.load_yaml(path)
first["section"]["key"].append(3)

assert parse_cache.load_yaml(path) == {"section": {"key": [1, 2]}}


def test_changed_file_is_reparsed(tmp_path, parse_counter):
path = tmp_path / "general.yaml"
path.write_text("a: 1\n")
assert parse_cache.load_yaml(path) == {"a": 1}

path.write_text("a: 22\n")
stat = path.stat()
os.utime(path, ns=(stat.st_atime_ns, stat.st_mtime_ns + 10**9))

assert parse_cache.load_yaml(path) == {"a": 22}
assert sum(parse_counter.values()) == 2


def test_missing_file_raises_and_is_not_cached(tmp_path):
path = tmp_path / "missing.yaml"
with pytest.raises(FileNotFoundError):
parse_cache.load_yaml(path)
path.write_text("a: 1\n")
assert parse_cache.load_yaml(path) == {"a": 1}


def test_json_and_yaml_kinds_are_cached_separately(tmp_path):
path = tmp_path / "both.json"
path.write_text('{"a": 1}')
assert parse_cache.load_json(path) == {"a": 1}
assert parse_cache.load_yaml(path) == {"a": 1}
Loading