From 3841e93e32e5baa1e4f8c4d45f8cbdbd44c2870d Mon Sep 17 00:00:00 2001 From: Asmin Studios Date: Fri, 30 Oct 2026 03:20:21 +0100 Subject: [PATCH] =?UTF-8?q?1.0.3=20-=20poprawa=20wydajno=C5=9Bci=20panelu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 5 +++++ RELEASE_NOTES.md | 2 +- VERSION | 2 +- app/core/audit.py | 1 + app/core/auth.py | 5 +++-- app/core/preferences.py | 20 ++++++++++++++------ app/core/settings.py | 2 +- app/main.py | 10 +++++----- app/static/js/app.js | 16 +++++++++++----- scripts/install.sh | 2 +- tests/test_help_localization.py | 2 +- tests/test_performance_changes.py | 28 ++++++++++++++++++++++++++++ tests/test_release_0404.py | 2 +- 13 files changed, 73 insertions(+), 24 deletions(-) create mode 100644 tests/test_performance_changes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 449c621..eed9453 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## v1.0.3 + +- Ograniczono odświeżanie panelu w ukrytych kartach i liczbę odczytów bazy danych. +- Przyspieszono wyszukiwanie historii połączeń oraz zmieniono domyślny interwał odświeżania nowych instalacji na 10 sekund. + ## v1.0.2 - Poprawiono wybór marki i przypisywanie uprawnień do sieci. diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index f063122..6b0acac 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1 +1 @@ -Fixes bugs and improves network configuration, user permissions and branding. +Improves panel performance and reduces unnecessary background refreshes. diff --git a/VERSION b/VERSION index 6d7de6e..21e8796 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.2 +1.0.3 diff --git a/app/core/audit.py b/app/core/audit.py index 9aa05b9..88d0d50 100644 --- a/app/core/audit.py +++ b/app/core/audit.py @@ -98,6 +98,7 @@ def init_audit_database() -> None: details TEXT NOT NULL DEFAULT '' ); CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at DESC); + CREATE INDEX IF NOT EXISTS idx_audit_connection_lookup ON audit_log(action, object, created_at DESC, id DESC); CREATE TABLE IF NOT EXISTS audit_wg_connection_state ( interface TEXT NOT NULL, public_key TEXT NOT NULL, diff --git a/app/core/auth.py b/app/core/auth.py index 0080e1a..b36c139 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -76,8 +76,9 @@ def init_database() -> None: conn.execute("ALTER TABLE user_access ADD COLUMN permissions TEXT NOT NULL DEFAULT '{}'") -def get_user_access(user_id: int) -> dict[str, Any]: - init_database() +def get_user_access(user_id: int, *, initialize: bool = True) -> dict[str, Any]: + if initialize: + init_database() with _connect() as conn: row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone() if row is None: diff --git a/app/core/preferences.py b/app/core/preferences.py index 22d1e7d..9858672 100644 --- a/app/core/preferences.py +++ b/app/core/preferences.py @@ -13,9 +13,8 @@ DEFAULT_BACKUP_RETENTION = 20 def get_branding() -> dict[str, Any]: - return {"name": _get("brand_name", "WGTools-Extended"), - "color": _get("brand_color", "#8f1f27"), - "logo": _get("brand_logo", "")} + values = _get_many({"brand_name": "WGTools-Extended", "brand_color": "#8f1f27", "brand_logo": ""}) + return {"name": values["brand_name"], "color": values["brand_color"], "logo": values["brand_logo"]} def update_branding(name: str, color: str, logo: str) -> dict[str, Any]: @@ -68,6 +67,14 @@ def _get(key: str, default: str) -> str: return str(row["value"]) if row else default +def _get_many(defaults: dict[str, str]) -> dict[str, str]: + init_preferences() + with _connect() as conn: + placeholders = ",".join("?" for _ in defaults) + rows = conn.execute(f"SELECT key,value FROM app_settings WHERE key IN ({placeholders})", tuple(defaults)).fetchall() + return {**defaults, **{str(row["key"]): str(row["value"]) for row in rows}} + + def _set(key: str, value: str) -> None: init_preferences() with _connect() as conn: @@ -81,9 +88,10 @@ def _set(key: str, value: str) -> None: def get_preferences() -> dict[str, Any]: - refresh = int(_get("refresh_seconds", str(REFRESH_SECONDS))) - threshold = int(_get("online_threshold_seconds", str(ONLINE_THRESHOLD_SECONDS))) - retention = int(_get("backup_retention", str(DEFAULT_BACKUP_RETENTION))) + values = _get_many({"refresh_seconds": str(REFRESH_SECONDS), "online_threshold_seconds": str(ONLINE_THRESHOLD_SECONDS), "backup_retention": str(DEFAULT_BACKUP_RETENTION)}) + refresh = int(values["refresh_seconds"]) + threshold = int(values["online_threshold_seconds"]) + retention = int(values["backup_retention"]) return { "refresh_seconds": max(2, min(refresh, 60)), "online_threshold_seconds": max(30, min(threshold, 3600)), diff --git a/app/core/settings.py b/app/core/settings.py index f51d92a..4326ba2 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -7,7 +7,7 @@ APP_NAME = "WGTools-Extended" VERSION = Path(__file__).resolve().parents[2].joinpath("VERSION").read_text().strip() WG_INTERFACE = os.getenv("WGTOOLS_INTERFACE", "wg0") HELPER_PATH = os.getenv("WGTOOLS_HELPER", "/usr/local/libexec/wgtools-helper") -REFRESH_SECONDS = int(os.getenv("WGTOOLS_REFRESH_SECONDS", "5")) +REFRESH_SECONDS = int(os.getenv("WGTOOLS_REFRESH_SECONDS", "10")) ONLINE_THRESHOLD_SECONDS = int(os.getenv("WGTOOLS_ONLINE_THRESHOLD_SECONDS", "180")) DATABASE_PATH = os.getenv("WGTOOLS_DATABASE", "/var/lib/wgtools/wgtools.db") SESSION_KEY_FILE = os.getenv("WGTOOLS_SESSION_KEY_FILE", "/var/lib/wgtools/session.key") diff --git a/app/main.py b/app/main.py index 9e255c3..f360eac 100644 --- a/app/main.py +++ b/app/main.py @@ -436,7 +436,7 @@ class NodeSettingsRequest(BaseModel): class AppSettingsRequest(BaseModel): - refresh_seconds: int = Field(default=5, ge=2, le=60) + refresh_seconds: int = Field(default=10, ge=2, le=60) online_threshold_seconds: int = Field(default=180, ge=30, le=3600) backup_retention: int = Field(default=20, ge=1, le=200) @@ -522,7 +522,7 @@ def is_internal_interface(name: str) -> bool: def request_interface(request: Request) -> str: current = getattr(request.state, "current_user", None) - access = get_user_access(int(current["id"])) if current else {"role": "admin", "interfaces": []} + access = getattr(request.state, "access", None) or (get_user_access(int(current["id"])) if current else {"role": "admin", "interfaces": []}) default_iface = (access["interfaces"][0] if access["role"] == "user" and access["interfaces"] else WG_INTERFACE) value = (request.cookies.get("wgtools_interface") or default_iface).strip() if access["role"] == "user" and access["interfaces"] and value not in access["interfaces"]: @@ -580,7 +580,7 @@ def render(request: Request, template: str, page: str, title_key: str) -> HTMLRe "language": language, "messages_json": messages_json, "tr": tr, - "current_user": get_user(int(request.session.get("user_id", 0))) if request.session.get("user_id") else None, + "current_user": getattr(request.state, "current_user", None), "help_sections": get_help_sections(language) if request.state.access['role'] == 'admin' else [], }, headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"}, @@ -649,9 +649,9 @@ async def require_authentication(request: Request, call_next): if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES): return await call_next(request) - users_exist = user_count() > 0 user_id = request.session.get("user_id") current = get_user(int(user_id)) if user_id else None + users_exist = bool(current) or user_count() > 0 if user_id and not current: request.session.clear() if current: @@ -682,7 +682,7 @@ async def require_authentication(request: Request, call_next): return RedirectResponse(url=f"{app_url(request, '/login')}?next={next_path}", status_code=303) request.state.current_user = current - access = get_user_access(int(current["id"])) + access = get_user_access(int(current["id"]), initialize=False) request.state.access = access if access["role"] != "admin": allowed = {"/", "/clients", "/api/interfaces", "/api/snapshot", "/api/metrics/history", "/api/app-settings", "/api/auth/logout", "/api/clients/create", "/api/clients/update", "/api/clients/credentials/rotate", "/api/clients/config", "/api/clients/config/download", "/api/clients/qr", "/api/extended/forwardings", "/api/extended/forwardings/delete"} diff --git a/app/static/js/app.js b/app/static/js/app.js index 3d2a937..053a39d 100644 --- a/app/static/js/app.js +++ b/app/static/js/app.js @@ -11,7 +11,7 @@ return nativeFetch(input, init); }; const page = document.body.dataset.page; - const refreshSeconds = Number(document.body.dataset.refresh || '5'); + const refreshSeconds = Number(document.body.dataset.refresh || '10'); const threshold = Number(document.body.dataset.onlineThreshold || '180'); let snapshot = null; let interfacesData = {interfaces:[], suggested:null}; @@ -2095,6 +2095,7 @@ auditAutoRefreshTimer=setInterval(()=>{ const modal=$('audit-modal'); if(!modal||modal.hidden){stopAuditAutoRefresh();return;} + if(document.hidden)return; loadAudit({showLoading:false}); },interval); } @@ -2993,14 +2994,19 @@ if(page==='dashboard'){ loadMetricsHistory(); if(document.body.dataset.role==='admin')loadDashboardDiagnostics(); - historyTimer=setInterval(loadMetricsHistory,60*1000); - if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(loadDashboardDiagnostics,60*1000); + historyTimer=setInterval(()=>{if(!document.hidden)loadMetricsHistory();},60*1000); + if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadDashboardDiagnostics();},60*1000); } if(page==='server'){ loadServerDiagnostics(); - serverDiagnosticsTimer=setInterval(loadServerDiagnostics,60*1000); + serverDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadServerDiagnostics();},60*1000); + } + if(page!=='settings'){ + let refreshing=false; + const refreshVisible=async()=>{if(document.hidden||refreshing)return;refreshing=true;try{await fetchSnapshot(false);}finally{refreshing=false;}}; + timer=setInterval(refreshVisible,Math.max(2,refreshSeconds)*1000); + document.addEventListener('visibilitychange',()=>{if(!document.hidden)refreshVisible();}); } - if(page!=='settings') timer=setInterval(()=>fetchSnapshot(false),Math.max(2,refreshSeconds)*1000); } boot(); })(); diff --git a/scripts/install.sh b/scripts/install.sh index fdcc196..06cd300 100644 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -78,7 +78,7 @@ if [[ ! -f /etc/wgtools/wgtools.env ]]; then WGTOOLS_INTERFACE=$WG_INTERFACE WGTOOLS_PORT=$WEB_PORT WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper -WGTOOLS_REFRESH_SECONDS=5 +WGTOOLS_REFRESH_SECONDS=10 WGTOOLS_ONLINE_THRESHOLD_SECONDS=180 WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key diff --git a/tests/test_help_localization.py b/tests/test_help_localization.py index 8114f0d..c07388e 100644 --- a/tests/test_help_localization.py +++ b/tests/test_help_localization.py @@ -36,7 +36,7 @@ class HelpTranslationTests(unittest.TestCase): def test_unknown_language_defaults_to_english(self): self.assertEqual(get_help_sections('non-existent-language'), HELP['en']) def test_version(self): - self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.2') + self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.3') if __name__ == '__main__': unittest.main() diff --git a/tests/test_performance_changes.py b/tests/test_performance_changes.py new file mode 100644 index 0000000..864ab48 --- /dev/null +++ b/tests/test_performance_changes.py @@ -0,0 +1,28 @@ +from app.core import audit, preferences + + +def test_settings_are_loaded_in_batches(tmp_path, monkeypatch): + monkeypatch.setattr(preferences, 'DATABASE_PATH', str(tmp_path / 'settings.db')) + original = preferences._connect + connections = [] + def connect(): + connections.append(1) + return original() + monkeypatch.setattr(preferences, '_connect', connect) + assert preferences.get_preferences()['refresh_seconds'] == max(2, min(preferences.REFRESH_SECONDS, 60)) + assert len(connections) == 2 + connections.clear() + assert preferences.get_branding()['name'] == 'WGTools-Extended' + assert len(connections) == 2 + + +def test_historical_connection_lookup_uses_index(tmp_path, monkeypatch): + monkeypatch.setattr(audit, 'DATABASE_PATH', str(tmp_path / 'audit.db')) + audit.init_audit_database() + with audit._connection() as conn: + plan = conn.execute( + "EXPLAIN QUERY PLAN SELECT created_at,details FROM audit_log " + "WHERE action='wireguard.client_connected' AND object=? " + "ORDER BY created_at DESC,id DESC LIMIT 1", ('wg0 · klient',) + ).fetchall() + assert any('idx_audit_connection_lookup' in str(row[3]) for row in plan) diff --git a/tests/test_release_0404.py b/tests/test_release_0404.py index 7fb9b5f..4e94757 100644 --- a/tests/test_release_0404.py +++ b/tests/test_release_0404.py @@ -15,7 +15,7 @@ LANGS = ('en', 'ru', 'de', 'fr', 'it', 'es', 'pl') class CandidateTests(unittest.TestCase): def test_versions_and_locale_fallback_contract(self): - self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.2') + self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.3') en = json.loads((ROOT/'app/locales/en.json').read_text()) self.assertGreaterEqual(len(en), 1098) for lang in LANGS: