pyferro 2.2.5__tar.gz → 2.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pyferro-2.2.5/src/pyferro.egg-info → pyferro-2.3.0}/PKG-INFO +1 -1
- {pyferro-2.2.5 → pyferro-2.3.0}/pyproject.toml +1 -1
- {pyferro-2.2.5 → pyferro-2.3.0/src/pyferro.egg-info}/PKG-INFO +1 -1
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro.egg-info/SOURCES.txt +7 -2
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/__init__.py +11 -1
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/auth/seeder.py +1 -0
- pyferro-2.3.0/src/pyferro2/cache/__init__.py +40 -0
- pyferro-2.3.0/src/pyferro2/cache/manager.py +446 -0
- pyferro-2.3.0/src/pyferro2/cache/models.py +140 -0
- pyferro-2.3.0/src/pyferro2/cache/rpc.py +140 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/core/constants.py +1 -0
- pyferro-2.3.0/src/pyferro2/db/engine.py +152 -0
- pyferro-2.3.0/src/pyferro2/frontend/dist/assets/index-B0aG4rP0.js +47 -0
- pyferro-2.3.0/src/pyferro2/frontend/dist/assets/index-CiGpJ7OV.css +1 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/frontend/dist/index.html +2 -2
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/help/help_data.json +240 -0
- pyferro-2.3.0/src/pyferro2/migrations/migration_v2_3_0.py +67 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/oauth/rpc.py +2 -1
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/rpc/router.py +76 -1
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/jinja_engine.py +3 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/server/app.py +13 -1
- pyferro-2.2.5/src/pyferro2/db/engine.py +0 -67
- pyferro-2.2.5/src/pyferro2/frontend/dist/assets/index-B_9G6De6.js +0 -47
- pyferro-2.2.5/src/pyferro2/frontend/dist/assets/index-DFTwYq0b.css +0 -1
- {pyferro-2.2.5 → pyferro-2.3.0}/LICENSE +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/README.md +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/setup.cfg +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro.egg-info/dependency_links.txt +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro.egg-info/requires.txt +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro.egg-info/top_level.txt +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/__main__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/auth/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/auth/models.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/auth/passwords.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/core/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/core/session.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/core/session_data.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/core/tabular.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/crud/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/crud/engine.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/crud/rpc.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/crud/spec.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/db/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/db/base.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/db/pagination.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/files/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/files/models.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/files/rpc.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/files/storage.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/help/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/help/rpc.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/migrations/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/migrations/migration_v2_0_0.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/migrations/migration_v2_1_0.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/migrations/migration_v2_2_0.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/oauth/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/oauth/http_client.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/oauth/mailer.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/oauth/manager.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/oauth/models.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/oauth/providers.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/rpc/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/rpc/errors.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/detector.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/indexnow.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/models.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/page_cache.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/renderer.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/router.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/rpc.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/site_tree.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/seo/sitemap.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/server/__init__.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/server/auth_rpc.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/server/test_client.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/src/pyferro2/server/tokens.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/tests/test_e2e_lifecycle.py +0 -0
- {pyferro-2.2.5 → pyferro-2.3.0}/tests/test_pagination.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyferro
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: High-performance reactive fullstack Python framework on Rust RSGI (Granian) with symmetric WSRPC (JSON-RPC 2.0) and Tabular Data Compression.
|
|
5
5
|
Author-email: Alex Titoff <a.tit.off@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "pyferro"
|
|
7
|
-
version = "2.
|
|
7
|
+
version = "2.3.0"
|
|
8
8
|
description = "High-performance reactive fullstack Python framework on Rust RSGI (Granian) with symmetric WSRPC (JSON-RPC 2.0) and Tabular Data Compression."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyferro
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.0
|
|
4
4
|
Summary: High-performance reactive fullstack Python framework on Rust RSGI (Granian) with symmetric WSRPC (JSON-RPC 2.0) and Tabular Data Compression.
|
|
5
5
|
Author-email: Alex Titoff <a.tit.off@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -12,6 +12,10 @@ src/pyferro2/auth/__init__.py
|
|
|
12
12
|
src/pyferro2/auth/models.py
|
|
13
13
|
src/pyferro2/auth/passwords.py
|
|
14
14
|
src/pyferro2/auth/seeder.py
|
|
15
|
+
src/pyferro2/cache/__init__.py
|
|
16
|
+
src/pyferro2/cache/manager.py
|
|
17
|
+
src/pyferro2/cache/models.py
|
|
18
|
+
src/pyferro2/cache/rpc.py
|
|
15
19
|
src/pyferro2/core/__init__.py
|
|
16
20
|
src/pyferro2/core/constants.py
|
|
17
21
|
src/pyferro2/core/session.py
|
|
@@ -30,8 +34,8 @@ src/pyferro2/files/models.py
|
|
|
30
34
|
src/pyferro2/files/rpc.py
|
|
31
35
|
src/pyferro2/files/storage.py
|
|
32
36
|
src/pyferro2/frontend/dist/index.html
|
|
33
|
-
src/pyferro2/frontend/dist/assets/index-
|
|
34
|
-
src/pyferro2/frontend/dist/assets/index-
|
|
37
|
+
src/pyferro2/frontend/dist/assets/index-B0aG4rP0.js
|
|
38
|
+
src/pyferro2/frontend/dist/assets/index-CiGpJ7OV.css
|
|
35
39
|
src/pyferro2/help/__init__.py
|
|
36
40
|
src/pyferro2/help/help_data.json
|
|
37
41
|
src/pyferro2/help/rpc.py
|
|
@@ -39,6 +43,7 @@ src/pyferro2/migrations/__init__.py
|
|
|
39
43
|
src/pyferro2/migrations/migration_v2_0_0.py
|
|
40
44
|
src/pyferro2/migrations/migration_v2_1_0.py
|
|
41
45
|
src/pyferro2/migrations/migration_v2_2_0.py
|
|
46
|
+
src/pyferro2/migrations/migration_v2_3_0.py
|
|
42
47
|
src/pyferro2/oauth/__init__.py
|
|
43
48
|
src/pyferro2/oauth/http_client.py
|
|
44
49
|
src/pyferro2/oauth/mailer.py
|
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
PyFerro 2.0 — высокопроизводительный веб-фреймворк с минимальным потреблением CPU и zero-boilerplate.
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
|
+
from pyferro2.cache import (
|
|
6
|
+
CacheConfig,
|
|
7
|
+
CacheManager,
|
|
8
|
+
CacheRule,
|
|
9
|
+
cache_manager,
|
|
10
|
+
)
|
|
5
11
|
from pyferro2.db.pagination import decode_cursor, encode_cursor, paginate_tabular
|
|
6
12
|
from pyferro2.seo import (
|
|
7
13
|
HtmlBuilder,
|
|
@@ -15,7 +21,7 @@ from pyferro2.seo import (
|
|
|
15
21
|
register_sitemap_provider,
|
|
16
22
|
)
|
|
17
23
|
|
|
18
|
-
__version__ = "2.
|
|
24
|
+
__version__ = "2.3.0"
|
|
19
25
|
|
|
20
26
|
__all__ = [
|
|
21
27
|
"__version__",
|
|
@@ -31,4 +37,8 @@ __all__ = [
|
|
|
31
37
|
"bot_page",
|
|
32
38
|
"register_sitemap_provider",
|
|
33
39
|
"notify_indexnow",
|
|
40
|
+
"CacheConfig",
|
|
41
|
+
"CacheRule",
|
|
42
|
+
"CacheManager",
|
|
43
|
+
"cache_manager",
|
|
34
44
|
]
|
|
@@ -25,6 +25,7 @@ SYSTEM_ROLE_DESCRIPTIONS: dict[str, str] = {
|
|
|
25
25
|
admRole.adm_rpc.value: "Доступ к инспектору и правам JSON-RPC методов",
|
|
26
26
|
admRole.adm_help.value: "Чтение справки PyFerro2",
|
|
27
27
|
admRole.adm_seo.value: "Доступ к управлению SEO-правилами и страницами",
|
|
28
|
+
admRole.adm_cache.value: "Доступ к управлению кешированием и Offline-режимом",
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Подсистема интеллектуального кеширования, авто-инвалидации и Offline-First в PyFerro 2.0 (`pyferro2.cache`).
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from pyferro2.cache.manager import (
|
|
6
|
+
CacheManager,
|
|
7
|
+
cache_manager,
|
|
8
|
+
compute_etag,
|
|
9
|
+
load_cache_from_db,
|
|
10
|
+
purge_all_cache,
|
|
11
|
+
record_read_table,
|
|
12
|
+
save_cache_to_db,
|
|
13
|
+
start_table_tracking,
|
|
14
|
+
stop_table_tracking,
|
|
15
|
+
)
|
|
16
|
+
from pyferro2.cache.models import (
|
|
17
|
+
CacheConfig,
|
|
18
|
+
CacheConfigRecord,
|
|
19
|
+
CacheRule,
|
|
20
|
+
CacheRuleRecord,
|
|
21
|
+
)
|
|
22
|
+
from pyferro2.cache.rpc import infer_method_cache_scope, register_cache_rpc
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"CacheManager",
|
|
26
|
+
"cache_manager",
|
|
27
|
+
"compute_etag",
|
|
28
|
+
"load_cache_from_db",
|
|
29
|
+
"save_cache_to_db",
|
|
30
|
+
"purge_all_cache",
|
|
31
|
+
"start_table_tracking",
|
|
32
|
+
"stop_table_tracking",
|
|
33
|
+
"record_read_table",
|
|
34
|
+
"CacheConfig",
|
|
35
|
+
"CacheConfigRecord",
|
|
36
|
+
"CacheRule",
|
|
37
|
+
"CacheRuleRecord",
|
|
38
|
+
"infer_method_cache_scope",
|
|
39
|
+
"register_cache_rpc",
|
|
40
|
+
]
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Менеджер серверного L1-кеша, авто-трекинга таблиц SQLAlchemy, ETag и идемпотентности мутаций (`pyferro2/cache/manager.py`).
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
from collections import OrderedDict
|
|
9
|
+
from contextvars import ContextVar, Token
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
import hashlib
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, Callable, Coroutine
|
|
14
|
+
|
|
15
|
+
import orjson
|
|
16
|
+
from sqlalchemy import delete, select
|
|
17
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
18
|
+
|
|
19
|
+
from pyferro2.cache.models import (
|
|
20
|
+
CacheConfig,
|
|
21
|
+
CacheConfigRecord,
|
|
22
|
+
CacheRule,
|
|
23
|
+
CacheRuleRecord,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# Контекстная переменная для отслеживания таблиц БД, прочитанных в рамках текущего RPC-вызова
|
|
27
|
+
_active_table_tracker: ContextVar[set[str] | None] = ContextVar(
|
|
28
|
+
"_active_table_tracker", default=None
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def start_table_tracking() -> tuple[set[str], Token[set[str] | None]]:
|
|
33
|
+
"""Включает сбор имен таблиц, к которым обращаются SELECT-запросы в текущем контексте."""
|
|
34
|
+
tracked: set[str] = set()
|
|
35
|
+
token = _active_table_tracker.set(tracked)
|
|
36
|
+
return tracked, token
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def stop_table_tracking(token: Token[set[str] | None]) -> None:
|
|
40
|
+
"""Завершает сбор имен таблиц в текущем контексте."""
|
|
41
|
+
_active_table_tracker.reset(token)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def record_read_table(table_name: str) -> None:
|
|
45
|
+
"""Фиксирует чтение из таблицы `table_name`, если трекинг активен."""
|
|
46
|
+
tracker = _active_table_tracker.get()
|
|
47
|
+
if tracker is not None and table_name and not table_name.startswith("pf_"):
|
|
48
|
+
tracker.add(table_name)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def compute_etag(data: Any) -> str:
|
|
52
|
+
"""Вычисляет быстрый 64-битный ETag (16 hex-символов) через BLAKE2b от сериализованного JSON."""
|
|
53
|
+
try:
|
|
54
|
+
raw = orjson.dumps(data, option=orjson.OPT_SORT_KEYS)
|
|
55
|
+
except Exception:
|
|
56
|
+
raw = str(data).encode("utf-8", errors="ignore")
|
|
57
|
+
return hashlib.blake2b(raw, digest_size=8).hexdigest()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def make_canonical_params(params: dict[str, Any] | list[Any] | None) -> str:
|
|
61
|
+
"""Возвращает каноническое строковое представление параметров вызова для ключа кеша."""
|
|
62
|
+
if not params:
|
|
63
|
+
return "{}"
|
|
64
|
+
try:
|
|
65
|
+
return orjson.dumps(params, option=orjson.OPT_SORT_KEYS).decode("utf-8")
|
|
66
|
+
except Exception:
|
|
67
|
+
return str(params)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(slots=True)
|
|
71
|
+
class ServerCacheEntry:
|
|
72
|
+
"""Запись в серверном L1-кеше (RAM)."""
|
|
73
|
+
|
|
74
|
+
cache_key: str
|
|
75
|
+
method_name: str
|
|
76
|
+
scope: str # "public" | "user"
|
|
77
|
+
user_id: int | None
|
|
78
|
+
result: Any
|
|
79
|
+
etag: str
|
|
80
|
+
tables: frozenset[str]
|
|
81
|
+
created_at: float
|
|
82
|
+
expires_at: float
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
BroadcastCallback = Callable[[str, dict[str, Any]], Coroutine[Any, Any, None]]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class CacheManager:
|
|
89
|
+
"""
|
|
90
|
+
Высокоскоростной in-memory движок кеширования, ETag-валидации и реактивной инвалидации.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(self, max_l1_entries: int = 4096) -> None:
|
|
94
|
+
self.config: CacheConfig = CacheConfig()
|
|
95
|
+
self.max_l1_entries: int = max_l1_entries
|
|
96
|
+
self._l1: OrderedDict[str, ServerCacheEntry] = OrderedDict()
|
|
97
|
+
self._table_to_keys: dict[str, set[str]] = {}
|
|
98
|
+
self._table_to_methods: dict[str, set[str]] = {}
|
|
99
|
+
self._method_to_keys: dict[str, set[str]] = {}
|
|
100
|
+
self._idempotency: OrderedDict[str, tuple[float, Any]] = OrderedDict()
|
|
101
|
+
self._max_idempotency: int = 2048
|
|
102
|
+
self._idempotency_ttl: float = 900.0 # 15 минут
|
|
103
|
+
self.hits: int = 0
|
|
104
|
+
self.misses: int = 0
|
|
105
|
+
self.not_modified_hits: int = 0
|
|
106
|
+
self.invalidations: int = 0
|
|
107
|
+
self._broadcast_cb: BroadcastCallback | None = None
|
|
108
|
+
|
|
109
|
+
def set_broadcast_callback(self, cb: BroadcastCallback | None) -> None:
|
|
110
|
+
"""Устанавливает функцию широковещательной рассылки событий всем WebSocket-сессиям."""
|
|
111
|
+
self._broadcast_cb = cb
|
|
112
|
+
|
|
113
|
+
def get_rule(self, method_name: str) -> CacheRule | None:
|
|
114
|
+
"""Мгновенно возвращает правило для метода за O(1)."""
|
|
115
|
+
if not self.config.enabled:
|
|
116
|
+
return None
|
|
117
|
+
return self.config.rules.get(method_name)
|
|
118
|
+
|
|
119
|
+
def build_cache_key(
|
|
120
|
+
self,
|
|
121
|
+
method_name: str,
|
|
122
|
+
scope: str,
|
|
123
|
+
user_id: int | None,
|
|
124
|
+
params: dict[str, Any] | list[Any] | None,
|
|
125
|
+
) -> str:
|
|
126
|
+
uid_part = str(user_id or 0) if scope == "user" else "0"
|
|
127
|
+
return f"{scope}:{uid_part}:{method_name}:{make_canonical_params(params)}"
|
|
128
|
+
|
|
129
|
+
def get_entry(self, cache_key: str) -> ServerCacheEntry | None:
|
|
130
|
+
"""Возвращает запись из L1-кеша (проверяя срок действия для стратегии 'ttl')."""
|
|
131
|
+
if not self.config.enabled:
|
|
132
|
+
return None
|
|
133
|
+
entry = self._l1.get(cache_key)
|
|
134
|
+
if entry is None:
|
|
135
|
+
self.misses += 1
|
|
136
|
+
return None
|
|
137
|
+
now = time.monotonic()
|
|
138
|
+
rule = self.config.rules.get(entry.method_name)
|
|
139
|
+
if rule is not None and rule.strategy == "ttl" and now > entry.expires_at:
|
|
140
|
+
self._remove_key(cache_key)
|
|
141
|
+
self.misses += 1
|
|
142
|
+
return None
|
|
143
|
+
self._l1.move_to_end(cache_key)
|
|
144
|
+
self.hits += 1
|
|
145
|
+
return entry
|
|
146
|
+
|
|
147
|
+
def put_entry(
|
|
148
|
+
self,
|
|
149
|
+
cache_key: str,
|
|
150
|
+
method_name: str,
|
|
151
|
+
scope: str,
|
|
152
|
+
user_id: int | None,
|
|
153
|
+
result: Any,
|
|
154
|
+
tables: set[str],
|
|
155
|
+
ttl_sec: int = 300,
|
|
156
|
+
) -> ServerCacheEntry:
|
|
157
|
+
"""Сохраняет результат выполнения RPC-метода в серверный L1-кеш и связывает его с таблицами БД."""
|
|
158
|
+
now = time.monotonic()
|
|
159
|
+
etag = compute_etag(result)
|
|
160
|
+
frozen_tables = frozenset(tables)
|
|
161
|
+
entry = ServerCacheEntry(
|
|
162
|
+
cache_key=cache_key,
|
|
163
|
+
method_name=method_name,
|
|
164
|
+
scope=scope,
|
|
165
|
+
user_id=user_id,
|
|
166
|
+
result=result,
|
|
167
|
+
etag=etag,
|
|
168
|
+
tables=frozen_tables,
|
|
169
|
+
created_at=now,
|
|
170
|
+
expires_at=now + max(1, ttl_sec),
|
|
171
|
+
)
|
|
172
|
+
if cache_key in self._l1:
|
|
173
|
+
self._remove_key(cache_key)
|
|
174
|
+
|
|
175
|
+
self._l1[cache_key] = entry
|
|
176
|
+
self._method_to_keys.setdefault(method_name, set()).add(cache_key)
|
|
177
|
+
for tbl in frozen_tables:
|
|
178
|
+
self._table_to_keys.setdefault(tbl, set()).add(cache_key)
|
|
179
|
+
self._table_to_methods.setdefault(tbl, set()).add(method_name)
|
|
180
|
+
|
|
181
|
+
while len(self._l1) > self.max_l1_entries:
|
|
182
|
+
oldest_key, _ = next(iter(self._l1.items()))
|
|
183
|
+
self._remove_key(oldest_key)
|
|
184
|
+
|
|
185
|
+
return entry
|
|
186
|
+
|
|
187
|
+
def _remove_key(self, cache_key: str) -> None:
|
|
188
|
+
entry = self._l1.pop(cache_key, None)
|
|
189
|
+
if entry is None:
|
|
190
|
+
return
|
|
191
|
+
m_keys = self._method_to_keys.get(entry.method_name)
|
|
192
|
+
if m_keys is not None:
|
|
193
|
+
m_keys.discard(cache_key)
|
|
194
|
+
for tbl in entry.tables:
|
|
195
|
+
t_keys = self._table_to_keys.get(tbl)
|
|
196
|
+
if t_keys is not None:
|
|
197
|
+
t_keys.discard(cache_key)
|
|
198
|
+
|
|
199
|
+
def invalidate_tables(self, mutated_tables: set[str] | frozenset[str]) -> list[str]:
|
|
200
|
+
"""
|
|
201
|
+
Сбрасывает все записи L1-кеша, которые читали из измененных таблиц `mutated_tables`.
|
|
202
|
+
Возвращает список затронутых RPC-методов и инициирует WebSocket-рассылку `$cache.invalidate`.
|
|
203
|
+
"""
|
|
204
|
+
if not mutated_tables:
|
|
205
|
+
return []
|
|
206
|
+
|
|
207
|
+
affected_methods: set[str] = set()
|
|
208
|
+
keys_to_remove: set[str] = set()
|
|
209
|
+
|
|
210
|
+
for tbl in mutated_tables:
|
|
211
|
+
if tbl.startswith("pf_"):
|
|
212
|
+
continue
|
|
213
|
+
t_keys = self._table_to_keys.get(tbl)
|
|
214
|
+
if t_keys:
|
|
215
|
+
keys_to_remove.update(t_keys)
|
|
216
|
+
t_methods = self._table_to_methods.get(tbl)
|
|
217
|
+
if t_methods:
|
|
218
|
+
affected_methods.update(t_methods)
|
|
219
|
+
|
|
220
|
+
for k in keys_to_remove:
|
|
221
|
+
self._remove_key(k)
|
|
222
|
+
|
|
223
|
+
if keys_to_remove or affected_methods:
|
|
224
|
+
self.invalidations += 1
|
|
225
|
+
|
|
226
|
+
methods_list = sorted(affected_methods)
|
|
227
|
+
if methods_list and self._broadcast_cb is not None:
|
|
228
|
+
try:
|
|
229
|
+
loop = asyncio.get_running_loop()
|
|
230
|
+
loop.create_task(
|
|
231
|
+
self._broadcast_cb(
|
|
232
|
+
"$cache.invalidate",
|
|
233
|
+
{
|
|
234
|
+
"methods": methods_list,
|
|
235
|
+
"tables": sorted(t for t in mutated_tables if not t.startswith("pf_")),
|
|
236
|
+
"epoch": self.config.cache_epoch,
|
|
237
|
+
},
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
except RuntimeError:
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
return methods_list
|
|
244
|
+
|
|
245
|
+
def invalidate_methods(self, method_names: list[str] | set[str]) -> None:
|
|
246
|
+
"""Принудительно очищает L1-кеш для указанных методов."""
|
|
247
|
+
keys_to_remove: set[str] = set()
|
|
248
|
+
for m in method_names:
|
|
249
|
+
m_keys = self._method_to_keys.get(m)
|
|
250
|
+
if m_keys:
|
|
251
|
+
keys_to_remove.update(m_keys)
|
|
252
|
+
for k in keys_to_remove:
|
|
253
|
+
self._remove_key(k)
|
|
254
|
+
|
|
255
|
+
def clear_l1(self) -> None:
|
|
256
|
+
"""Полная очистка серверного L1-кеша."""
|
|
257
|
+
self._l1.clear()
|
|
258
|
+
self._table_to_keys.clear()
|
|
259
|
+
self._method_to_keys.clear()
|
|
260
|
+
|
|
261
|
+
def check_idempotency(self, key: str) -> tuple[bool, Any]:
|
|
262
|
+
"""Проверяет, выполнялась ли уже мутация с данным `$idempotency_key`."""
|
|
263
|
+
if not key:
|
|
264
|
+
return False, None
|
|
265
|
+
now = time.monotonic()
|
|
266
|
+
item = self._idempotency.get(key)
|
|
267
|
+
if item is None:
|
|
268
|
+
return False, None
|
|
269
|
+
expires_at, saved_result = item
|
|
270
|
+
if now > expires_at:
|
|
271
|
+
self._idempotency.pop(key, None)
|
|
272
|
+
return False, None
|
|
273
|
+
self._idempotency.move_to_end(key)
|
|
274
|
+
return True, saved_result
|
|
275
|
+
|
|
276
|
+
def save_idempotency(self, key: str, result: Any) -> None:
|
|
277
|
+
"""Сохраняет результат успешной мутации по `$idempotency_key`."""
|
|
278
|
+
if not key:
|
|
279
|
+
return
|
|
280
|
+
now = time.monotonic()
|
|
281
|
+
self._idempotency[key] = (now + self._idempotency_ttl, result)
|
|
282
|
+
self._idempotency.move_to_end(key)
|
|
283
|
+
while len(self._idempotency) > self._max_idempotency:
|
|
284
|
+
self._idempotency.popitem(last=False)
|
|
285
|
+
|
|
286
|
+
def stats(self) -> dict[str, Any]:
|
|
287
|
+
"""Возвращает статистику работы серверного L1-кеша для панели управления."""
|
|
288
|
+
total = self.hits + self.misses
|
|
289
|
+
hit_rate = round((self.hits / total) * 100, 1) if total > 0 else 0.0
|
|
290
|
+
return {
|
|
291
|
+
"l1_entries": len(self._l1),
|
|
292
|
+
"tracked_tables": sorted(self._table_to_methods.keys()),
|
|
293
|
+
"hits": self.hits,
|
|
294
|
+
"misses": self.misses,
|
|
295
|
+
"not_modified_hits": self.not_modified_hits,
|
|
296
|
+
"invalidations": self.invalidations,
|
|
297
|
+
"hit_rate_pct": hit_rate,
|
|
298
|
+
"cache_epoch": self.config.cache_epoch,
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# Глобальный синглтон менеджера кеша
|
|
303
|
+
cache_manager = CacheManager()
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
async def load_cache_from_db(session: AsyncSession) -> CacheConfig:
|
|
307
|
+
"""
|
|
308
|
+
Загружает глобальные настройки (`pf_cache_config`) и правила методов (`pf_cache_rules`)
|
|
309
|
+
из БД в оперативную память `cache_manager`.
|
|
310
|
+
"""
|
|
311
|
+
cfg_row = (await session.execute(select(CacheConfigRecord).where(CacheConfigRecord.id == 1))).scalar_one_or_none()
|
|
312
|
+
if cfg_row is None:
|
|
313
|
+
cfg_row = CacheConfigRecord(
|
|
314
|
+
id=1,
|
|
315
|
+
enabled=True,
|
|
316
|
+
liefi_timeout_ms=2500,
|
|
317
|
+
max_media_mb=250,
|
|
318
|
+
max_rpc_entries=2000,
|
|
319
|
+
cache_epoch=1,
|
|
320
|
+
)
|
|
321
|
+
session.add(cfg_row)
|
|
322
|
+
await session.commit()
|
|
323
|
+
|
|
324
|
+
rule_rows = (await session.execute(select(CacheRuleRecord))).scalars().all()
|
|
325
|
+
rules_map: dict[str, CacheRule] = {}
|
|
326
|
+
for r in rule_rows:
|
|
327
|
+
rules_map[r.method_name] = CacheRule(
|
|
328
|
+
method_name=r.method_name,
|
|
329
|
+
cache_enabled=bool(r.cache_enabled),
|
|
330
|
+
strategy=r.strategy or "auto",
|
|
331
|
+
ttl_sec=int(r.ttl_sec),
|
|
332
|
+
prefetch_media=bool(r.prefetch_media),
|
|
333
|
+
preload_on_boot=bool(r.preload_on_boot),
|
|
334
|
+
offline_outbox=bool(r.offline_outbox),
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
cache_manager.config = CacheConfig(
|
|
338
|
+
enabled=bool(cfg_row.enabled),
|
|
339
|
+
liefi_timeout_ms=int(cfg_row.liefi_timeout_ms),
|
|
340
|
+
max_media_mb=int(cfg_row.max_media_mb),
|
|
341
|
+
max_rpc_entries=int(cfg_row.max_rpc_entries),
|
|
342
|
+
cache_epoch=int(cfg_row.cache_epoch),
|
|
343
|
+
rules=rules_map,
|
|
344
|
+
)
|
|
345
|
+
return cache_manager.config
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
async def save_cache_to_db(
|
|
349
|
+
session: AsyncSession,
|
|
350
|
+
config_data: dict[str, Any],
|
|
351
|
+
rules_list: list[dict[str, Any]],
|
|
352
|
+
) -> CacheConfig:
|
|
353
|
+
"""
|
|
354
|
+
Атомарно сохраняет глобальные настройки и правила методов в БД,
|
|
355
|
+
обновляет in-memory конфигурацию и рассылает обновленный манифест клиентам.
|
|
356
|
+
"""
|
|
357
|
+
cfg_row = (await session.execute(select(CacheConfigRecord).where(CacheConfigRecord.id == 1))).scalar_one_or_none()
|
|
358
|
+
if cfg_row is None:
|
|
359
|
+
cfg_row = CacheConfigRecord(id=1)
|
|
360
|
+
session.add(cfg_row)
|
|
361
|
+
|
|
362
|
+
cfg_row.enabled = bool(config_data.get("enabled", True))
|
|
363
|
+
cfg_row.liefi_timeout_ms = max(500, min(30000, int(config_data.get("liefi_timeout_ms", 2500))))
|
|
364
|
+
cfg_row.max_media_mb = max(10, min(2048, int(config_data.get("max_media_mb", 250))))
|
|
365
|
+
cfg_row.max_rpc_entries = max(100, min(50000, int(config_data.get("max_rpc_entries", 2000))))
|
|
366
|
+
|
|
367
|
+
await session.execute(delete(CacheRuleRecord))
|
|
368
|
+
|
|
369
|
+
new_rules_map: dict[str, CacheRule] = {}
|
|
370
|
+
for item in rules_list:
|
|
371
|
+
m_name = str(item.get("method_name", "")).strip()
|
|
372
|
+
if not m_name:
|
|
373
|
+
continue
|
|
374
|
+
c_enabled = bool(item.get("cache_enabled", False))
|
|
375
|
+
strategy = str(item.get("strategy", "auto")).strip().lower()
|
|
376
|
+
if strategy not in ("auto", "ttl"):
|
|
377
|
+
strategy = "auto"
|
|
378
|
+
ttl_sec = max(1, min(604800, int(item.get("ttl_sec", 300))))
|
|
379
|
+
prefetch_media = bool(item.get("prefetch_media", False))
|
|
380
|
+
preload_on_boot = bool(item.get("preload_on_boot", False))
|
|
381
|
+
offline_outbox = bool(item.get("offline_outbox", False))
|
|
382
|
+
|
|
383
|
+
if c_enabled or prefetch_media or preload_on_boot or offline_outbox:
|
|
384
|
+
rec = CacheRuleRecord(
|
|
385
|
+
method_name=m_name,
|
|
386
|
+
cache_enabled=c_enabled,
|
|
387
|
+
strategy=strategy,
|
|
388
|
+
ttl_sec=ttl_sec,
|
|
389
|
+
prefetch_media=prefetch_media,
|
|
390
|
+
preload_on_boot=preload_on_boot,
|
|
391
|
+
offline_outbox=offline_outbox,
|
|
392
|
+
)
|
|
393
|
+
session.add(rec)
|
|
394
|
+
new_rules_map[m_name] = CacheRule(
|
|
395
|
+
method_name=m_name,
|
|
396
|
+
cache_enabled=c_enabled,
|
|
397
|
+
strategy=strategy,
|
|
398
|
+
ttl_sec=ttl_sec,
|
|
399
|
+
prefetch_media=prefetch_media,
|
|
400
|
+
preload_on_boot=preload_on_boot,
|
|
401
|
+
offline_outbox=offline_outbox,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
await session.commit()
|
|
405
|
+
|
|
406
|
+
cache_manager.config = CacheConfig(
|
|
407
|
+
enabled=bool(cfg_row.enabled),
|
|
408
|
+
liefi_timeout_ms=int(cfg_row.liefi_timeout_ms),
|
|
409
|
+
max_media_mb=int(cfg_row.max_media_mb),
|
|
410
|
+
max_rpc_entries=int(cfg_row.max_rpc_entries),
|
|
411
|
+
cache_epoch=int(cfg_row.cache_epoch),
|
|
412
|
+
rules=new_rules_map,
|
|
413
|
+
)
|
|
414
|
+
cache_manager.clear_l1()
|
|
415
|
+
|
|
416
|
+
if cache_manager._broadcast_cb is not None:
|
|
417
|
+
await cache_manager._broadcast_cb(
|
|
418
|
+
"$cache.config_updated",
|
|
419
|
+
cache_manager.config.to_public_manifest(),
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
return cache_manager.config
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
async def purge_all_cache(session: AsyncSession) -> int:
|
|
426
|
+
"""
|
|
427
|
+
Очищает серверный L1-кеш, увеличивает `cache_epoch` в БД и рассылает сигнал `$cache.purge` всем клиентам.
|
|
428
|
+
"""
|
|
429
|
+
cfg_row = (await session.execute(select(CacheConfigRecord).where(CacheConfigRecord.id == 1))).scalar_one_or_none()
|
|
430
|
+
if cfg_row is None:
|
|
431
|
+
cfg_row = CacheConfigRecord(id=1, cache_epoch=2)
|
|
432
|
+
session.add(cfg_row)
|
|
433
|
+
else:
|
|
434
|
+
cfg_row.cache_epoch = int(cfg_row.cache_epoch) + 1
|
|
435
|
+
|
|
436
|
+
await session.commit()
|
|
437
|
+
cache_manager.config.cache_epoch = int(cfg_row.cache_epoch)
|
|
438
|
+
cache_manager.clear_l1()
|
|
439
|
+
|
|
440
|
+
if cache_manager._broadcast_cb is not None:
|
|
441
|
+
await cache_manager._broadcast_cb(
|
|
442
|
+
"$cache.purge",
|
|
443
|
+
{"cache_epoch": cache_manager.config.cache_epoch},
|
|
444
|
+
)
|
|
445
|
+
|
|
446
|
+
return cache_manager.config.cache_epoch
|