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
23 changes: 17 additions & 6 deletions docs/design/01-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down Expand Up @@ -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).
Expand Down
14 changes: 8 additions & 6 deletions docs/design/02-services.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion docs/design/03-implementation-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions docs/design/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion sofascore_scraper/config/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion sofascore_scraper/store/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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ü
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
}


Expand Down Expand Up @@ -253,6 +256,7 @@ def __dir__() -> list:
"league_dir_name",
"Purger",
"TournamentClearReport",
"use_settings",
"StoreError",
"LeaseHeld",
"StoreBusy",
Expand Down
32 changes: 22 additions & 10 deletions sofascore_scraper/store/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down Expand Up @@ -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": [
Expand Down
4 changes: 4 additions & 0 deletions tests/characterization/fixtures/cli/doctor_json.golden.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [],
Expand Down
3 changes: 3 additions & 0 deletions tests/fixtures/store_api/use_settings.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# sofascore_scraper.store.use_settings
# kaynak: sofascore_scraper/store/files.py
def use_settings(source: Optional[Callable[[], Any]]) -> None
39 changes: 39 additions & 0 deletions tests/test_config_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_")}
Expand Down
Loading
Loading