diff --git a/docs/design/01-storage.md b/docs/design/01-storage.md index f7a0cb98..6070602a 100644 --- a/docs/design/01-storage.md +++ b/docs/design/01-storage.md @@ -3019,11 +3019,21 @@ Conclusions: P09). ST-22 (#98) added the line to `.env.example` (`normal` or `full`); since ST-21 and ST-22 the writers of matches, schedules and season lists honour it, because they write through the Store. Since P30 (#186) it is the setting `storage.durability` (`SOFASCORE_STORAGE__DURABILITY`; `STORE_DURABILITY` is no - longer read and only gives a `legacy_name` warning). `sofascore_scraper/store/files.py` reads it, and - `storage.open_reconcile_seconds`, from the active settings of the loader through `sys.modules` - (`_storage_settings`, `:54-66` at `216c2f9`), because the Store may not import the configuration; a process - without a loader (a tool, a test) uses the defaults. The plan's wish that the Store gets them from its - caller is open: no caller of the Store has the settings (`03-implementation-plan.md` section 19). + longer read and only gives a `legacy_name` warning). Until 2026-11-21 `sofascore_scraper/store/files.py` + read it, and `storage.open_reconcile_seconds`, from the active settings of the loader through `sys.modules` + (`_storage_settings`, `:54-66` at `216c2f9`), because the Store may not import the configuration. Since + then the Store gets them from its caller: `sofascore_scraper.store.use_settings(source)` takes a function + that returns the `[storage]` section (`data_dir`, `durability`, `open_reconcile_seconds`), and the settings + loader passes its own (`loader._store_settings`, the active settings' `storage`) when it is imported, so + every process that has settings has given them to the Store before its first write. The Store calls the + function on every read: a changed environment variable or a reload of `sofascore.toml` or `overrides.json` + applies to the next write, as before (the Settings page does not edit `storage.durability` and marks it + as needing a restart). A process that never imports the loader (a tool, a test) and a function that + raises use the defaults: no `fsync`, `data`, 60 seconds. The `durable=` argument of `write_bytes` and + `publish_dir` still overrides the setting per call (a restore writes the certificates and the settings + file with `fsync`). `tests/test_layers.py` checks that no Store module looks into `sys.modules`. Importing + the configuration now loads the Store's root and `files` (with `errors` and `layout`; no SQLite), which the + CLI goldens of `ssc doctor` list. - Windows: `os.replace` fails while another process has the target open. Store readers read a file in one call and close it; the writer retries a failed replace up to 10 times with 20 ms pauses, then raises a non-fatal `StoreError`. That holds for the Store-layer functions (`write_bytes`, `replace`, `publish_dir`, @@ -5283,7 +5293,8 @@ Corrections after the 3.0.0 release and the first 3.1 work (2026-10-09, the tent `storage.durability` and `storage.open_reconcile_seconds`, which `sofascore_scraper/store/files.py` reads from the loader through `sys.modules`; the old names only give a `legacy_name` warning. The plan wanted the durability from the Store's caller, which no caller can give; it stays open. Sections 3.5, - 4.4 (P30 #186). + 4.4 (P30 #186). Closed on 2026-11-21: the loader gives the Store a function for its settings + (`store.use_settings`), and the Store no longer looks into `sys.modules` (4.4). 151. **Three backup scopes.** Section 9.1 still listed the four 2.x scopes as deprecated. P30 removed them everywhere; archives with an old scope name are still recognised and restored. Sections 2.3, 6.1, 9.1 (P30 #186). diff --git a/docs/design/02-services.md b/docs/design/02-services.md index 204333c4..a5dfdb05 100644 --- a/docs/design/02-services.md +++ b/docs/design/02-services.md @@ -3779,10 +3779,12 @@ config file too, the loader wrote the effective value of every setting back into legacy name (`loader.projection`). P30 (#186) removed it with the legacy table and the dotenv layer: the throttle, the refresh policy, the bridge health, the breaker, the logger, the paths module, the transport, the bridge, the web security module and `sofascore_scraper/store/files.py` read the active settings, and the -logger follows every rebuild of the settings (`logger.follow_settings`). `store/files.py` does not get its -durability from its caller, as the plan said: the Store may not import the configuration, so it reads -`storage.durability`, `storage.open_reconcile_seconds` and `storage.data_dir` from the loader module through -`sys.modules` and uses the defaults when no loader is loaded (`01-storage.md`). +logger follows every rebuild of the settings (`logger.follow_settings`). The Store may not import the +configuration, so `store/files.py` gets `storage.durability`, `storage.open_reconcile_seconds` and +`storage.data_dir` from its caller: the loader, when it is imported, gives it a function that returns the +active settings' `[storage]` section (`sofascore_scraper.store.use_settings`), and the Store calls it on every +read, so changed settings apply to the next write. Without the loader the Store uses the defaults +(`01-storage.md` 4.4). Until 2026-11-21 it read the loader module through `sys.modules`. **What stops the start.** A broken config file, an unknown `SOFASCORE_*__*` variable, an invalid value under a new name, one of the guarded 2.x names set without its new name (`GuardedNameError`) or an invalid @@ -6659,8 +6661,8 @@ Corrections after the removal of the guarded 2.x names (2026-11-20, for 3.2; not relay set as `API_BASE_URL` is not, so such a user's requests go straight to SofaScore. A value in `.env` under a new name pins the setting above `sofascore.toml` and locks it on the Settings page, which a user who edits the config file may not expect; the lock shows its source. - `sofascore_scraper/store/files.py` reads the storage settings through `sys.modules` (4.3), so a process - that never loads the settings loader writes with the default durability. + The settings loader gives the Store its storage settings when it is imported (`store.use_settings`, 4.3), + so a process that never loads the settings loader writes with the default durability. - Webhook head-of-line blocking: a receiver that is down blocks its sink for up to `max_age` (24 h by default); a low `max_age` loses events. Operators need the lag shown in status. As built (P22) the lag is not shown anywhere yet (`ssc status` per sink is ST-24's), and one thread diff --git a/docs/design/03-implementation-plan.md b/docs/design/03-implementation-plan.md index 67c9e482..e1a48852 100644 --- a/docs/design/03-implementation-plan.md +++ b/docs/design/03-implementation-plan.md @@ -5680,7 +5680,9 @@ Open after 3.2.0 (the items of section 19's list that are not done, copied), in a season's pages, the planner's listed events) read `listed_in`. Dropping them needs a design first. - **`sofascore_scraper/store/files.py` gets its durability from the caller.** It reads `storage.durability` through the loader module in `sys.modules` (the Store may not import the configuration); no Store caller - has the settings today. + has the settings today. **Done (this PR, 2026-11-21).** The Store takes a function for its `[storage]` + settings (`sofascore_scraper.store.use_settings`), the loader passes its own when it is imported and the + Store calls it on every read, so changed settings still apply to the next write (`01-storage.md` 4.4). - **The live-match-tracker document in the explorer.** The iframe document under `/api/v1/event/{id}/live-match-tracker/` is a Document request, outside the explorer's `Fetch` patterns, so it is sent without a slot and not counted (one per event page). Holding Document requests in the interceptor would fix it. diff --git a/docs/design/README.md b/docs/design/README.md index c5a087c1..fa9b1e75 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -130,14 +130,14 @@ section 19, 3.2 and the release 3.2.0 in its section 20): #239). The image is `ghcr.io/tunjayoff/sofascore_scraper:3.2.0`, from source like 3.1. - **Open after 3.2.0** (section 20 of `03`): a rule for team streaks that answer 200 with an empty body, baseball's umpires, weather, comments and at-bats, a fetch of the odds providers' listing and a - `provider_name` field, a replacement for the events columns `stage_name` and `listed_in`, the Store's - durability from its caller, the explorer's unthrottled live-match-tracker document, and two small + `provider_name` field, a replacement for the events columns `stage_name` and `listed_in`, the explorer's + unthrottled live-match-tracker document, and two small leftovers of P30; from 3.1.2: the trust feature is not verified on Windows and macOS or behind a real proxy, its browser part is Linux only, CI has no path filter for documents-only changes, the profile list has no routine for re-measuring it, and a trusted certificate has no scope and no reminder. Closed in 3.2: the four deprecated names, backups without the `ca` folder, the home-page load of `ssc doctor --live`, the set-aside profiles in no face, unused code, and the third P30 leftover (closed without a - code change). + code change). Closed after 3.2.0: the Store's durability from its caller (2026-11-21). Not in 3.1 or 3.2: a localized date picker (owner) and the web UI under a path prefix. - What a user can see: everything a download writes is in the new layout (`v3/`, 8.4 times smaller on the owner's data) and the old folders are read in place; `ssc` covers every task of the former terminal menu diff --git a/sofascore_scraper/config/loader.py b/sofascore_scraper/config/loader.py index 66d862c6..b4b1b248 100644 --- a/sofascore_scraper/config/loader.py +++ b/sofascore_scraper/config/loader.py @@ -22,7 +22,8 @@ diğerleri gibi bir uyarıdır. Ayarları okuyan modüller (throttle, refresh, logger, köprü sağlığı, devre kesici, istek katmanı...) değeri -`active_settings()`ten alır; ortamdan doğrudan okumazlar. 3.0'ın geçiş köprüsü (etkin değeri eski adıyla +`active_settings()`ten alır; ortamdan doğrudan okumazlar. Store ayarları içe aktaramaz: `[storage]` bölümünü ona +bu modül verir (`sofascore_scraper.store.use_settings`, yüklenirken). 3.0'ın geçiş köprüsü (etkin değeri eski adıyla ortama yazan `projection`) 3.1'de kalktı. Yapılandırma dosyası süreç başına bir kez okunur; yeniden okumak açık bir çağrıdır (`reload`, @@ -60,6 +61,7 @@ from sofascore_scraper.exceptions import ConfigError from sofascore_scraper.redact import MASK, mask_webhook_url from sofascore_scraper.sports import UnknownSliceName, check_slice_names, sport_slugs +from sofascore_scraper.store import use_settings as use_store_settings logger = logging.getLogger("Config") @@ -1382,6 +1384,19 @@ def active_settings() -> Settings: return active().settings +def _store_settings() -> model.StorageSettings: + """ + Store'un ayar kaynağı (`sofascore_scraper.store.use_settings`): etkin ayarların `[storage]` bölümü. Store onu her + okumada çağırır; ortamdaki ya da yeniden yüklenen dosyalardaki değişiklik sonraki yazmada geçerlidir. + """ + return active_settings().storage + + +# Store ayarları içe aktaramaz (katman kuralı): dayanıklılığı, varsayılan veri dizinini ve açılış taramasının süresini +# ona yükleyici verir, kendisi yüklenir yüklenmez (docs/design/01-storage.md bölüm 4.4) +use_store_settings(_store_settings) + + def current() -> Optional[LoadedSettings]: """Kurulmuş etkin ayarlar; henüz kurulmadıysa None. Kurmaz (log maskesi gibi kurulumu tetiklememesi gerekenler için).""" return _loaded diff --git a/sofascore_scraper/store/__init__.py b/sofascore_scraper/store/__init__.py index ce584a8c..e504bcad 100644 --- a/sofascore_scraper/store/__init__.py +++ b/sofascore_scraper/store/__init__.py @@ -7,7 +7,8 @@ (`EventStore`, `EntityStore`, `ChangeLog` ile sorgu ve sonuç türleri: `Ref`, `Scope`, `EventQuery`, `Page`, `EventRow`, `SliceInfo`, ...) ve kataloğun yönetimi (`CatalogAdmin` ve raporları). Eski düzen yazıcılarının gölge kip kancaları (`shadow_*`) plan maddesi FX-15'te kalktı. Maçların yazma API'si `EventStore.put` / `observe` / `reset_empty_markers` / -`delete` (sonucu `PutResult`) ve `ChangeLog.append`'tir; maç dışı varlıklarınki `EntityStore.put`. +`delete` (sonucu `PutResult`) ve `ChangeLog.append`'tir; maç dışı varlıklarınki `EntityStore.put`. Store'un `[storage]` +ayarlarını (dayanıklılık, varsayılan veri dizini, açılış taraması) çağıran `use_settings` ile verir. Hata sınıfları dışındaki adlar ilk kullanımda yüklenir: kök, cepheyi (SQLite, katalog, türetme) içe aktarmadan da alınabilmelidir: hata sınıflarını uygulamanın en alt katmanları kullanır ve bir alt modülü @@ -76,6 +77,7 @@ from sofascore_scraper.store.state import load_migrations from sofascore_scraper.store.legacy import league_dir_name from sofascore_scraper.store.purge import Purger, TournamentClearReport + from sofascore_scraper.store.files import use_settings _LAZY = { "open_store": "sofascore_scraper.store.api", @@ -157,6 +159,7 @@ "league_dir_name": "sofascore_scraper.store.legacy", "Purger": "sofascore_scraper.store.purge", "TournamentClearReport": "sofascore_scraper.store.purge", + "use_settings": "sofascore_scraper.store.files", } @@ -253,6 +256,7 @@ def __dir__() -> list: "league_dir_name", "Purger", "TournamentClearReport", + "use_settings", "StoreError", "LeaseHeld", "StoreBusy", diff --git a/sofascore_scraper/store/files.py b/sofascore_scraper/store/files.py index 7f255424..2a647ff8 100644 --- a/sofascore_scraper/store/files.py +++ b/sofascore_scraper/store/files.py @@ -7,8 +7,9 @@ dosyaya aynı anda yazan iki süreç birbirinin geçici dosyasını ezmez. Her OSError bir StoreError'a çevrilir (`fatal` errno'dan hesaplanır) ve `storage.durability` "full" ise dosya ve -dizini fsync edilir (`durability_full`). Veri dizini dışındaki yapılandırma dosyaları (leagues.txt, league_sports.json, -overrides.json) bu modülle değil sofascore_scraper/config_files.py ile yazılır. +dizini fsync edilir (`durability_full`). Ayarları Store'a çağıranı verir (`use_settings`); Store ayarları içe +aktarmaz. Veri dizini dışındaki yapılandırma dosyaları (leagues.txt, league_sports.json, overrides.json) bu modülle +değil sofascore_scraper/config_files.py ile yazılır. Dosya izinleri (karar S12): Store katmanının yazdığı dosyalar (yükler, manifestler, .meta/schema.json) sürecin umask'ine uyar: umask 022 ile 0644, 077 ile 0600. Böylece Docker bağlama noktasını başka bir @@ -26,7 +27,6 @@ import errno import os import shutil -import sys import time import uuid from typing import Any, Callable, Collection, Optional, Tuple, Union @@ -52,17 +52,29 @@ class ReplaceBusy(PermissionError): """Yerine koyma, yeniden denemelere rağmen başarısız: hedef başka bir süreçte açık (Windows).""" -def _storage_settings() -> Any: +# Store'un `[storage]` ayarlarını veren işlev: üst katman (ayar yükleyicisi, sofascore_scraper/config/loader.py) kendisi +# yüklenirken `use_settings` ile verir. Store ayarları içe aktarmaz (katman kuralı; ayarlar Store'un üstündedir). +_settings_source: Optional[Callable[[], Any]] = None + + +def use_settings(source: Optional[Callable[[], Any]]) -> None: """ - Uygulamanın `[storage]` ayarları; ayar yükleyicisi bu süreçte yüklenmemişse None. Store ayar yükleyicisini içe - aktaramaz (katman kuralı; ayarlar Store'un üstündedir): değerler yükleyicinin modülünden, yüklenmişse, - `sys.modules` üzerinden okunur. Yükleyicisi olmayan bir süreç (yönetim aracı, test) varsayılanlarla çalışır. + Store'un ayarlarını nereden okuyacağını söyler. `source()` her okumada çağrılır ve `data_dir`, `durability`, + `open_reconcile_seconds` öznitelikleri olan bir nesne döndürür (uygulamada etkin ayarların `[storage]` + bölümü): ayar değişince (ortam, Ayarlar sayfasının yeniden yüklemesi) sonraki yazma yeni değeri görür. + None kaynağı kaldırır. Kaynağı verilmemiş bir süreç (yönetim aracı, test) varsayılanlarla çalışır. """ - loader = sys.modules.get("sofascore_scraper.config.loader") - if loader is None: + global _settings_source + _settings_source = source + + +def _storage_settings() -> Any: + """Çağıranın verdiği `[storage]` ayarları (`use_settings`); kaynak yoksa ya da okunamıyorsa None.""" + source = _settings_source + if source is None: return None try: - return loader.active_settings().storage + return source() except Exception: # geçersiz yapılandırma: yazma durmasın, varsayılanlar return None diff --git a/tests/characterization/fixtures/cli/doctor_env_problems.golden.json b/tests/characterization/fixtures/cli/doctor_env_problems.golden.json index 53b40617..5db7dd23 100644 --- a/tests/characterization/fixtures/cli/doctor_env_problems.golden.json +++ b/tests/characterization/fixtures/cli/doctor_env_problems.golden.json @@ -45,6 +45,10 @@ "sofascore_scraper.paths", "sofascore_scraper.redact", "sofascore_scraper.sports", + "sofascore_scraper.store", + "sofascore_scraper.store.errors", + "sofascore_scraper.store.files", + "sofascore_scraper.store.layout", "sofascore_scraper.version" ], "stderr": [ @@ -144,6 +148,10 @@ "sofascore_scraper.paths", "sofascore_scraper.redact", "sofascore_scraper.sports", + "sofascore_scraper.store", + "sofascore_scraper.store.errors", + "sofascore_scraper.store.files", + "sofascore_scraper.store.layout", "sofascore_scraper.version" ], "stderr": [ diff --git a/tests/characterization/fixtures/cli/doctor_json.golden.json b/tests/characterization/fixtures/cli/doctor_json.golden.json index 031d8ee6..e6dd2b3e 100644 --- a/tests/characterization/fixtures/cli/doctor_json.golden.json +++ b/tests/characterization/fixtures/cli/doctor_json.golden.json @@ -44,6 +44,10 @@ "sofascore_scraper.paths", "sofascore_scraper.redact", "sofascore_scraper.sports", + "sofascore_scraper.store", + "sofascore_scraper.store.errors", + "sofascore_scraper.store.files", + "sofascore_scraper.store.layout", "sofascore_scraper.version" ], "stderr": [], diff --git a/tests/fixtures/store_api/use_settings.txt b/tests/fixtures/store_api/use_settings.txt new file mode 100644 index 00000000..80ae772d --- /dev/null +++ b/tests/fixtures/store_api/use_settings.txt @@ -0,0 +1,3 @@ +# sofascore_scraper.store.use_settings +# kaynak: sofascore_scraper/store/files.py +def use_settings(source: Optional[Callable[[], Any]]) -> None diff --git a/tests/test_config_loader.py b/tests/test_config_loader.py index a98cd106..8fb04d40 100644 --- a/tests/test_config_loader.py +++ b/tests/test_config_loader.py @@ -1339,6 +1339,45 @@ def test_log_settings_from_the_config_file_reach_the_running_logger(active): assert app_logger._file_handler.backupCount == app_logger.DEFAULT_BACKUP_COUNT +def test_the_store_reads_its_settings_through_the_loader(active, monkeypatch, tmp_path): + """ + Store ayarları içe aktaramaz (tests/test_layers.py): `[storage]` bölümünü ona yükleyici verir + (`store.use_settings`), Store onu her okumada çağırır. Dosyadaki değer ve yeniden yükleme sonraki yazmada geçerlidir; + ortamdaki değer dosyayı ezer ve değişimi de hemen görülür; 2.x'in adı okunmaz. + """ + assert store_files._settings_source is loader._store_settings + monkeypatch.delenv("SOFASCORE_STORAGE__DATA_DIR") + data_dir = (tmp_path / "from-file").as_posix() + active(f'[storage]\ndurability = "full"\ndata_dir = "{data_dir}"\nopen_reconcile_seconds = 5\n') + assert (store_files.durability_full(), store_files.default_data_dir(), store_files.open_reconcile_seconds()) == ( + True, str(Path(data_dir)), 5.0) + active("[storage]\n") + assert (store_files.durability_full(), store_files.default_data_dir(), store_files.open_reconcile_seconds()) == ( + False, "data", 60.0) + for raw in ("full", "FULL", " full "): + monkeypatch.setenv("SOFASCORE_STORAGE__DURABILITY", raw) + assert store_files.durability_full() is True, raw + monkeypatch.delenv("SOFASCORE_STORAGE__DURABILITY") + monkeypatch.setenv("STORE_DURABILITY", "full") + assert store_files.durability_full() is False + + +def test_importing_the_loader_gives_the_store_its_settings(tmp_path): + """Ayrı bir süreçte: yükleyiciyi içe aktaran süreçte Store ortamdaki `storage.durability`yi görür, kendisi ayarları yüklemez.""" + code = ( + "import sys\n" + "from sofascore_scraper.store import files\n" + "assert files._settings_source is None and files.durability_full() is False\n" + "assert 'sofascore_scraper.config.loader' not in sys.modules\n" + "import sofascore_scraper.config\n" + "print(files.durability_full(), files.open_reconcile_seconds())\n" + ) + done = _run_python(code, tmp_path, SOFASCORE_STORAGE__DURABILITY="full", + SOFASCORE_STORAGE__OPEN_RECONCILE_SECONDS="7", SOFASCORE_CONFIG="none") + assert done.returncode == 0, done.stderr + assert done.stdout.strip().splitlines()[-1] == "True 7.0" + + def _run_python(code: str, tmp_path: Path, **env: str) -> subprocess.CompletedProcess: """Kodu temiz bir süreçte çalıştırır: gerçek `.env`, config/ ve log dizinine dokunmaz.""" clean = {k: v for k, v in os.environ.items() if k not in loader.LEGACY_ENV_NAMES and not k.startswith("SOFASCORE_")} diff --git a/tests/test_layers.py b/tests/test_layers.py index 286d4bb3..2df19769 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -135,6 +135,20 @@ def test_store_has_no_network_code(): assert not problems, "sofascore_scraper/store/ ağ kodu içermez (docs/design/01-storage.md bölüm 2.1):\n " + "\n ".join(problems) +def test_the_store_does_not_look_up_other_layers_in_sys_modules(): + """ + İçe aktarma yasağının arka kapısı da kapalı: Store başka bir katmanın modülünü `sys.modules`'tan almaz. Ayarlarını + (`[storage]`) ona çağıranı verir (`sofascore_scraper.store.use_settings`; 03-implementation-plan.md bölüm 20). + """ + found = [ + f"{path.relative_to(ROOT).as_posix()}:{number}" + for path in sorted(STORE_DIR.rglob("*.py")) + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1) + if "sys.modules" in line + ] + assert not found, "sofascore_scraper/store/ sys.modules'a bakmaz; değeri çağıran versin:\n " + "\n ".join(found) + + def test_the_modules_the_store_may_import_exist(): for module in sorted(STORE_MAY_IMPORT): assert (ROOT / (module.replace(".", "/") + ".py")).is_file(), f"{module} yok: izin listesi güncel değil" diff --git a/tests/test_store_files.py b/tests/test_store_files.py index 51730e80..84447936 100644 --- a/tests/test_store_files.py +++ b/tests/test_store_files.py @@ -14,6 +14,7 @@ import stat import sys from datetime import datetime, timezone +from types import SimpleNamespace from typing import Iterator import pytest @@ -259,7 +260,7 @@ def test_permission_error_is_not_retried_outside_windows(tmp_path, monkeypatch, assert not isinstance(caught.value.__cause__, files.ReplaceBusy) -# --- fsync (STORE_DURABILITY) ----------------------------------------------------------------------- +# --- fsync (`storage.durability`; değeri çağıran verir: files.use_settings) ---------------------------- @pytest.fixture def fsyncs(monkeypatch): @@ -268,12 +269,24 @@ def fsyncs(monkeypatch): return recorded -# `storage.durability`in ortamdaki adı: Store onu ayar yükleyicisinden okur (sofascore_scraper/store/files.py) -DURABILITY_ENV = "SOFASCORE_STORAGE__DURABILITY" +def _storage(durability="normal", data_dir="data", open_reconcile_seconds=60.0): + """Çağıranın Store'a verdiği `[storage]` bölümünün yerine geçen nesne (`files.use_settings`).""" + return SimpleNamespace(durability=durability, data_dir=data_dir, open_reconcile_seconds=open_reconcile_seconds) -def test_nothing_is_fsynced_by_default(tmp_path, monkeypatch, fsyncs): - monkeypatch.delenv(DURABILITY_ENV, raising=False) +@pytest.fixture +def storage_source(monkeypatch): + """`files.use_settings` ile verilecek ayarları test seçer; test bitince süreçteki kaynak (yükleyici) geri gelir.""" + monkeypatch.setattr(files, "_settings_source", files._settings_source) + + def use(**values): + files.use_settings(lambda: _storage(**values)) + + return use + + +def test_nothing_is_fsynced_by_default(tmp_path, storage_source, fsyncs): + storage_source() files.write_bytes(tmp_path / "a.json.gz", b"x") @@ -281,9 +294,8 @@ def test_nothing_is_fsynced_by_default(tmp_path, monkeypatch, fsyncs): assert fsyncs == [] -@pytest.mark.parametrize("value", ["full", "FULL", " full "]) -def test_store_durability_full_fsyncs_the_file_and_its_directory(tmp_path, monkeypatch, fsyncs, value): - monkeypatch.setenv(DURABILITY_ENV, value) +def test_store_durability_full_fsyncs_the_file_and_its_directory(tmp_path, storage_source, fsyncs): + storage_source(durability="full") files.write_bytes(tmp_path / "a.json.gz", b"x") @@ -292,23 +304,51 @@ def test_store_durability_full_fsyncs_the_file_and_its_directory(tmp_path, monke assert (tmp_path / "a.json.gz").read_bytes() == b"x" -def test_the_2x_durability_name_is_not_read(tmp_path, monkeypatch, fsyncs): - monkeypatch.delenv(DURABILITY_ENV, raising=False) - monkeypatch.setenv("STORE_DURABILITY", "full") - files.write_bytes(tmp_path / "a.json.gz", b"x") - assert files.durability_full() is False and fsyncs == [] - - -def test_durable_argument_overrides_the_environment(tmp_path, monkeypatch, fsyncs): - monkeypatch.setenv(DURABILITY_ENV, "full") +def test_durable_argument_overrides_the_setting(tmp_path, storage_source, fsyncs): + storage_source(durability="full") files.write_bytes(tmp_path / "a.json.gz", b"x", durable=False) assert fsyncs == [] - monkeypatch.setenv(DURABILITY_ENV, "normal") + storage_source(durability="normal") files.write_bytes(tmp_path / "b.json.gz", b"x", durable=True) assert len(fsyncs) == (1 if WINDOWS else 2) +def test_the_source_is_read_on_every_write(tmp_path, monkeypatch, fsyncs): + """Kaynak her okumada çağrılır: ayar değişince (ortam, yeniden yükleme) sonraki yazma yeni değeri görür.""" + monkeypatch.setattr(files, "_settings_source", None) + current = {"durability": "normal"} + files.use_settings(lambda: _storage(**current)) + files.write_bytes(tmp_path / "a.json.gz", b"x") + assert fsyncs == [] + + current["durability"] = "full" + files.write_bytes(tmp_path / "b.json.gz", b"x") + assert len(fsyncs) == (1 if WINDOWS else 2) + + +def test_the_other_storage_settings_come_from_the_same_source(storage_source): + storage_source(data_dir="/srv/sofascore", open_reconcile_seconds=5.0) + assert (files.default_data_dir(), files.open_reconcile_seconds()) == ("/srv/sofascore", 5.0) + storage_source(data_dir="", open_reconcile_seconds=-3) + assert (files.default_data_dir(), files.open_reconcile_seconds()) == ("data", 0.0) + + +def test_without_a_source_or_with_a_failing_one_the_defaults_apply(tmp_path, monkeypatch, fsyncs): + """Kaynağı verilmemiş süreç (yönetim aracı, test) ya da okunamayan ayarlar: yazma durmaz, varsayılanlar.""" + monkeypatch.setattr(files, "_settings_source", None) + defaults = (files.durability_full(), files.default_data_dir(), files.open_reconcile_seconds()) + assert defaults == (False, "data", files.OPEN_RECONCILE_SECONDS) + + def broken(): + raise ValueError("invalid configuration") + + files.use_settings(broken) + files.write_bytes(tmp_path / "a.json.gz", b"x") + assert (files.durability_full(), files.default_data_dir(), files.open_reconcile_seconds()) == defaults + assert fsyncs == [] + + # --- dosya izinleri (karar S12) ---------------------------------------------------------------------- posix_modes = pytest.mark.skipif(WINDOWS, reason="POSIX dosya izinleri Windows'ta yok") diff --git a/tests/test_store_shadow.py b/tests/test_store_shadow.py index d91ab317..be1e2161 100644 --- a/tests/test_store_shadow.py +++ b/tests/test_store_shadow.py @@ -88,7 +88,7 @@ def no_check(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv(api_mod.SHADOW_CHECK_ENV) -# `storage.open_reconcile_seconds`in ortamdaki adı (Store onu ayar yükleyicisinden okur) +# `storage.open_reconcile_seconds`in ortamdaki adı (yükleyici onu Store'a verir: store.use_settings) OPEN_RECONCILE_ENV = "SOFASCORE_STORAGE__OPEN_RECONCILE_SECONDS"