#!/usr/bin/env python3 """ Code Keeper Bot - Web Application אפליקציית ווב לניהול וצפייה בקטעי קוד """ import os import copy import logging import hashlib import hmac import json import math import time import mimetypes import uuid import socket from datetime import datetime, timezone from functools import wraps, lru_cache from types import SimpleNamespace from typing import Optional, Dict, Any, List, Tuple, Union from concurrent.futures import ThreadPoolExecutor from flask import Flask, Blueprint, render_template, jsonify, request, session, redirect, url_for, send_file, abort, Response, g, flash, make_response, send_from_directory from markupsafe import Markup import threading import atexit import time as _time from werkzeug.http import http_date, parse_date from werkzeug.utils import secure_filename from werkzeug.security import safe_join from urllib.parse import urlparse, urlunparse, quote as url_quote from werkzeug.exceptions import HTTPException, RequestEntityTooLarge from flask_compress import Compress from pymongo import MongoClient, DESCENDING, ASCENDING from pymongo.errors import PyMongoError from pygments import highlight from pygments.lexers import TextLexer, get_lexer_by_name, guess_lexer from pygments.util import ClassNotFound from pygments.formatters import HtmlFormatter from pygments.styles import get_style_by_name from bs4 import BeautifulSoup from markdown import Markdown from bson import ObjectId from bson.binary import Binary from bson.errors import InvalidId from datetime import timedelta import re import sys from pathlib import Path import secrets import yaml import threading import base64 import traceback import asyncio # --- שם אחד למודול --- # הקובץ הזה הוא המודול ``webapp.app``, וכך מייבאים אותו בכל הקוד (``from webapp.app import get_db`` # ועוד). פייתון מזהה מודול לפי השם שלו ולא לפי הקובץ, ולכן קובץ שנטען בשם אחר — ``app`` מתוך # ``webapp/``, או ``__main__`` בהרצה ישירה — נטען שוב במלואו ברגע שמישהו מבקש ``webapp.app``, וכל # מה שרץ כאן בזמן טעינה רץ פעמיים: תהליכי הרקע, התראת העלייה, רישום ה-jobs. מכאן והלאה שום דבר # לא רץ בעותק שנטען בשם אחר, וייבוא ממודול שבשורש הריפו לא עולה מעל הבלוק הזה: בהרצה ישירה # השורש נכנס לנתיב החיפוש רק בתוכו. if __name__ == "__main__": # ``python app.py`` / ``python webapp/app.py``: טוענים את הקובץ פעם אחת, בשמו, ומריצים ממנו # את שרת הפיתוח. ההמשך של העותק הזה, ``__main__``, לא רץ. _repo_root = str(Path(__file__).resolve().parents[1]) if _repo_root not in sys.path: sys.path.insert(0, _repo_root) # דרך importlib ולא ``from webapp.app import run_dev_server``: ייבוא של שם מתוך הקובץ שבו הוא # מוגדר, בהמשך אותו קובץ, נראה ל-mypy כשם שלא קיים ([attr-defined], ששלב ה-mypy ב-CI נכשל עליו). import importlib importlib.import_module("webapp.app").run_dev_server() raise SystemExit(0) if __name__ != "webapp.app": raise ImportError( f"webapp/app.py נטען בשם {__name__!r} ולא כ-'webapp.app', ולכן כל ייבוא של webapp.app היה טוען " "אותו פעם נוספת. בגוניקורן: webapp.app:app עם --pythonpath לשורש הריפו, כמו ש-scripts/start_webapp.sh " "מפעיל — ו-WEBAPP_WSGI_APP לא מוגדר ל-app:app. בהרצה מקומית: python app.py." ) # Cache עבור בדיקות persistent login _persistent_login_cache = {} _persistent_login_cache_lock = threading.Lock() def _check_persistent_login_cached(user_id: str) -> bool: """בדיקת persistent login עם cache של 60 שניות""" now = time.time() token = request.cookies.get(REMEMBER_COOKIE_NAME) if not token: return False # cache key כולל גם את ה-token (חלק ממנו) כדי להימנע מזיהום בין מכשירים cache_key = f"persistent_{user_id}_{token[:16]}" # בדיקת Cache (בנעילה כדי למנוע race / dict-size-change) with _persistent_login_cache_lock: if cache_key in _persistent_login_cache: cached_value, expires_at = _persistent_login_cache[cache_key] if expires_at > now: return cached_value # Cache miss - בדיקה מול DB has_persistent = False try: db = get_db() doc = db.remember_tokens.find_one({'token': token, 'user_id': user_id}) if doc: exp = doc.get('expires_at') if isinstance(exp, datetime): if exp.tzinfo is None: exp = exp.replace(tzinfo=timezone.utc) has_persistent = exp > datetime.now(timezone.utc) else: try: dt = datetime.fromisoformat(str(exp)) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) has_persistent = dt > datetime.now(timezone.utc) except Exception: has_persistent = False except Exception: has_persistent = False # שמירה ב-cache with _persistent_login_cache_lock: _persistent_login_cache[cache_key] = (has_persistent, now + 60) # ניקוי cache ישן (בטוח) if len(_persistent_login_cache) > 1000: keys_to_remove = [k for k, v in list(_persistent_login_cache.items()) if v[1] < now] for k in keys_to_remove: _persistent_login_cache.pop(k, None) return has_persistent # --- Logging: honor LOG_LEVEL for the WebApp process --- def _env_log_level_name(default: str = "INFO") -> str: raw = os.getenv("LOG_LEVEL") value = (str(raw or "")).strip() if not value: return str(default or "INFO").strip().upper() or "INFO" upper = value.upper() if upper == "WARN": return "WARNING" if upper == "FATAL": return "CRITICAL" if upper.isdigit(): return upper if upper in {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}: return upper return str(default or "INFO").strip().upper() or "INFO" _WEBAPP_LOG_LEVEL_NAME = _env_log_level_name("INFO") try: _WEBAPP_LOG_LEVEL = int(_WEBAPP_LOG_LEVEL_NAME) if _WEBAPP_LOG_LEVEL_NAME.isdigit() else getattr(logging, _WEBAPP_LOG_LEVEL_NAME, logging.INFO) except Exception: _WEBAPP_LOG_LEVEL_NAME = "INFO" _WEBAPP_LOG_LEVEL = logging.INFO _root_logger = logging.getLogger() if not _root_logger.handlers: logging.basicConfig( level=_WEBAPP_LOG_LEVEL, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", handlers=[logging.StreamHandler(sys.stdout)], ) else: _root_logger.setLevel(_WEBAPP_LOG_LEVEL) # שורש הריפו, לנתיבי קבצים (OPENAPI_SPEC_PATH). הוא כבר בנתיב החיפוש: ``webapp.app`` נטען # רק כשהשורש בנתיב, וההרצה הישירה מכניסה אותו בבלוק שבראש הקובץ. ROOT_DIR = str(Path(__file__).resolve().parents[1]) # Best-effort: keep redaction + structlog level in sync with LOG_LEVEL. try: from utils import install_sensitive_filter # noqa: E402 install_sensitive_filter() except Exception: pass try: from observability import setup_structlog_logging as _setup_structlog_logging # noqa: E402 _setup_structlog_logging(_WEBAPP_LOG_LEVEL_NAME) except Exception: pass from http_sync import request as http_request # noqa: E402 # תקרת אורך פתק, לשימוש בתבניות. כמו כל ייבוא ממודול שבשורש הריפו, לא עולה מעל בלוק השם # שבראש הקובץ — tests/test_webapp_import_paths.py נופל אם כן. from sticky_notes_target import MAX_NOTE_CHARS as MAX_NOTE_CHARS_FOR_TEMPLATES # noqa: E402 # ותקרת אורך תגובה בשרשור על פתק — מאותה סיבה, למונה התווים של החלונית. from note_threads import MAX_COMMENT_CHARS as MAX_THREAD_COMMENT_CHARS_FOR_TEMPLATES # noqa: E402 from note_reminder_state import active_reminder_filter # noqa: E402 # השם שבו פתק מוצג בשורה אחת — אותה פונקציה של התראת הפוש וחלונית הפעמון. from sticky_notes_target import NOTE_LABEL_FIELDS, note_label # noqa: E402 # איפה פתק יושב (כרטיס "פתקים אחרונים"): סוג היעד ושדותיו, ושמות הלוחות. והכרטיס מציג רק פתקים # שאינם בארכיון — באותו פילטר שסופר את תקרת הפתקים ושמסתיר את הארכיון בחיפוש. from sticky_notes_target import TARGET_FIELDS, active_notes_filter, note_target_ref # noqa: E402 from note_boards import board_names_by_id # noqa: E402 from utils import TimeUtils, detect_language_from_filename # noqa: E402 # פענוח ה-CRLF ששליחת טופס HTML מוסיפה לערך של textarea. זה לא ניקוי של תוכן: # הוובאפ שומר בדיוק את מה שהמשתמש כתב (ראו services/line_endings.py). from services.line_endings import decode_form_newlines # noqa: E402 # קישור שמוביל לעמוד נפתח בלשונית חדשה, ברנדרר של מצב הקריאה ושל גיבוי התצוגה החיה (``_render_markdown_preview``). from services.md_link_target import LinkTargetExtension # noqa: E402 # מה נחשב Markdown — הכלל של הוובאפ, שגם שרת ה-MCP קורא (ראו services/markdown_files.py). from services.markdown_files import ( # noqa: E402 MARKDOWN_FILE_SUFFIXES as _MARKDOWN_FILE_SUFFIXES, MARKDOWN_LANGUAGES as _MARKDOWN_LANGUAGES, is_markdown_file as _is_markdown_file_shared, ) # אזהרה לצד קוד שמוצג, כשיש בו תווים שמשנים את סדר התצוגה (ראו services/code_service.py). from services.code_service import bidi_warning_for_display # noqa: E402 # קישורי השיתוף של ייצוא ה-HTML המעוצב — שם האוסף והאינדקסים שלו (מודול שורש טהור, ראו styled_shares.py). from styled_shares import ( # noqa: E402 STYLED_SHARES_COLLECTION, STYLED_SHARE_DELETE_KEY_HASH_FIELD, STYLED_SHARE_FORMAT_MARKDOWN, STYLED_SHARE_MAX_MARKDOWN_BYTES, STYLED_SHARE_ORIGIN_FIELD, STYLED_SHARE_ORIGIN_PUBLIC_EDITOR, STYLED_SHARE_TOKEN_RE, markdown_share_fields, new_styled_share_secret, styled_share_delete_key_hash, ) # כללי תאריכי קובץ — מודול שורש טהור. חייב להיות אחרי הכנת ה-sys.path # שלמעלה, ראו tests/test_webapp_import_paths.py. from file_dates import ( # noqa: E402 VERSION_CREATED_AT_FIELD, inherited_created_at, file_was_edited, version_created_at, ) # הגרסה האחרונה של קובץ — מודול שורש טהור, אותו כלל שהגיבוי האישי בוחר בו. ראו file_versions.py from file_versions import LATEST_VERSION_SORT_BY # noqa: E402 # גיל התיאור — מודול שורש טהור, אותו כלל בדיוק שמסלול השמירה של הבוט # ושל ה-MCP מריץ. ראו file_description.py, ובפרט למה הוא כאן ולא ב- # ``database.repository``: ייבוא משם ברמת המודול מפיל את ``import # webapp.app`` בסביבה בלי ``MONGODB_URL``, ויש טסט שאוכף את זה. from file_description import ( # noqa: E402 DESCRIPTION_SET_AT_VERSION_FIELD, FILE_DESCRIPTION_MAX_CHARS, description_stamp_for_new_version, normalized_version, ) # מחיקה רכה — מודול שורש טהור, אותה שאילתה שהבוט מריץ. ראו file_deletion.py from file_deletion import ( # noqa: E402 RECYCLE_BIN_COLLECTIONS, RECYCLE_BIN_TTL_FIELD, SINGLE_ACTIVE_COLLECTIONS, RestoreConflict, is_recycle_bin_ttl_index, purge_files_by_names, recycle_bin_count_stages, recycle_bin_page_stages, recycle_bin_rows_pipeline, resolve_owned_file_names, resolve_trashed_file_names, restore_files_by_names, soft_delete_files_by_names as _soft_delete_files_by_names, ) # ירושת סימון המועדף לגרסה חדשה — מודול שורש בלי חיבור משלו, אותו כלל # שמסלול השמירה של הבוט ושל ה-MCP מריץ. ראו file_favorite.py. from file_favorite import favorite_fields_for_new_version, file_is_favorite # noqa: E402 # חיתוך שורת תגיות ונרמול העדכון המהיר — מודול שורש טהור, החיתוך היחיד # לעריכה, להעלאה ול-quick-update. ראו file_tags.py. from file_tags import normalize_quick_update_tags, split_tags_text # noqa: E402 # כתובת הוובאפ — מודול שורש טהור, הקורא היחיד של ``WEBAPP_URL``, בלי ברירת מחדל. ראו webapp_url.py. from webapp_url import approval_notice, log_webapp_url_status, webapp_base_url_for_request, webapp_url_status # noqa: E402 from user_stats import user_stats # noqa: E402 from webapp.size_format import format_file_size as _format_file_size_shared # שם קובץ בשורה עברית (הפילטר ``file_name``) — התאום של ``utils/file-name.js``. ראו file_name_display.py. from webapp.file_name_display import TEMPLATE_FILTERS as _FILE_NAME_TEMPLATE_FILTERS # noqa: E402 from webapp.activity_tracker import log_user_event # noqa: E402 from webapp.config_radar import build_config_radar_snapshot # noqa: E402 # המסגרת של תצוגת ה-HTML: ה-CSP של ``/raw_html`` ומדווח הגלילה שהפתקים נשענים עליו. from webapp import html_preview_frame # noqa: E402 # הצ'קליסט "צעדים ראשונים" בדשבורד: שמות הדגלים ב-``ui_prefs`` ש-``/api/ui_prefs`` כותב, # והרישום של בחירת ערכה "רק במכשיר הזה". from webapp import first_steps # noqa: E402 from webapp.gallery import GALLERY_SLIDES, share_image as gallery_share_image # noqa: E402 from webapp.legacy_host_redirect import ( # noqa: E402 legacy_redirect_config, legacy_redirect_for, log_legacy_redirect_status, ) from webapp.markdown_editor import THEME_ID as MARKDOWN_EDITOR_THEME_ID, demo_text as markdown_editor_demo_text # noqa: E402 from webapp.markdown_editor import ( # noqa: E402 EXPORT_THEME_IDS as MARKDOWN_EDITOR_EXPORT_THEME_IDS, PUBLIC_SHARE_DAILY_LIMIT as MARKDOWN_EDITOR_PUBLIC_SHARE_DAILY_LIMIT, PUBLIC_SHARE_DAILY_WINDOW as MARKDOWN_EDITOR_PUBLIC_SHARE_DAILY_WINDOW, PUBLIC_SHARE_MAX_BODY_BYTES as MARKDOWN_EDITOR_PUBLIC_SHARE_MAX_BODY_BYTES, PUBLIC_SHARE_RATE_LIMIT as MARKDOWN_EDITOR_PUBLIC_SHARE_RATE_LIMIT, export_hljs_fallback_css as markdown_editor_hljs_fallback_css, export_themes as markdown_editor_export_themes, katex_inline_css as markdown_editor_katex_css, ) from services import observability_dashboard as observability_service # noqa: E402 from services.diff_service import get_diff_service, DiffMode # noqa: E402 from services.db_health_service import ( # noqa: E402 SyncDatabaseHealthService, InvalidCollectionNameError, CollectionAccessDeniedError, MAX_SKIP, clean_db_health_filter_value, ) from services.query_profiler_service import ( # noqa: E402 # ייבוא ברמת המודול ולא בתוך הפונקציה: שם מחלקה ב-``except`` מוערך רק כשחריגה # מגיעה לשם, ולכן שם שאינו קיים היה מתגלה כ-NameError רק בזמן כשל אמיתי. ExplainTimeoutError as _ProfilerExplainTimeout, ProfilerInputError as _ProfilerInputError, ProfilerPagingError, PROFILER_WINDOW_HOURS, ) from services.git_mirror_service import get_mirror_service # noqa: E402 from services.styled_export_service import ( # noqa: E402 COPY_CODE_SCRIPT_CSP_HASH, EDITOR_EXPORT_CONTENT_MARKER_TEXT, export_mermaid_theme, get_export_theme, list_export_presets, markdown_to_html, render_editor_export_skeleton, render_public_editor_share_page, render_styled_export_skeleton, render_styled_html, render_styled_share_page, styled_export_filename, styled_export_title, styled_share_csp, styled_share_page_csp, ) from services.theme_parser_service import ( # noqa: E402 MD_DOC_THEME_UI_CONDITION, build_md_doc_theme_css, exclude_md_doc_theme_from_hljs_css, parse_vscode_theme, validate_theme_json, ) # --- Observability: הרצת פעולות כבדות בת׳רד (תואם Flask sync) --- _OBSERVABILITY_THREADPOOL = ThreadPoolExecutor( max_workers=max(2, min(16, int(os.getenv('OBSERVABILITY_THREADPOOL_WORKERS') or 6))), thread_name_prefix='observability', ) def _run_observability_blocking(func, *args, **kwargs): """מריץ פונקציה כבדה בת׳רד ומחזיר תוצאה (ללא async/await).""" return _OBSERVABILITY_THREADPOOL.submit(func, *args, **kwargs).result() # קונפיגורציה מרכזית (Pydantic Settings) try: # שמירה על יציבות גם בסביבות דוקס/CI from config import config as cfg except Exception: # pragma: no cover cfg = None # --- Smart Projection (Performance) --- # ברירת מחדל למסכי רשימות: אל תמשוך שדות "כבדים" מה-DB. # חשוב: מסכי צפייה/עריכה של קובץ בודד עדיין מושכים מסמך מלא. try: # prefer the canonical list projection from repository layer from database.repository import HEAVY_FIELDS_EXCLUDE_PROJECTION as _HEAVY_FIELDS_EXCLUDE_PROJECTION # type: ignore except Exception: # pragma: no cover - fallback for minimal environments # חייב להישאר זהה לקבוע הקנוני ב-database/repository.py. חסר כאן בעבר raw_data, # כלומר בסביבה מינימלית שדה כבד היה נמשך בשאילתות רשימה בלי שאיש ישים לב. _HEAVY_FIELDS_EXCLUDE_PROJECTION = { "code": 0, "content": 0, "raw_data": 0, "raw_content": 0, "snippetEmbedding": 0, } LIST_EXCLUDE_HEAVY_PROJECTION: Dict[str, int] = dict(_HEAVY_FIELDS_EXCLUDE_PROJECTION) # --- Semantic chunk cleanup --- # מסלולי סל המיחזור כאן כותבים ישירות ל-``db.code_snippets`` ואינם עוברים דרך # ``database/repository.py``, ולכן הם צריכים את אותם helpers בעצמם. בסביבה # מינימלית (בלי שכבת ה-DB) נופלים ל-no-op כדי לא להפיל את טעינת המודול. try: from database.manager import ( # type: ignore delete_snippet_chunks as _delete_snippet_chunks, mark_snippets_for_reindex as _mark_snippets_for_reindex, ) except Exception: # pragma: no cover - fallback for minimal environments def _delete_snippet_chunks(*_args: Any, **_kwargs: Any) -> int: return 0 def _mark_snippets_for_reindex(*_args: Any, **_kwargs: Any) -> int: return 0 def _clear_superseded_chunks(doc: Dict[str, Any], inserted_id: Any) -> None: """מוחק את הצ'אנקים הסמנטיים של הגרסאות הקודמות של אותו קובץ. שמירת גרסה חדשה ב-WebApp אינה מכבה את הגרסה הקודמת (``is_active`` שלה נשאר True), ולכן בלי הקריאה הזו כל גרסה היסטורית נשארת מאונדקסת ומתחרה על מקומות ה-ANN. הקריאה נעשית **אחרי** הכנסה מוצלחת בלבד: מחיקה לפני ההכנסה הייתה מוציאה את הגרסה הנוכחית מהחיפוש הסמנטי אם ההכנסה תיכשל, ושום דבר לא היה מחזיר אותה. ``user_id``/``file_name`` נקראים מהמסמך עצמו כדי שאותה קריאה תתאים לכל מסלולי השמירה ב-WebApp, שלכל אחד מהם שמות משתנים משלו. המחיקה מוגבלת ל-``version`` נמוך מזה של המסמך שנכתב, ולא ל"הכל חוץ ממני": כששתי שמירות של אותו קובץ חופפות, ניקוי של הישנה יכול לרוץ אחרי שהחדשה כבר נשמרה ולמחוק דווקא את הצ'אנקים שלה. בלי ``version`` במסמך לא מוחקים כלום — הג'וב היומי ינקה את הגרסאות הישנות. """ if not inserted_id: return try: user_id = int(doc.get('user_id')) file_name = str(doc.get('file_name') or '') version = int(doc.get('version')) except (TypeError, ValueError): return if not file_name: return _delete_snippet_chunks( user_id, file_name=file_name, exclude_snippet_id=inserted_id, older_than_version=version, ) # --- Smart Projection helpers --- # מסמכים חדשים יכולים להכיל file_size/lines_count (נשמרים בזמן שמירה). # למסמכים ישנים: נחשב ב-DB (בלי להחזיר את `code`) באמצעות $strLenBytes/$split. _MONGO_FILE_SIZE_FROM_CODE = { '$cond': { 'if': {'$and': [ {'$ne': ['$code', None]}, {'$eq': [{'$type': '$code'}, 'string']}, ]}, 'then': {'$strLenBytes': '$code'}, 'else': 0, } } _MONGO_LINES_COUNT_FROM_CODE = { '$cond': { 'if': {'$and': [ {'$ne': ['$code', None]}, {'$eq': [{'$type': '$code'}, 'string']}, ]}, # הערה: $split שומר תאימות טובה מספיק למסך רשימה (לא מושלם לעומת splitlines()). 'then': {'$size': {'$split': ['$code', '\n']}}, 'else': 0, } } _MONGO_ADD_SIZE_LINES_STAGE = { '$addFields': { 'file_size': {'$ifNull': ['$file_size', _MONGO_FILE_SIZE_FROM_CODE]}, 'lines_count': {'$ifNull': ['$lines_count', _MONGO_LINES_COUNT_FROM_CODE]}, } } #: "הקובץ אינו ריק", לפי ``file_size`` השמור. ``None`` מתאים גם לשדה חסר #: (https://www.mongodb.com/docs/manual/tutorial/query-for-null-fields/), #: ומסמך בלי גודל שמור נחשב לא-ריק: אי אפשר לדעת את גודלו בלי למשוך את #: ``code``, והסתרת קובץ של משתמש גרועה מהצגתו. ב-23.9.2026 לכל 1,406 #: המסמכים במסד היה ``file_size`` שמור (קיבוץ לפי ``$type`` של השדה על כל #: ``code_snippets``), ולכן זו רשת ביטחון ולא מקרה חי. _NON_EMPTY_FILE_MATCH: Dict[str, Any] = { '$or': [{'file_size': {'$gt': 0}}, {'file_size': None}], } def _latest_version_per_file_stages( match: Dict[str, Any], *, non_empty_only: bool = True, favorites_only: bool = False, file_match: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: """שלבי "הגרסה האחרונה לכל שם קובץ" — שורה אחת לכל קובץ, בלי גוף הקובץ. כל עריכה יוצרת מסמך חדש ב-``code_snippets``, ולכן מסך רשימה חייב לקבץ לפי ``file_name`` ולקחת את ה-``version`` הגבוה. ``match`` מסנן **גרסאות** לפני הקיבוץ (משתמש, פעיל, שפה, חיפוש, קטגוריה). **הסדר כאן הוא כל העניין: רק ``$match`` רשאי לבוא לפני ההיטלה.** כך מונגו מחיל את הורדת השדות הכבדים כבר בשכבת השאילתה, והמסמכים שמגיעים לקיבוץ קטנים באמת. שלב אחר באמצע — עד 23.9.2026 ישב שם ``$addFields`` שחישב גודל מתוך ``$code`` — מבטל את זה: ההיטלה רצה אז כשלב בצינור, ושם היא **לא** מקטינה את מה שהשלב הבא נספר עליו. נמדד ב-23.9.2026 על הקלאסטר ‏(MongoDB 8.0.32, Atlas Flex), ב-``explain`` במצב ``executionStats``, בשדה ``totalDataSizeSortedBytesEstimate`` של שלב המיון: מיון של אותם 79 מסמכים נספר 2,585,634 בתים בצורה הישנה ו-93,939 כשההיטלה צמודה ל- ``$match``. אצל המשתמש הראשי הגודל המלא של כל הגרסאות היה 35,776,968 בתים (``$bsonSize``), מעל תקרת המיון של האשכול (``internalQueryMaxBlockingSortMemoryUsageBytes``, 33,554,432 לפי ``serverParameters`` שב-explain), ו"שאר קבצים" החזיר 500 עם שגיאה 292. ``allowDiskUse`` **אינו** מציל כאן: *"Atlas Free clusters and Flex clusters don't support writing temporary files to disk. Atlas ignores the ``allowDiskUse`` option"* (https://www.mongodb.com/docs/atlas/reference/free-shared-limitations/). **קיבוץ בלי מיון מקדים.** ``$top`` בוחר את הגרסה הגבוהה בתוך הקיבוץ עצמו (MongoDB 5.2 ומעלה), כך שאין מיון שחוסם על כל הגרסאות — הזיכרון גדל עם מספר הקבצים ולא עם מספר הגרסאות. ``_id`` שובר שוויון בין שתי גרסאות עם אותו מספר, כפי שתיעוד ``$top`` ממליץ. על הנתונים המלאים בפרודקשן, באותה מדידה, הצינור של "כל הקבצים" רץ ב-26ms (``executionTimeMillis``), והמיון של העמוד הראשון נספר 23,738 בתים. גם בעמוד האחרון הוא לא יכול לעבור בהרבה את המטא-דאטה של כל הגרסאות בלי השדות הכבדים — 838,899 בתים ב-``$bsonSize``, פחות מ-3% מהתקרה. **החרגה ולא רשימת שדות מותרים.** ``LIST_EXCLUDE_HEAVY_PROJECTION`` מוריד את הכבדים ומשאיר את השאר, ולכן שדה שיתווסף למסמך יגיע לרשימה בלי שמישהו יזכור להוסיף אותו כאן. ``non_empty_only`` — לסנן קבצים ריקים לפי ``_NON_EMPTY_FILE_MATCH``. הסינון חל על הגרסאות **לפני** הקיבוץ, כך שנבחרת הגרסה האחרונה הלא-ריקה. **כבוי אצל מי שלא סינן קודם** (רשימת הריפואים, הווידג'ט, המועדפים, תצוגת ריפו): הוספת הסינון הייתה משנה את קבוצת התוצאות. ``favorites_only`` — הכלל ברמת הקובץ של ``file_favorite.py``: קובץ נכנס אם **איזושהי** גרסה פעילה שלו מסומנת, והשורה היא הגרסה האחרונה שלו גם כשהיא עצמה לא מסומנת. ``favorited_at`` של השורה הוא הסימון האחרון בקובץ. סינון ``is_favorite`` בתוך ``match`` היה בוחר את האחרונה **מבין המסומנות** — ובפרודקשן נמצאו שני קבצים שבהם זו גרסה ישנה. ``file_match`` — תנאים על **הקובץ**, שנבדקים על הגרסה שהשורה מציגה (האחרונה), אחרי הקיבוץ. כאן יושבים מסנני הקטגוריה — תגית ריפו, "שאר קבצים": אותה שאלה ש-``repo_pipeline`` ב-``files()`` (רשימת הריפואים) שואל כשהוא משייך קובץ לריפו לפי הגרסה האחרונה שלו. ב- ``match`` הם סיננו **גרסאות**, ו-``$top`` בחר את האחרונה **מבין המתאימות**: קובץ שעבר לריפו אחר הוצג גם בישן, בגרסה הישנה, וקובץ ידני שיובא אחר כך מ-GitHub המשיך להופיע ב"שאר קבצים". מאותה סיבה יושב כאן גם החיפוש בשם, בתיאור ובתגיות (``_files_search_file_match``), מאז שהוחלף בו ה-``$text``, שמונגו מחייבת ב-``$match`` הראשון. לפני הקיבוץ נשארים רק התחום (משתמש, גרסאות פעילות, שפה, ובנפתחו לאחרונה — השמות) וסינון הקבצים הריקים (``non_empty_only``, וראו את ההערה ליד ``recent_stages`` ב-``files()``). """ stages: List[Dict[str, Any]] = [{'$match': match}] if non_empty_only: stages.append({'$match': dict(_NON_EMPTY_FILE_MATCH)}) stages.append({'$project': dict(LIST_EXCLUDE_HEAVY_PROJECTION)}) group: Dict[str, Any] = { '_id': '$file_name', 'latest': {'$top': {'sortBy': dict(LATEST_VERSION_SORT_BY), 'output': '$$ROOT'}}, } if favorites_only: # ``$max`` מתעלם מ-null כל עוד יש ערך אחר, ובוליאני משווה לפי סדר # BSON (false < true) — https://www.mongodb.com/docs/manual/reference/operator/aggregation/max/ group['is_favorite'] = {'$max': {'$eq': ['$is_favorite', True]}} group['favorited_at'] = { '$max': {'$cond': [{'$eq': ['$is_favorite', True]}, '$favorited_at', None]}, } stages.append({'$group': group}) stages.append({'$match': {'is_favorite': True}}) # הערך מהמסמך האחרון בממוזג גובר (תיעוד ``$mergeObjects``), ולכן # הסימון ברמת הקובץ דורס את מה שכתוב על הגרסה עצמה. stages.append({'$replaceRoot': {'newRoot': {'$mergeObjects': [ '$latest', {'is_favorite': True, 'favorited_at': '$favorited_at'}, ]}}}) else: stages.append({'$group': group}) stages.append({'$replaceRoot': {'newRoot': '$latest'}}) if file_match: stages.append({'$match': dict(file_match)}) return stages def _files_search_file_match(search_query: str) -> Optional[Dict[str, Any]]: """התיבה "חיפוש לפי שם, תיאור או תגית" בעמוד הקבצים — תנאי על **הקובץ**. כל מילה בשאילתה (מופרדות ברווחים) חייבת להופיע באחד משלושה: שם הקובץ, התיאור, או אחת התגיות — חלק ממילה מספיק, ובלי הבדל בין אותיות גדולות לקטנות. ``#`` בתחילת מילה יורד, כדי ש-``#python`` ימצא את התגית ``python``. ``None`` כשאין מילים — אין מה לסנן. **תוכן הקובץ אינו נבדק, בכוונה.** עד אוקטובר 2026 התיבה הריצה ``$text`` על ``search_text_idx``, שכולל גם את ``code`` — ולכן, בניגוד לטקסט שבתיבה, היא מצאה קבצים שהמילה מופיעה רק בקוד שלהם, בלי להראות איפה, והקובץ שהמילה בתגית שלו נקבר ביניהם. ``$text`` גם מתאים רק מילה שלמה: ``view`` לא מצא את ``view_file.html``. חיפוש בתוכן הוא תפקיד התיבה הראשונה (החיפוש הגלובלי), שמראה גם איפה המילה בקוד. **התנאי נבדק על הגרסה שהשורה מציגה** — הוא נכנס ל-``file_match`` של :func:`_latest_version_per_file_stages`, אחרי הקיבוץ. ב-``$match`` שלפני הקיבוץ הוא היה מסנן **גרסאות**: קובץ שתגית הייתה רק בגרסה ישנה שלו נמצא, ומוצגת הייתה דווקא הגרסה הישנה. אחרי הקיבוץ השדות הכבדים כבר בחוץ, והסינון קורא בדיוק את המסמכים שפתיחת העמוד בלי חיפוש כבר קוראת (``totalDocsExamined`` ב-``explain``, MongoDB 8.0 מקומי על נתונים סינתטיים, 25.10.2026). המילים עוברות ``re.escape``: ``a.b`` מחפש נקודה, ולא "כל תו". ``re.escape`` משאיר NUL כמו שהוא, ו-``$regex`` של מונגו דוחה ביטוי שיש בו NUL ("Regular expression cannot contain an embedded null byte", קוד 2 — נמדד מול MongoDB 8.0 מקומי) — ``/files?q=%00`` הפיל את העמוד. לכן NUL נכתב ``\\x00``: אותו תו, בכתיב ש-PCRE מכיר, בלי NUL במחרוזת עצמה. """ patterns = [ re.escape(term).replace('\x00', r'\x00') for term in (t.lstrip('#') for t in (search_query or '').split()) if term ] clauses = [ {'$or': [ {'file_name': {'$regex': pattern, '$options': 'i'}}, {'description': {'$regex': pattern, '$options': 'i'}}, {'tags': {'$regex': pattern, '$options': 'i'}}, ]} for pattern in patterns ] if not clauses: return None return clauses[0] if len(clauses) == 1 else {'$and': clauses} def _all_of(*conditions: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: """תנאי אחד שכל התנאים שאינם ``None`` חייבים להתקיים בו — או ``None`` כשאין אף אחד.""" present = [c for c in conditions if c] if not present: return None return present[0] if len(present) == 1 else {'$and': present} def _attach_file_size_and_lines(doc: Dict[str, Any], code_value: Any) -> None: """מוסיף file_size/lines_count למסמכי CodeSnippet שנכתבים ישירות ל-DB.""" try: if doc.get("file_size") is not None and doc.get("lines_count") is not None: return except Exception: # אם doc לא מתנהג כמו dict סטנדרטי ננסה בכל זאת pass size_bytes = 0 lines_count = 0 try: if isinstance(code_value, (bytes, bytearray)): size_bytes = int(len(code_value)) try: text = bytes(code_value).decode("utf-8", errors="ignore") except Exception: text = "" # עקביות עם מסלולי MongoDB: ספירה לפי '\n' (כולל newline בסוף). lines_count = int(len(text.split('\n'))) if text else 0 else: try: text = "" if code_value is None else str(code_value) except Exception: text = "" if text: try: size_bytes = int(len(text.encode("utf-8", errors="ignore"))) except Exception: size_bytes = 0 try: lines_count = int(len(text.split('\n'))) except Exception: lines_count = 0 except Exception: size_bytes = 0 lines_count = 0 try: if doc.get("file_size") is None: doc["file_size"] = int(size_bytes) except Exception: doc["file_size"] = int(size_bytes) try: if doc.get("lines_count") is None: doc["lines_count"] = int(lines_count) except Exception: doc["lines_count"] = int(lines_count) def _attach_description_stamp(doc: Dict[str, Any], *previous_docs: Any) -> None: """מוסיף את חותמת גיל התיאור למסמך גרסה שנכתב ישירות ל-DB. האח של :func:`_attach_file_size_and_lines`, ומאותה סיבה בדיוק: חמישה ראוטים בקובץ הזה כותבים ``code_snippets.insert_one`` בעצמם ואינם עוברים ב-``save_code_snippet``, ולכן כל שדה נגזר צריך כאן נקודה אחת שכולם קוראים לה. **הכלל עצמו אינו כאן** — הוא ב-``file_description``, ומשם מריצים אותו גם הבוט וגם ה-MCP; מה שכאן הוא רק החיבור אליו. ``previous_docs`` נבדקים לפי הסדר והראשון שהוא ``dict`` מנצח, בדיוק כמו ב-``inherited_created_at`` — ומאותה סיבה: הראוטים מחזיקים כמה מועמדים ל"המסמך הקודם" (הגרסה האחרונה, המסמך שנטען לעמוד, הגרסה שמשחזרים), ומיזוג ביניהם היה מאפשר למסמך בלי תיאור לדרוס את זה שיש לו. **המועמד הנכון הוא הגרסה שהתיאור הוצג ממנה עד עכשיו.** ``None`` מהכלל פירושו "אל תכתוב את השדה", ולכן אין כאן ענף ``else`` שכותב ``None``: מסמך בלי השדה הוא מה שמסלולי הקריאה מתרגמים לגיל ``null``. """ previous: Any = None for candidate in previous_docs: if isinstance(candidate, dict): previous = candidate break stamp = description_stamp_for_new_version( previous, doc.get("description"), doc.get("version") ) if stamp is not None: doc[DESCRIPTION_SET_AT_VERSION_FIELD] = stamp DEFAULT_LANGUAGE_CHOICES = [ "python", "javascript", "typescript", "html", "css", "sql", "json", "markdown", "xml", "shell", "bash", "go", "java", "yaml", "csharp", ] def _load_supported_languages_from_config() -> List[str]: try: configured = list((cfg.SUPPORTED_LANGUAGES if cfg else []) or []) if configured: return configured except Exception: pass return list(DEFAULT_LANGUAGE_CHOICES) def _build_language_choices(user_langs: Optional[List[str]] = None) -> List[str]: """איחוד שפות: נתונים קיימים של המשתמש + ברירת מחדל מהקונפיג.""" dedup: Dict[str, str] = {} def _add_languages(candidates: List[str]) -> None: for lang in candidates or []: if not lang: continue lang_str = str(lang).strip() if not lang_str: continue if lang_str.lower() == "text": continue key = lang_str.lower() dedup.setdefault(key, lang_str) _add_languages(user_langs or []) _add_languages(_load_supported_languages_from_config()) return [dedup[key] for key in sorted(dedup.keys())] def _cfg_or_env(attr: str, default: Any = None, *, env_name: str | None = None) -> Any: """משיג ערך מהקונפיג או מהסביבה, כולל תמיכה ב-Stubs פשוטים בטסטים.""" env_key = env_name or attr value = None if cfg is not None: value = getattr(cfg, attr, None) if value in (None, '') and env_key: env_val = os.getenv(env_key) if env_val not in (None, ''): value = env_val if value in (None, ''): value = default return value # Search engine & types try: from search_engine import ( search_engine, SearchType, SearchFilter, SortOrder, semantic_search, ) except Exception: search_engine = None class _Missing: pass SearchType = _Missing SearchFilter = _Missing SortOrder = _Missing semantic_search = None # Structured logging (optional and safe-noop fallbacks) try: from observability import ( emit_event, bind_request_id, generate_request_id, bind_user_context, bind_command, get_observability_context, ) except Exception: # pragma: no cover def emit_event(event: str, severity: str = "info", **fields): return None def bind_request_id(request_id: str) -> None: return None def generate_request_id() -> str: try: return str(int(time.time() * 1000))[-8:] except Exception: return "" def bind_user_context(*_a, **_k): return None def bind_command(_identifier: str | None = None) -> None: return None def get_observability_context() -> Dict[str, Any]: return {} # Alertmanager forwarding (optional) try: from alert_forwarder import forward_alerts as _forward_alerts except Exception: # pragma: no cover def _forward_alerts(_alerts): return None # Optional monitoring & resilience try: from prometheus_client import Counter, Histogram, Gauge, generate_latest, REGISTRY except Exception: Counter = Histogram = Gauge = generate_latest = REGISTRY = None try: from tenacity import retry, stop_after_attempt, wait_exponential except Exception: retry = stop_after_attempt = wait_exponential = None try: import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration _SENTRY_AVAILABLE = True except Exception: _SENTRY_AVAILABLE = False # Cache (Redis) – שימוש במנהל הקאש המרכזי של הפרויקט try: from cache_manager import cache # noqa: E402 except Exception: from typing import Any, Optional, Dict, Union class _NoCache: is_enabled: bool = False def get(self, key: str) -> None: # pragma: no cover - fallback only return None def set(self, key: str, value: Any, expire_seconds: int = 60) -> bool: # pragma: no cover - fallback only return False def set_dynamic(self, key: str, value: Any, content_type: str, context: Optional[Dict[str, Any]] = None) -> bool: # pragma: no cover - fallback only return False def delete(self, key: str) -> bool: # pragma: no cover - fallback only return False def delete_pattern(self, pattern: str) -> int: # pragma: no cover - fallback only return 0 def invalidate_user_cache(self, user_id: int) -> int: # pragma: no cover - fallback only return 0 def clear_all(self) -> int: # pragma: no cover - fallback only return 0 def invalidate_file_related(self, file_id: str, user_id: Optional[Union[int, str]] = None) -> int: # pragma: no cover - fallback only return 0 def clear_stale(self, max_scan: int = 1000, ttl_seconds_threshold: int = 60) -> int: # pragma: no cover - fallback only return 0 def get_stats(self) -> Dict[str, Any]: # pragma: no cover - fallback only return {"enabled": False} cache = _NoCache() # יצירת האפליקציה app = Flask(__name__) app.secret_key = os.getenv('SECRET_KEY', 'dev-secret-key-change-in-production') app.permanent_session_lifetime = timedelta(days=30) # סשן נשמר ל-30 יום app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 31536000 # שנה לסטטיקה app.config['COMPRESS_ALGORITHM'] = ['br', 'gzip'] app.config['COMPRESS_LEVEL'] = 6 app.config['COMPRESS_BR_LEVEL'] = 5 Compress(app) # ראשון מבין ה-``before_request``, ולכן רשום כאן, מיד אחרי יצירת האפליקציה: בקשה שמופנית לא מגיעה להתחברות # האוטומטית מ-``remember_me`` (שאילתה למסד), למגבלת הקצב או ל-handler — למשל ``GET`` של פעולת אדמין לא רץ בכתובת # הישנה. Flask מריץ את ה-``before_request`` של האפליקציה לפי סדר הרישום, ותשובה שאחד מהם מחזיר עוצרת את השאר # (``Flask.preprocess_request``). ``tests/test_legacy_host_redirect.py`` בודק שהוא ראשון. @app.before_request def _redirect_legacy_host(): """מפנה דף שנפתח בכתובת ישנה של ה-WebApp לאותו נתיב ב-``WEBAPP_URL``. מה מופנה ומה לא — ב-``webapp/legacy_host_redirect.py``.""" decision = legacy_redirect_for(request) if decision is None: return None location, status_code = decision return redirect(location, code=status_code) @app.get("/favicon.ico") def favicon(): """favicon ברירת מחדל (לכל האתר). דפים ספציפיים יכולים להגדיר icon אחר ב-HTML.""" return send_from_directory(app.static_folder, "favicon.ico", mimetype="image/x-icon", max_age=31536000) @app.get("/google7bb000f75b7bf329.html") def google_site_verification(): """קובץ אימות הבעלות על האתר ב-Google Search Console (שיטת "HTML file upload") — ציבורי, בלי התחברות. גוגל מוריד את הקובץ בלי סשן ובלי לעקוב אחרי הפניות, ודורש שהתוכן לא ישתנה. הוא גם חוזר לבדוק מדי פעם, ומחיקה של הנתיב מבטלת את האימות. מקור: https://support.google.com/webmasters/answer/9008080 (נקרא באוקטובר 2026). הנתיב והתוכן מוצמדים ב-``tests/test_google_site_verification.py``. """ return Response("google-site-verification: google7bb000f75b7bf329.html", mimetype="text/html") # OpenTelemetry (best-effort, fail-open) try: from observability_otel import setup_telemetry as _setup_otel # type: ignore _setup_otel( service_name=str(os.getenv("OTEL_SERVICE_NAME") or "codebot-webapp"), service_version=os.getenv("SERVICE_VERSION") or os.getenv("RENDER_GIT_COMMIT") or None, environment=os.getenv("ENVIRONMENT") or os.getenv("ENV") or None, flask_app=app, ) except Exception: pass # לוגר מודולרי לשימוש פנימי logger = logging.getLogger(__name__) # Jobs Monitor: רישום Jobs מוכרים ל-UI/API (fail-open) try: from services.register_jobs import register_all_jobs # noqa: E402 register_all_jobs() except Exception: pass # --- Embedding model health-check (best-effort, background) --- # כדי לא להיתקע על מודל שירד מהמדף (404), נריץ בדיקה קצרה ונאפשר שדרוג אוטומטי + סימון reindex. _EMBEDDING_HEALTH_THREAD: Optional[threading.Thread] = None _EMBEDDING_HEALTH_LOCK = threading.Lock() def _maybe_start_embedding_health_check() -> None: """מרים את הבדיקה ב-thread, כשהחיפוש הסמנטי פעיל ויש ``GEMINI_API_KEY``. נקרא רק מתהליך השרת של הוובאפ — הבלוק שאחרי ``_is_webapp_runtime``, ולא בכל ייבוא של הקובץ. """ global _EMBEDDING_HEALTH_THREAD enabled = True if cfg is not None: enabled = bool(getattr(cfg, "SEMANTIC_SEARCH_ENABLED", True)) if not enabled: return if not str(os.getenv("GEMINI_API_KEY", "") or "").strip(): return with _EMBEDDING_HEALTH_LOCK: if _EMBEDDING_HEALTH_THREAD is not None and _EMBEDDING_HEALTH_THREAD.is_alive(): return def _runner(): try: from services.semantic_embedding_health import ( sync_probe_and_upgrade, ) sync_probe_and_upgrade() except Exception: # גבול ה-thread: חריגה כאן הייתה מסתיימת בשקט עם ה-thread. נרשמת עם traceback. logger.warning("Embedding health-check thread failed", exc_info=True) t = threading.Thread(target=_runner, daemon=True, name="embedding-healthcheck") _EMBEDDING_HEALTH_THREAD = t t.start() # --- Background warmup: heavy observability reports (fire & forget) --- _OBS_WARMUP_THREAD: Optional[threading.Thread] = None _OBS_WARMUP_LOCK = threading.Lock() _OBS_WARMUP_STOP_EVENT = threading.Event() def _env_bool(name: str, default: bool) -> bool: raw = os.getenv(name) if raw is None: return default return str(raw).strip().lower() in {"1", "true", "yes", "on"} def _env_float(name: str, default: float) -> float: raw = os.getenv(name) if raw is None: return float(default) try: return float(str(raw).strip()) except Exception: return float(default) def _parse_timerange_seconds(raw: str | None, default_seconds: int) -> int: """Parse '24h'/'7d'/'30d' style duration to seconds (best-effort).""" if not raw: return int(default_seconds) text = str(raw).strip().lower() if not text: return int(default_seconds) try: if text.endswith("ms"): value = float(text[:-2]) seconds = max(0.001, value / 1000.0) elif text.endswith("s"): seconds = float(text[:-1]) elif text.endswith("m"): seconds = float(text[:-1]) * 60.0 elif text.endswith("h"): seconds = float(text[:-1]) * 3600.0 elif text.endswith("d"): seconds = float(text[:-1]) * 86400.0 else: seconds = float(text) except Exception: return int(default_seconds) return max(1, int(seconds)) def _observability_warmup_ranges() -> List[str]: raw = os.getenv("OBSERVABILITY_WARMUP_RANGES", "24h,7d,30d") parts = [p.strip() for p in str(raw or "").split(",")] ranges = [p for p in parts if p] return ranges or ["24h", "7d", "30d"] def _should_autostart_observability_warmup() -> bool: # Feature flag if not _env_bool("OBSERVABILITY_WARMUP_ENABLED", True): return False # Avoid noisy side-effects in unit tests unless explicitly forced if os.getenv("PYTEST_CURRENT_TEST") and not _env_bool("OBSERVABILITY_WARMUP_AUTOSTART", False): return False # Flask dev reloader imports modules twice; start only in the "real" (child) process. # # Werkzeug sets WERKZEUG_RUN_MAIN="true" only in the child process that serves requests. # The parent reloader process typically has it *unset* (None), which looks identical to many # production setups (gunicorn/uwsgi) where it's also unset. # # לכן אנחנו מזהים "סביבת reloader" לפי דגלים של flask-run/debug, ורק אז דורשים WERKZEUG_RUN_MAIN="true". wrm = os.getenv("WERKZEUG_RUN_MAIN") if wrm not in (None, ""): # When explicitly present, only allow the child ("true"/"1"). if str(wrm).strip().lower() not in {"true", "1"}: return False else: # If it is unset, allow in production, but block in the reloader parent process. flask_run_from_cli = str(os.getenv("FLASK_RUN_FROM_CLI") or "").strip().lower() in {"true", "1"} flask_debug = str(os.getenv("FLASK_DEBUG") or "").strip().lower() in {"true", "1"} flask_env = str(os.getenv("FLASK_ENV") or "").strip().lower() likely_reloader_parent = flask_run_from_cli or flask_debug or (flask_env == "development") if likely_reloader_parent: return False return True def _run_observability_warmup(stop_event: threading.Event) -> None: """Warm up the heavy observability aggregations cache and DB RAM.""" delay_seconds = max(0.0, _env_float("OBSERVABILITY_WARMUP_DELAY_SECONDS", 5.0)) budget_seconds = max(0.0, _env_float("OBSERVABILITY_WARMUP_BUDGET_SECONDS", 20.0)) slow_endpoints_limit = max(1, min(20, int(_env_float("OBSERVABILITY_WARMUP_SLOW_LIMIT", 5.0)))) # Delay: allow the server to start accepting requests first. if delay_seconds > 0: stop_event.wait(delay_seconds) if stop_event.is_set(): return logger.info("🔥 Starting Background Cache Warmup...") t0 = _time.monotonic() try: for range_val in _observability_warmup_ranges(): if budget_seconds and (_time.monotonic() - t0) > budget_seconds: logger.info("⏱️ Warmup budget exceeded; stopping early") break if stop_event.is_set(): break logger.info("⏳ Warming up report: %s...", range_val) now = datetime.now(timezone.utc) seconds = _parse_timerange_seconds(range_val, default_seconds=24 * 3600) start_dt = now - timedelta(seconds=seconds) # Direct service call (no HTTP) to populate internal cache and DB RAM. observability_service.fetch_aggregations( start_dt=start_dt, end_dt=now, slow_endpoints_limit=slow_endpoints_limit, ) logger.info("✅ Background Cache Warmup Completed!") except Exception as e: # Fail-open: warmup is best-effort and should never crash the process. logger.warning("⚠️ Warmup failed (non-critical): %s", e, exc_info=True) def start_background_observability_warmup() -> None: """Start warmup thread once (non-blocking).""" global _OBS_WARMUP_THREAD if not _should_autostart_observability_warmup(): return try: with _OBS_WARMUP_LOCK: if _OBS_WARMUP_THREAD is not None and _OBS_WARMUP_THREAD.is_alive(): return _OBS_WARMUP_STOP_EVENT.clear() _OBS_WARMUP_THREAD = threading.Thread( target=_run_observability_warmup, args=(_OBS_WARMUP_STOP_EVENT,), name="observability_warmup", daemon=True, ) _OBS_WARMUP_THREAD.start() except Exception: # Fail-open: never block startup due to warmup scheduling. return def _stop_background_observability_warmup() -> None: try: _OBS_WARMUP_STOP_EVENT.set() except Exception: return atexit.register(_stop_background_observability_warmup) # זמני (חירום): ביטול Warmup בזמן startup כדי לשחרר עומס DB. # כדי להפעיל מחדש בלי שינוי קוד: DISABLE_STARTUP_WARMUP=false if str(os.getenv("DISABLE_STARTUP_WARMUP", "true")).lower() not in {"1", "true", "yes", "on"}: start_background_observability_warmup() # --- Backup restore jobs TTL index --- try: from webapp.backup_api import _ensure_restore_indexes # noqa: E402 _ensure_restore_indexes() except Exception: pass # --- תהליכוני רקע: רק בתהליך השרת של הוובאפ --- # חשוב: מתזמן הגיבויים ושולח הפושים חייבים לרוץ רק בתוך תהליך ה-webapp עצמו # (gunicorn/flask), ולא כש-module זה מיובא מתהליך אחר — הבוט ב-main.py שעושה # `from webapp.app import get_db`, סקריפטים, ותהליכי הטסטים. אחרת קם עותק נוסף # בשירות שאין לו את המשאבים: למתזמן חסר ה-persistent disk (PermissionError על # /var/data), ולשולח חסרים מפתחות ה-VAPID. #: שמות ה-console script של שרתי WSGI/ASGI שטוענים את ``webapp.app:app``, כפי שהם רשומים #: ב-``entry_points.txt`` של כל חבילה (gunicorn 23.0.0, uvicorn 0.38.0, flask 3.1.2, #: hypercorn 0.18.0, waitress 3.0.2). ``scripts/start_webapp.sh`` מריץ את gunicorn. _WEBAPP_SERVER_SCRIPTS = frozenset({"gunicorn", "uvicorn", "hypercorn", "waitress-serve", "flask"}) #: אותם שרתים כשהם מורצים ב-``python -m <חבילה>``: אז ``sys.argv[0]`` הוא הנתיב המלא #: ל-``<חבילה>/__main__.py``, ולכל החמש יש קובץ כזה. _WEBAPP_SERVER_PACKAGES = frozenset({"gunicorn", "uvicorn", "hypercorn", "waitress", "flask"}) def _is_webapp_runtime() -> bool: """האם התהליך הזה הוא שרת הוובאפ — לפי ``sys.argv[0]`` בלבד. **ההשוואה היא לשם קובץ ההרצה, לא לתווים בנתיב.** עד התיקון הזה נבדק אם אחת המילים "gunicorn", "flask" וכו' מופיעה **איפשהו** ב-``sys.argv[0]``, כך שסקריפט כמו ``/srv/flask-migrations/reindex.py`` היה נחשב לשרת ומרים את מתזמן הגיבויים ואת שולח הפושים. עכשיו נבדק רק שם הקובץ עצמו מול ``_WEBAPP_SERVER_SCRIPTS``, או — כשהוא ``__main__.py`` של ``python -m`` — שם החבילה שהוא יושב בה, מול ``_WEBAPP_SERVER_PACKAGES``. בכוונה בלי דגלי override: כל צרכן מחליט בעצמו אם לאפשר עקיפה, ובשם משלו. ``FORCE_BACKUP_SCHEDULER`` היה כאן, וכך היה מפעיל בשקט גם את שולח הפושים, בעוד שהתיעוד שלו מבטיח רק את מתזמן הגיבויים. """ entry = (sys.argv[0] or "") if sys.argv else "" if not entry: return False # הרצה ישירה של הקובץ הזה (python app.py / python webapp/app.py / נתיב מלא) try: if os.path.realpath(entry) == os.path.realpath(__file__): return True except Exception: pass # שרת WSGI/ASGI שטוען את webapp.app:app entry_path = entry.lower().replace("\\", "/") name = os.path.basename(entry_path) if name == "__main__.py": return os.path.basename(os.path.dirname(entry_path)) in _WEBAPP_SERVER_PACKAGES return name in _WEBAPP_SERVER_SCRIPTS # כתובת הוובאפ: INFO כשהיא תקינה, ERROR כשהיא חסרה או פגומה — רק בשרת הוובאפ, כי גם הבוט מייבא את # ``webapp.app`` (חימום הקאש), והוא כותב את השורה שלו בעצמו (``main()``). מוצג גם ב-``/health``. if _is_webapp_runtime(): log_webapp_url_status(logger, service="webapp") log_legacy_redirect_status(logger) try: if str(os.getenv("DISABLE_BACKUP_SCHEDULER", "")).lower() not in {"1", "true", "yes"}: # FORCE_BACKUP_SCHEDULER: override מפורש לסביבות לא סטנדרטיות, שבהן הזיהוי נכשל _force_backup = str(os.getenv("FORCE_BACKUP_SCHEDULER", "")).lower() in {"1", "true", "yes"} if _force_backup or _is_webapp_runtime(): from webapp.backup_scheduler import start_backup_scheduler # noqa: E402 start_backup_scheduler() else: logger.info( "Skipping backup scheduler: webapp.app imported from non-webapp process (argv0=%s)", (sys.argv[0] if sys.argv else ""), ) except Exception: pass # החוטים של הריפואים (``start_webapp_repo_threads`` ב-``services/repo_sync_service.py``): מילוי ה-mirrors החסרים # בדיסק, ואחריו ה-worker של הסנכרון, שמחכה למילוי לפני שהוא תופס ג'ובים. רק בשרת הוובאפ, שהדיסק שלו. ה-worker עולה # כאן ולא רק כשמגיע webhook, כדי שג'ובים ממתינים ייתפסו גם בשירות שה-webhooks לא מגיעים אליו. כשל לא מפיל את # העלייה, אבל נרשם — בלעדיו ריפו שחסר בדיסק נשאר חסר בלי שום סימן. if _is_webapp_runtime(): try: from services.repo_sync_service import start_webapp_repo_threads # noqa: E402 start_webapp_repo_threads() except Exception: logger.warning("Failed to start the repo mirror fill and the sync worker", exc_info=True) # בדיקת מודל ה-embedding מול Gemini (``_maybe_start_embedding_health_check``) — רק בשרת הוובאפ. עד נובמבר 2026 היא # קמה בכל ייבוא של הקובץ: בבוט, שמריץ בעלייה בדיקה משלו (``maybe_upgrade_embedding_model_on_startup`` ב-``main.py``); # בסקריפטים שמייבאים מכאן רק את ``get_db``; ובתהליך הטסטים — עם בקשה אמיתית ל-Gemini כשהמפתח מוגדר בסביבה. כשהמודל # מחזיר 404 הבדיקה גם משדרגת מודל ומסמנת את כל הקבצים לאינדוקס מחדש, כך שזו לא רק בקשת רשת מיותרת. if _is_webapp_runtime(): try: _maybe_start_embedding_health_check() except Exception: logger.warning("Failed to start the embedding health-check", exc_info=True) else: logger.info( "Skipping embedding health-check: webapp.app imported from non-webapp process (argv0=%s)", (sys.argv[0] if sys.argv else ""), ) # --- Observability: Alert Tags indexes warmup (best-effort) --- def start_background_alert_tags_indexes() -> None: """מנסה להבטיח אינדקסים ל-alert_tags ברקע (לא חוסם את השרת).""" # אל תרוץ ב-CI/Docs (לפי אותו כלל גלובלי) if str(os.getenv("DISABLE_DB", "")).lower() in {"1", "true", "yes"}: return if str(os.getenv("SPHINX_MOCK_IMPORTS", "")).lower() in {"1", "true", "yes"}: return try: from monitoring import alert_tags_storage # type: ignore except Exception: return try: t = threading.Thread(target=alert_tags_storage.ensure_indexes, daemon=True, name="alert_tags_indexes") t.start() except Exception: return start_background_alert_tags_indexes() # --- Startup metrics instrumentation (נרשם רק בזמן עלייה) --- _STARTUP_METRICS_MS: Dict[str, float] = {} _STARTUP_METRICS_LOCK = threading.Lock() _STARTUP_METRICS_LOGGED = False def _record_startup_metric(name: str, duration_seconds: float | None, *, accumulate: bool = False) -> None: """שומר מדידה (במילי-שניות) עבור שלב העלייה – ללא תקורה בזמן ריצה.""" if duration_seconds is None: return try: duration_ms = max(0.0, float(duration_seconds) * 1000.0) except Exception: return updated_value: float | None = None try: with _STARTUP_METRICS_LOCK: if accumulate: updated_value = duration_ms + _STARTUP_METRICS_MS.get(name, 0.0) _STARTUP_METRICS_MS[name] = updated_value else: existing = _STARTUP_METRICS_MS.get(name) if existing is None or duration_ms > existing: _STARTUP_METRICS_MS[name] = duration_ms updated_value = duration_ms else: updated_value = existing except Exception: return try: record_startup_stage_metric(name, updated_value) except Exception: pass def _emit_startup_metrics_log(total_ms: float | None = None) -> None: """מדפיס לוג מובנה בסיום העלייה בפורמט שניתן לניתוח.""" global _STARTUP_METRICS_LOGGED with _STARTUP_METRICS_LOCK: if _STARTUP_METRICS_LOGGED: return _STARTUP_METRICS_LOGGED = True metrics_snapshot = dict(_STARTUP_METRICS_MS) try: templates_ms = metrics_snapshot.get('templates') mongo_ms = metrics_snapshot.get('mongo') or metrics_snapshot.get('mongo_ping') indexes_ms = ( metrics_snapshot.get('indexes_recent', 0.0) + metrics_snapshot.get('indexes_code', 0.0) + metrics_snapshot.get('indexes_announcements', 0.0) ) ordered_parts: list[str] = [] for label, value in ( ('mongo', mongo_ms), ('templates', templates_ms), ('indexes', indexes_ms), ): if value and value > 0.0: ordered_parts.append(f"{label}={int(round(value))}ms") if total_ms is None: try: total_ms = max(0.0, (_time.perf_counter() - get_boot_monotonic()) * 1000.0) except Exception: total_ms = 0.0 ordered_parts.append(f"total={int(round(total_ms or 0.0))}ms") try: record_startup_total_metric(total_ms) except Exception: pass logger.info("[startup-metrics] %s", " ".join(ordered_parts)) except Exception: pass # --- Static asset version (for cache-busting of PWA manifest/icons) --- _MANIFEST_PATH = (Path(__file__).parent / 'static' / 'manifest.json') _STATIC_VERSION_SOURCE = "init" def _compute_static_version() -> str: """Return a short version string to bust caches for static assets. Preference order: 1) ASSET_VERSION env (exported by start_webapp.sh) 2) APP_VERSION env (explicit override) 3) VCS commit env (Render/Heroku/etc.) 4) SHA1(first 8) of manifest.json contents 5) Hourly rolling timestamp """ global _STATIC_VERSION_SOURCE version_candidates = [ ("ASSET_VERSION", os.getenv("ASSET_VERSION")), ("APP_VERSION", os.getenv("APP_VERSION")), ("RENDER_GIT_COMMIT", os.getenv("RENDER_GIT_COMMIT")), ("SOURCE_VERSION", os.getenv("SOURCE_VERSION")), ("GIT_COMMIT", os.getenv("GIT_COMMIT")), ("HEROKU_SLUG_COMMIT", os.getenv("HEROKU_SLUG_COMMIT")), ] for source_name, value in version_candidates: if value: _STATIC_VERSION_SOURCE = source_name.lower() return str(value)[:8] # קיצור כדי לשמור על מחרוזת קצרה ויציבה try: p = _MANIFEST_PATH if p.is_file(): h = hashlib.sha1(p.read_bytes()).hexdigest() # nosec - not for security _STATIC_VERSION_SOURCE = "manifest_sha" return h[:8] except Exception: pass try: _STATIC_VERSION_SOURCE = "hourly_timestamp" return str(int(_time.time() // 3600)) except Exception: _STATIC_VERSION_SOURCE = "default_dev" return "dev" _STATIC_VERSION = _compute_static_version() try: logger.info("[static-version] using=%s source=%s", _STATIC_VERSION, _STATIC_VERSION_SOURCE) except Exception: pass def _env_int(name: str, default: int) -> int: try: raw = os.getenv(name) if raw is None or raw.strip() == '': return default value = int(raw) if value <= 0: return default return value except Exception: return default MARKDOWN_IMAGE_LIMIT = _env_int('MARKDOWN_IMAGE_LIMIT', 6) MARKDOWN_IMAGE_MAX_BYTES = _env_int('MARKDOWN_IMAGE_MAX_BYTES', 2 * 1024 * 1024) ALLOWED_MARKDOWN_IMAGE_TYPES = {'image/png', 'image/jpeg', 'image/webp', 'image/gif'} # מזהי השיתוף של מדריך המשתמש (``/share/welcome``). פעם מודאל הפתיחה קישר אליהם, # וקישורים שכבר נשלחו ממשיכים להפנות לכאן. הערכים ההיסטוריים נשמרים כאליאסים מאותה # סיבה – בפועל נטען את המדריך המעודכן מקובץ USER_GUIDE.md בכל בקשה. WELCOME_GUIDE_PRIMARY_SHARE_ID = "welcome" WELCOME_GUIDE_SECONDARY_SHARE_ID = "welcome-quickstart" WELCOME_GUIDE_SHARE_ALIASES = { WELCOME_GUIDE_PRIMARY_SHARE_ID, WELCOME_GUIDE_SECONDARY_SHARE_ID, "JjvpJFTXZO0oHtoC", "sdVOAx6hUGsH4Anr", } USER_GUIDE_PATH = Path(__file__).parent / 'USER_GUIDE.md' WELCOME_GUIDE_FILE_NAME = "CodeKeeper-WebApp-Guide-v2.md" WELCOME_GUIDE_DESCRIPTION = "מדריך משתמש מעודכן ל-Code Keeper WebApp (גרסה 2.0)" # Weekly Tip feature flag (env/config override) def _to_bool(val, default: bool = True) -> bool: try: if isinstance(val, bool): return val s = str(val).strip().lower() if s in ("0", "false", "no", "off", "none", ""): # treat empty as false only if explicitly provided return False if s in ("1", "true", "yes", "on"): # common truthy strings return True return default except Exception: return default _WEEKLY_TIP_ENABLED_RAW = _cfg_or_env('WEEKLY_TIP_ENABLED', default='true') WEEKLY_TIP_ENABLED = _to_bool(_WEEKLY_TIP_ENABLED_RAW, default=True) # Guards for first-request and DB init race conditions _FIRST_REQUEST_LOCK = threading.Lock() _FIRST_REQUEST_RECORDED = False def _build_request_span_attrs() -> Dict[str, str]: attrs: Dict[str, str] = {"component": "flask.webapp"} try: method = getattr(request, "method", "") if method: attrs["http.method"] = str(method).upper() except Exception: pass try: endpoint = getattr(request, "endpoint", "") or "" if endpoint: attrs["endpoint"] = endpoint except Exception: pass try: path = getattr(request, "path", "") or "" if path: attrs["http.target"] = path except Exception: pass try: rid = getattr(request, "_req_id", None) if not rid: rid = request.headers.get("X-Request-ID") if rid: attrs["request_id"] = str(rid) except Exception: pass try: ctx = get_observability_context() or {} if isinstance(ctx, dict): if ctx.get("command"): attrs["command"] = str(ctx["command"]) if ctx.get("user_id"): attrs["user_id_hash"] = str(ctx["user_id"]) if ctx.get("chat_id"): attrs["chat_id_hash"] = str(ctx["chat_id"]) except Exception: pass return {k: v for k, v in attrs.items() if v not in ("", None)} @app.before_request def _otel_start_request_span(): try: attrs = _build_request_span_attrs() span_cm = start_span("web.request", attrs) except Exception: setattr(g, "_otel_span_cm", None) setattr(g, "_otel_span", None) setattr(g, "_otel_response_status", None) setattr(g, "_otel_cache_hit", None) return span = span_cm.__enter__() setattr(g, "_otel_span_cm", span_cm) setattr(g, "_otel_span", span) setattr(g, "_otel_response_status", None) setattr(g, "_otel_cache_hit", None) if span is not None: try: set_current_span_attributes({"component": "flask.webapp"}) except Exception: pass # --- OpenTelemetry (optional, fail-open) --- try: from observability_otel import setup_telemetry as _setup_otel _setup_otel( service_name="code-keeper-webapp", service_version=os.getenv("APP_VERSION", ""), environment=os.getenv("ENVIRONMENT", os.getenv("ENV", "production")), flask_app=app, ) except Exception: pass # Manual tracing decorator (fail-open) try: from observability_instrumentation import traced, start_span, set_current_span_attributes except Exception: # pragma: no cover def traced(*_a, **_k): def _inner(f): return f return _inner class _NoSpan: def __enter__(self): # pragma: no cover return None def __exit__(self, *_exc): # pragma: no cover return False def start_span(*_a, **_k): # type: ignore return _NoSpan() def set_current_span_attributes(*_a, **_k): # type: ignore return None # --- Correlation ID across services (request_id) --- try: from observability import generate_request_id as _gen_rid, bind_request_id as _bind_rid except Exception: def _gen_rid(): return "" def _bind_rid(_rid: str) -> None: return None # --- Lightweight preload of heavy dependencies/templates (non-blocking) --- def _preload_heavy_assets_async() -> None: """Preload non-critical assets to reduce first-hit latency. Runs in a background thread to avoid blocking app import. """ try: import threading as _thr def _job(): job_started = _time.perf_counter() # Preload Pygments lexers/formatters (import and simple use) try: from pygments.lexers import get_lexer_by_name as _g _t0 = _time.perf_counter() for _name in ("python", "javascript", "bash", "json"): try: _ = _g(_name) except Exception: pass duration = max(0.0, float(_time.perf_counter() - _t0)) try: record_dependency_init("pygments_lexers", duration) except Exception: pass try: _record_startup_metric('lexers', duration) except Exception: pass except Exception: pass # Warm up Jinja by preloading hot templates (compile without request context) try: _t1 = _time.perf_counter() with app.app_context(): # Preload a few hot templates (best-effort) for _tpl in ("files.html", "view_file.html", "dashboard.html", "md_preview.html", "login.html"): try: _ = app.jinja_env.get_template(_tpl) except Exception: pass duration = max(0.0, float(_time.perf_counter() - _t1)) try: record_dependency_init("jinja_precompile", duration) except Exception: pass try: _record_startup_metric('templates', duration) except Exception: pass except Exception: pass # Optionally attempt DB ping + init in background (best-effort) try: _t0 = _time.perf_counter() # Use a short‑lived client to avoid mutating the global shared client if MONGODB_URL: _tmp_client = MongoClient( MONGODB_URL, serverSelectionTimeoutMS=2000, tz_aware=True, tzinfo=timezone.utc, ) try: # Best‑effort ping; ignore failures silently _ = _tmp_client.admin.command('ping') except Exception: pass finally: try: _tmp_client.close() except Exception: pass try: _ = get_db() except Exception: pass duration = max(0.0, float(_time.perf_counter() - _t0)) try: record_dependency_init("mongodb_ping", duration) except Exception: pass try: _record_startup_metric('mongo_ping', duration) except Exception: pass except Exception: pass # Signal startup completion at the end of preload sequence total_ms = max(0.0, float((_time.perf_counter() - job_started) * 1000.0)) try: mark_startup_complete() finally: try: _emit_startup_metrics_log(total_ms=total_ms) except Exception: pass _thr.Thread(target=_job, name="preload-assets", daemon=True).start() except Exception: # Never block on preload failures try: mark_startup_complete() finally: try: _emit_startup_metrics_log() except Exception: pass # --- API blueprints registration --- try: from webapp.bookmarks_api import bookmarks_bp # noqa: E402 app.register_blueprint(bookmarks_bp) except Exception: # אם יש כשל בייבוא (למשל בזמן דוקס/CI בלי תלותים), אל תפיל את השרת pass # Personal Backup API (Export/Restore) try: from webapp.backup_api import backup_bp # noqa: E402 app.register_blueprint(backup_bp) except Exception: # אל תפיל את השרת אם ה-Blueprint אינו זמין (למשל בסביבת דוקס/CI) pass # Google Drive Auth (OAuth redirect flow) try: from webapp.drive_auth import drive_auth_bp # noqa: E402 app.register_blueprint(drive_auth_bp) except Exception: pass # Drive & Disk Backup API (schedule, trigger, status) try: from webapp.drive_backup_api import drive_backup_bp # noqa: E402 app.register_blueprint(drive_backup_bp) except Exception: pass # GitHub Webhooks (Repo Sync Engine) - לפי המדריך try: from webapp.routes.webhooks import webhooks_bp # noqa: E402 app.register_blueprint(webhooks_bp) except Exception: # אל תפיל את השרת אם ה-Blueprint אינו זמין (למשל בסביבת דוקס/CI) pass # Repo Browser UI/API (Repo Sync Engine) - לפי המדריך try: from webapp.routes.repo_browser import repo_bp # noqa: E402 app.register_blueprint(repo_bp) except Exception: # אל תפיל את השרת אם ה-Blueprint אינו זמין (למשל בסביבת דוקס/CI) pass # Files API (Layered Architecture Pilot - Issue #2871) try: from webapp.routes.files_routes import files_bp # noqa: E402 app.register_blueprint(files_bp) except Exception: # אל תפיל את השרת אם ה-Blueprint אינו זמין (למשל בסביבת דוקס/CI) pass # Auth Routes (Layered Architecture - Issue #2871 Step 3) try: from webapp.routes.auth_routes import auth_bp # noqa: E402 app.register_blueprint(auth_bp) except Exception: pass # Settings Routes (Layered Architecture - Issue #2871 Step 3) try: from webapp.routes.settings_routes import settings_bp # noqa: E402 app.register_blueprint(settings_bp) except Exception: pass # Dashboard Routes (Layered Architecture - Issue #2871 Step 3) try: from webapp.routes.dashboard_routes import dashboard_bp # noqa: E402 app.register_blueprint(dashboard_bp) except Exception: pass # Themes API (Presets/Import/Export) - לפי המדריך try: from webapp.themes_api import themes_bp # noqa: E402 app.register_blueprint(themes_bp) except Exception: # אל תפיל את השרת אם ה-Blueprint אינו זמין (למשל בסביבת דוקס/CI) pass # Sticky Notes API (Markdown inline notes) try: from webapp.sticky_notes_api import sticky_notes_bp, kickoff_index_warmup # noqa: E402 app.register_blueprint(sticky_notes_bp) # זמני (חירום): ביטול Warmup בזמן startup כדי לשחרר עומס DB. # כדי להפעיל מחדש בלי שינוי קוד: DISABLE_STARTUP_WARMUP=false if str(os.getenv("DISABLE_STARTUP_WARMUP", "true")).lower() not in {"1", "true", "yes", "on"}: try: kickoff_index_warmup() except Exception: pass except Exception: # אל תפיל את היישום אם ה-Blueprint אינו זמין (למשל בסביבת דוקס/CI) pass # Note Boards API (לוחות פתקים — פתקים שאינם צמודים לקובץ). # ראוטי הפתקים של הלוח יושבים ב-sticky_notes_bp שלמעלה; כאן רק הלוחות עצמם. try: from webapp.note_boards_api import note_boards_bp # noqa: E402 app.register_blueprint(note_boards_bp) except Exception as _e: # לא מפילים את היישום (סביבות דוקס/CI ללא תלויות), אבל גם לא בולעים # בשקט: רישום שנכשל פירושו שהפיצ'ר פשוט לא קיים, וזה חייב להיראות # בלוג ברמת error ולא להתגלות כ-404 מסתורי. try: logger.error("note_boards_api blueprint not registered: %s", _e, exc_info=True) except Exception: pass # Note Boards UI (עמודי הלוחות עצמם) try: from webapp.boards_ui import boards_ui # noqa: E402 app.register_blueprint(boards_ui) except Exception as _e: try: logger.error("boards_ui blueprint not registered: %s", _e, exc_info=True) except Exception: pass # עמוד חיפוש הפתקים. התוצאות עצמן מגיעות מ-``sticky_notes_bp``. try: from webapp.routes.notes_search import notes_search_bp # noqa: E402 app.register_blueprint(notes_search_bp) except Exception as _e: try: logger.error("notes_search blueprint not registered: %s", _e, exc_info=True) except Exception: pass # Web Push API (public key + subscribe/unsubscribe) try: from webapp.push_api import push_bp, start_sender_if_enabled # noqa: E402 app.register_blueprint(push_bp) # הפעלת שולח פושים ברקע — רק בתהליך השרת של הוובאפ, באותו שומר כמו מתזמן # הגיבויים (``_is_webapp_runtime``), ורק אם מאופשר בקונפיג. עד כאן הוא קם # בכל ייבוא: בבוט (ג'וב חימום הקאש ב-main.py) הוא רץ כל דקה ונכשל על מפתח # VAPID חסר (``push_send_missing_vapid_private`` בלוג של שירות הבוט), ובתהליכי # הטסטים הוא החזיק את ``_DB_INIT_LOCK`` בזמן חיפוש שרת מונגו — ונתקע לתמיד # כשהחיפוש התחיל בתוך ``freeze_time``, ואיתו כל טסט שחיכה לנעילה (CI של # #3585). ההחלטה מי שולח: ``docs/deployment/workers.rst``. try: if _is_webapp_runtime(): start_sender_if_enabled() else: logger.info( "Skipping push sender: webapp.app imported from non-webapp process (argv0=%s)", (sys.argv[0] if sys.argv else ""), ) except Exception: # עליית האפליקציה אינה נופלת על שולח הפושים — אבל הכשל נרשם, כי בלעדיו # אין שום סימן לכך שתזכורות הפסיקו להישלח. ``start_sender_if_enabled`` # מעלה לכאן כשל בהרמת ה-thread, ולא בולע אותו בעצמו. logger.warning("Failed to start push sender", exc_info=True) except Exception: # סביבת דוקס/CI ללא תלויות לא צריכה להיכשל על ייבוא זה pass # Code Tools API (format/lint/fix) try: from webapp.code_tools_api import code_tools_bp # noqa: E402 app.register_blueprint(code_tools_bp) except Exception as e: try: logger.warning(f"Failed to register code_tools_bp: {e}") except Exception: pass # JSON Formatter API (format/minify/validate/fix) try: from webapp.json_formatter_api import json_formatter_bp # noqa: E402 app.register_blueprint(json_formatter_bp) except Exception as e: try: logger.warning(f"Failed to register json_formatter_bp: {e}") except Exception: pass # זיהוי הרצה תחת pytest בזמן import (גם בזמן איסוף טסטים) _IS_PYTEST = bool(os.getenv("PYTEST_CURRENT_TEST")) or ("pytest" in sys.modules) or os.getenv("PYTEST") == "1" or os.getenv("PYTEST_RUNNING") == "1" # Collections (My Collections) API try: from config import config as _cfg except Exception: _cfg = None try: # קביעת זמינות הפיצ'ר: ברירת מחדל True, אלא אם הקונפיג מכבה במפורש. enabled = True if _cfg is None else bool(getattr(_cfg, 'FEATURE_MY_COLLECTIONS', True)) # ב-PyTest – נכפה enable כדי להבטיח רישום ה-Blueprint גם אם config חסר/מכובה if _IS_PYTEST: enabled = True if enabled: from webapp.collections_api import collections_bp # noqa: E402 # רישום יחיד וקנוני של ה-API בנתיב /api/collections app.register_blueprint(collections_bp, url_prefix="/api/collections") try: from webapp.workspace_api import workspace_bp # noqa: E402 app.register_blueprint(workspace_bp, url_prefix="/api/workspace") except Exception as _workspace_err: try: logger.info("workspace_api blueprint not registered: %s", _workspace_err) except Exception: pass # רישום דפי UI (server-rendered) הטעונים למסלול /collections try: from webapp.collections_ui import collections_ui # noqa: E402 app.register_blueprint(collections_ui) except Exception as _e: try: logger.info("collections_ui blueprint not registered: %s", _e) except Exception: pass except Exception as e: # בפרודקשן – לא נרשום Blueprint דיאגנוסטי, רק נרשום ללוג try: logger.error("Failed to register collections blueprint: %s", e, exc_info=True) except Exception: pass if _IS_PYTEST: # ב-PyTest – אם הייבוא נכשל, נרשום Blueprint דיאגנוסטי שמחזיר 503 במקום 404 try: from flask import Blueprint # ייבוא לוקלי כדי לא לזהם טופ-לבל diagnostic_bp = Blueprint('collections_diagnostic', __name__) # נתיבים לוכדים לכל ה-API תחת /api/collections @diagnostic_bp.route('', defaults={'_path': ''}, methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']) @diagnostic_bp.route('/', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']) def _collections_unavailable(_path: str = ""): # שימוש ב-jsonify שכבר יובא בטופ-לבל return jsonify({ 'ok': False, 'error': 'collections_api_unavailable', 'diagnostic': True }), 503 app.register_blueprint(diagnostic_bp, url_prefix="/api/collections") try: logger.info("Registered diagnostic collections blueprint for pytest") except Exception: pass except Exception: # אם גם הרישום הדיאגנוסטי נכשל – נכשיל את הטסט כדי לא להסתיר תקלה אמיתית raise # Community Library API/UI (feature-flagged) try: _enabled_comm = True if _cfg is None else bool(getattr(_cfg, 'COMMUNITY_LIBRARY_ENABLED', True)) if _IS_PYTEST: _enabled_comm = True if _enabled_comm: try: from webapp.community_library_api import community_lib_bp # type: ignore # noqa: E402 app.register_blueprint(community_lib_bp) except Exception as _e: try: logger.info("community_library_api not registered: %s", _e) except Exception: pass try: from webapp.community_library_ui import community_library_ui # type: ignore # noqa: E402 app.register_blueprint(community_library_ui) except Exception as _e: try: logger.info("community_library_ui not registered: %s", _e) except Exception: pass # Snippet Library API/UI try: from webapp.snippet_library_api import snippets_bp # type: ignore # noqa: E402 app.register_blueprint(snippets_bp) except Exception as _e: try: logger.info("snippets_api not registered: %s", _e) except Exception: pass try: # UI blueprint may be optional; register if available from webapp.snippet_library_ui import snippet_library_ui # type: ignore # noqa: E402 app.register_blueprint(snippet_library_ui) except Exception as _e: try: logger.info("snippet_library_ui not registered: %s", _e) except Exception: pass except Exception: pass # Visual Rules API (Visual Rule Engine) try: from webapp.rules_api import rules_bp # noqa: E402 app.register_blueprint(rules_bp, url_prefix="/api/rules") except Exception as _e: # אל תפיל את היישום אם ה-Blueprint אינו זמין (למשל בסביבת דוקס/CI) try: logger.info("rules_api blueprint not registered: %s", _e) except Exception: pass # --- Metrics helpers (import guarded to avoid hard deps in docs/CI) --- try: from metrics import ( record_request_outcome, record_http_request, record_request_queue_delay, get_boot_monotonic, mark_startup_complete, note_first_request_latency, record_dependency_init, get_avg_response_time_seconds, update_health_gauges, record_startup_stage_metric, record_startup_total_metric, note_request_started, note_request_finished, note_deployment_started, note_deployment_shutdown, ) _METRICS_AVAILABLE = True except Exception: # pragma: no cover _METRICS_AVAILABLE = False def record_request_outcome(status_code: int, duration_seconds: float, **_kwargs) -> None: return None def record_http_request(method: str, endpoint: str, status_code: int, duration_seconds: float) -> None: return None def record_request_queue_delay(method: str, endpoint: str | None, delay_seconds: float, **_kwargs) -> None: return None def get_boot_monotonic() -> float: return 0.0 def mark_startup_complete() -> None: return None def note_first_request_latency(_d: float | None = None) -> None: return None def record_dependency_init(_name: str, _dur: float) -> None: return None def get_avg_response_time_seconds() -> float: return 0.0 def update_health_gauges(**_kwargs) -> None: return None def record_startup_stage_metric(_stage: str, _duration_ms: float | None) -> None: return None def record_startup_total_metric(_duration_ms: float | None) -> None: return None def note_request_started() -> None: return None def note_request_finished() -> None: return None def note_deployment_started(_summary: str = "Service starting up") -> None: return None def note_deployment_shutdown(_summary: str = "Service shutting down") -> None: return None # Trigger preload only after metrics helpers are available _preload_heavy_assets_async() try: note_deployment_started("webapp service starting up") except Exception: pass # --- Search: metrics, limiter (lightweight, optional) --- def _no_op(*args, **kwargs): return None try: from flask_limiter import Limiter from flask_limiter.util import get_remote_address _LIMITER_AVAILABLE = True except Exception: Limiter = None # fall back to a simple remote address accessor if limiter not installed get_remote_address = lambda: request.remote_addr if request else "" _LIMITER_AVAILABLE = False # Prometheus metrics (idempotent registration) def _get_existing_metric(name: str): try: if REGISTRY is not None and hasattr(REGISTRY, '_names_to_collectors'): return REGISTRY._names_to_collectors.get(name) except Exception: return None return None class _MetricNoop: def labels(self, *a, **k): return self def inc(self, *a, **k): return None def observe(self, *a, **k): return None def set(self, *a, **k): return None def _ensure_metric(name: str, create_fn): existing = _get_existing_metric(name) if existing: return existing try: return create_fn() except Exception: existing = _get_existing_metric(name) if existing: return existing return _MetricNoop() if Counter and Histogram and Gauge: search_counter = _ensure_metric('search_requests_total', lambda: Counter('search_requests_total', 'Total number of search requests', ['search_type', 'status'])) search_duration = _ensure_metric('search_duration_seconds', lambda: Histogram('search_duration_seconds', 'Search request duration in seconds')) search_results_count = _ensure_metric('search_results_count', lambda: Histogram('search_results_count', 'Number of results returned')) search_cache_hits = _ensure_metric('search_cache_hits_total', lambda: Counter('search_cache_hits_total', 'Total number of cache hits')) search_cache_misses = _ensure_metric('search_cache_misses_total', lambda: Counter('search_cache_misses_total', 'Total number of cache misses')) active_indexes_gauge = _ensure_metric('search_active_indexes', lambda: Gauge('search_active_indexes', 'Number of active search indexes')) impersonation_sessions_total = _ensure_metric( 'admin_impersonation_sessions_total', lambda: Counter( 'admin_impersonation_sessions_total', 'Total admin impersonation sessions started', ['admin_id'] ) ) impersonation_duration_seconds = _ensure_metric( 'admin_impersonation_duration_seconds', lambda: Histogram( 'admin_impersonation_duration_seconds', 'Duration of admin impersonation sessions', buckets=[60, 300, 600, 1800, 3600] ) ) else: search_counter = _MetricNoop() search_duration = _MetricNoop() search_results_count = _MetricNoop() search_cache_hits = _MetricNoop() search_cache_misses = _MetricNoop() active_indexes_gauge = _MetricNoop() impersonation_sessions_total = _MetricNoop() impersonation_duration_seconds = _MetricNoop() # Optional Sentry init (non-fatal if missing) try: if _SENTRY_AVAILABLE and getattr(__import__('config'), 'config').SENTRY_DSN: # Install sensitive data redaction on all handlers before Sentry hooks logging try: from utils import install_sensitive_filter install_sensitive_filter() except Exception: pass def _sentry_before_send(event, hint): """מנקה טוקני בוט מכל אירוע לפני שהוא נשלח ל-Sentry. הלוגיקה המשותפת (ניקוי עמוק + fail-closed) חיה ב-telegram_api.scrub_sentry_event — אותה נקודה שגם הבוט משתמש בה. """ try: from telegram_api import scrub_sentry_event # type: ignore event = scrub_sentry_event(event) except Exception: event = None if event is None: try: logger.warning("sentry event dropped: token redaction failed", extra={"event": "sentry_redaction_failed"}) except Exception: # nosec B110 — הגנה על מסלול הדיווח עצמו; האירוע כבר הופל pass return None return event sentry_sdk.init( dsn=getattr(__import__('config'), 'config').SENTRY_DSN, integrations=[FlaskIntegration()], traces_sample_rate=0.05, environment=getattr(__import__('config'), 'config').ENVIRONMENT, before_send=_sentry_before_send, # ה-spans של transactions נושאים כתובות HTTP מלאות (כולל טוקן ב-URL) # ואינם עוברים דרך before_send — מנקים אותם באותו מסלול fail-closed before_send_transaction=_sentry_before_send, ) except Exception: pass """Rate limiting backend setup Preference order: 1) Redis via REDIS_URL (TLS supported by driver) when available 2) In-memory fallback (per-process; acceptable for local/dev and tests) 3) Disabled if flask_limiter is unavailable """ def _client_rate_key(): """Rate-limit key: prefer user_id; else leftmost X-Forwarded-For; else remote_addr. זה מצמצם false-positives בפלטפורמות Proxy (למשל Render/Cloudflare) ומונע הגבלת משתמשים שונים תחת אותו IP פנימי. """ try: if 'user_id' in session: return str(session.get('user_id')) # Try the leftmost IP from X-Forwarded-For try: xff = (request.headers.get('X-Forwarded-For') or '').split(',') for raw in xff: ip = (raw or '').strip() if ip: return ip except Exception: pass return get_remote_address() except Exception: try: return request.remote_addr or "" except Exception: return "" _RATE_LIMIT_EXEMPT_USER_IDS = {6865105071} # החרגה לפיתוח (לא מוגבל בכלל) def _is_rate_limit_exempt_user() -> bool: """האם המשתמש הנוכחי מוחרג מכל ה-rate limits (אדמין או allowlist).""" try: uid_raw = session.get("user_id") uid = int(uid_raw) if uid_raw is not None else None except Exception: uid = None if uid is None: return False if uid in _RATE_LIMIT_EXEMPT_USER_IDS: return True try: return bool(is_admin(int(uid))) except Exception: return False if _LIMITER_AVAILABLE: try: # Resolve storage URI: prefer Redis when configured _storage_uri = "memory://" try: from config import config as _cfg except Exception: _cfg = None if _cfg is not None and getattr(_cfg, 'REDIS_URL', None): _storage_uri = str(getattr(_cfg, 'REDIS_URL')) elif os.getenv('REDIS_URL'): _storage_uri = os.getenv('REDIS_URL') or "memory://" limiter = Limiter( app=app, key_func=_client_rate_key, default_limits=["200 per day", "50 per hour"], storage_uri=_storage_uri, strategy=(getattr(_cfg, 'RATE_LIMIT_STRATEGY', 'moving-window') if _cfg else 'moving-window'), swallow_errors=True, # don't crash the app if backend unavailable ) # ========================================================== # Rate limit exemptions (dev/admin) # ========================================================== # מטרת ההחרגה: לאפשר פיתוח שוטף בלי להיחסם ע"י Rate Limiting # ולהחריג אדמינים מכל Endpoint. @limiter.request_filter def _rate_limit_exempt_filter() -> bool: return _is_rate_limit_exempt_user() except Exception: limiter = None else: limiter = None # ה-webhook של GitHub מוחרג מהמגבלה הגורפת (blanket-policy-silent-block §7). המפתח של המגביל הוא # ה-IP, ו-GitHub שולח מכמה כתובות קבועות: בלי ההחרגה, משלוחים של push ושל סטטוסי פריסה נספרים יחד # מול "50 per hour" ונחסמים ב-429 — וסנכרון או אינדוקס מתפספסים בלי שום עקבה אצלנו. כל בקשה שם # נבדקת בחתימה לפני כל עבודה. בבלוק נפרד ולא בתוך ה-``try`` שלמעלה, כדי שכשל כאן לא יאפס את המגביל. # ה-Blueprint נרשם למעלה בתוך ``try`` משלו; כשהוא לא נרשם, אין מה להחריג. _github_webhooks_bp = app.blueprints.get("webhooks") if limiter is not None and _github_webhooks_bp is not None: limiter.exempt(_github_webhooks_bp) # הגדרות MONGODB_URL = _cfg_or_env('MONGODB_URL') DATABASE_NAME = _cfg_or_env('DATABASE_NAME', default='code_keeper_bot') BOT_TOKEN = _cfg_or_env('BOT_TOKEN') def _webapp_base_url() -> str: """כתובת הבסיס המלאה של הוובאפ, בלי לוכסן בסוף — :func:`webapp_url.webapp_base_url_for_request`: ``WEBAPP_URL``, ואם אין כתובת תקינה — הכתובת שהבקשה הגיעה אליה. למקום שצריך כתובת מלאה ולא נתיב, בתשובה לאותה בקשה: קישור שיתוף שחוזר ליוצר, ותגיות התצוגה המקדימה בעמוד ציבורי (``og:url``, ``og:image``), שוואטסאפ דורש בהן כתובת מלאה. דורש הקשר בקשה. מודולים של הוובאפ שאינם מייבאים את הקובץ הזה (``drive_auth``, ``collections_api``, ``snippet_library_api``) קוראים ישירות ל-``webapp_base_url_for_request``, כך שהנפילה לכתובת הבקשה נשארת במקום אחד. """ return webapp_base_url_for_request(request) _DOCS_URL_RAW = _cfg_or_env('DOCUMENTATION_URL', default='https://amirbiron.github.io/CodeBot/') DOCUMENTATION_URL = (_DOCS_URL_RAW.rstrip('/') + '/') if _DOCS_URL_RAW else 'https://amirbiron.github.io/CodeBot/' BOT_USERNAME = os.getenv('BOT_USERNAME', 'my_code_keeper_bot') BOT_USERNAME_CLEAN = (BOT_USERNAME or '').lstrip('@') _ttl_env = os.getenv('PUBLIC_SHARE_TTL_DAYS', '7') FA_SRI_HASH = (os.getenv('FA_SRI_HASH') or '').strip() # --- Cache TTLs (seconds) for heavy endpoints/pages --- def _int_env(name: str, default: int, lo: int = 30, hi: int = 180) -> int: try: val = int(os.getenv(name, str(default))) return max(lo, min(hi, val)) except Exception: return default FILES_PAGE_CACHE_TTL = _int_env('FILES_PAGE_CACHE_TTL', 90, lo=30, hi=180) MD_PREVIEW_CACHE_TTL = _int_env('MD_PREVIEW_CACHE_TTL', 120, lo=60, hi=180) API_STATS_CACHE_TTL = _int_env('API_STATS_CACHE_TTL', 120, lo=60, hi=180) # --- External uptime monitoring (Option 2 from issue #730) --- # Provider options: 'betteruptime' (Better Stack), 'uptimerobot', 'statuscake', 'pingdom' UPTIME_PROVIDER = (os.getenv('UPTIME_PROVIDER') or '').strip().lower() # e.g., 'betteruptime' UPTIME_API_KEY = os.getenv('UPTIME_API_KEY', '') UPTIME_MONITOR_ID = os.getenv('UPTIME_MONITOR_ID', '') # Public status page URL (if you have one externally) UPTIME_STATUS_URL = os.getenv('UPTIME_STATUS_URL', '') # Optional widget (Better Uptime / Better Stack announcement widget) UPTIME_WIDGET_SCRIPT_URL = os.getenv('UPTIME_WIDGET_SCRIPT_URL', 'https://uptime.betterstack.com/widgets/announcement.js') UPTIME_WIDGET_ID = os.getenv('UPTIME_WIDGET_ID', '') # the widget data-id # Cache TTL (seconds) for external uptime API calls try: UPTIME_CACHE_TTL_SECONDS = max(30, int(os.getenv('UPTIME_CACHE_TTL_SECONDS', '120'))) except Exception: UPTIME_CACHE_TTL_SECONDS = 120 try: PUBLIC_SHARE_TTL_DAYS = max(1, int(_ttl_env)) except Exception: PUBLIC_SHARE_TTL_DAYS = 7 #: חלון הייצוא המעוצב בעמוד הקובץ (``export_modal.html``) בונה את הקובץ בדפדפן, באותו מנוע כמו התצוגה החיה. #: ``0`` מחזיר אותו לבנייה בשרת (``/export/styled/``), שנשארה כמו שהיא — דרך חזרה בלי דיפלוי של קוד. #: עובר לתבנית דרך ``inject_globals``. STYLED_EXPORT_BROWSER_RENDER = _env_bool('STYLED_EXPORT_BROWSER_RENDER', True) def _hebrew_day_count(days: int) -> str: """מספר ימים בעברית תקנית: "יום אחד", "יומיים", "7 ימים". משמש את התווית של הקישור הזמני במודאל השיתוף (``public_share_ttl_label`` ב-``inject_globals``), שנגזרת מ-``PUBLIC_SHARE_TTL_DAYS`` ואינה מוקלדת בתבנית. """ if days == 1: return 'יום אחד' if days == 2: return 'יומיים' return f'{days} ימים' # ימי השהות בסל המחזור — ערך אחד לכל מסלולי המחיקה, בבוט ובווב. # # היו כאן שניים: עמוד הקובץ הבטיח 30 יום ומחיקה מרובה נתנה 7, כי כל אחד # קרא מקור אחר — הקבוע הזה מול ``config.RECYCLE_TTL_DAYS``. אותה פעולה # בדיוק, שני מספרים. הקריאה עוברת דרך ``config`` ולא דרך ``os.getenv`` # בנפרד, כדי שלא ייווצר שוב מסלול קריאה שני שיכול לסטות. try: RECYCLE_TTL_DAYS = max(1, int(getattr(cfg, 'RECYCLE_TTL_DAYS', 30))) except Exception: RECYCLE_TTL_DAYS = 30 #: התקרה שהראוט מקבל מהלקוח. חייבת להיות לפחות ברירת המחדל, אחרת היא #: הייתה חותכת אותה בשקט. RECYCLE_TTL_DAYS_MAX = max(30, RECYCLE_TTL_DAYS) FILE_HISTORY_MAX_VERSIONS = 25 # הגדרת חיבור קבוע (Remember Me) try: PERSISTENT_LOGIN_DAYS = max(30, int(os.getenv('PERSISTENT_LOGIN_DAYS', '180'))) except Exception: PERSISTENT_LOGIN_DAYS = 180 REMEMBER_COOKIE_NAME = 'remember_me' # --- Admin Impersonation --- IMPERSONATION_SESSION_KEY = 'admin_impersonation_active' IMPERSONATION_ORIGINAL_ADMIN_KEY = 'admin_impersonation_original_user_id' # חיבור ל-MongoDB client = None db = None # Cache לנתוני healthz (מדידת אינדקסים) כדי לעמוד בדרישת 300ms _HEALTHZ_INDEX_CACHE_TTL_SECONDS = 60 _HEALTHZ_INDEX_CACHE: Dict[str, Any] = {'ts': 0.0, 'count': 0} _HEALTHZ_INDEX_CACHE_LOCK = threading.Lock() _HEALTHZ_CRITICAL_COLLECTIONS: Tuple[str, ...] = ( 'code_snippets', 'recent_opens', 'collections', 'users', ) def _sample_critical_index_count(db_ref) -> tuple[int, float]: """מודד מספר אינדקסים בסיסי עבור אוספים קריטיים (עם cache קצר).""" if db_ref is None: return (0, 0.0) now_ts = time.time() with _HEALTHZ_INDEX_CACHE_LOCK: cached_ts = float(_HEALTHZ_INDEX_CACHE.get('ts') or 0.0) if (now_ts - cached_ts) < _HEALTHZ_INDEX_CACHE_TTL_SECONDS: return (int(_HEALTHZ_INDEX_CACHE.get('count') or 0), 0.0) start = _time.perf_counter() total_indexes = 0 for coll_name in _HEALTHZ_CRITICAL_COLLECTIONS: try: info = db_ref[coll_name].index_information() total_indexes += len(info or {}) except Exception: continue duration = max(0.0, float(_time.perf_counter() - start)) with _HEALTHZ_INDEX_CACHE_LOCK: _HEALTHZ_INDEX_CACHE['ts'] = now_ts _HEALTHZ_INDEX_CACHE['count'] = total_indexes return (total_indexes, duration) #: התכונה על ``g`` שמחזיקה את מסמך המשתמש של הבקשה — ``(user_id, doc)``, ראו ``_request_user_doc``. _REQUEST_USER_DOC_ATTR = '_request_user_doc' def _request_user_doc(user_id: Any) -> Optional[Dict[str, Any]]: """מסמך המשתמש של הבקשה — נשלף פעם אחת, וכל מי שצריך אותו באותה בקשה קורא מכאן. ``inject_globals`` צריך אותו בכל דף, אבל הוא רץ רק בזמן הרינדור, **אחרי** שגוף הראוט כבר רץ. ראוט שצריך את אותו מסמך לפני כן — הדשבורד, שקורא ממנו את הדגלים של הצ'קליסט "צעדים ראשונים" (``webapp/first_steps.py``) — היה שולף אותו פעם שנייה. כאן השניים חולקים שליפה אחת, שנזכרת על ``g`` יחד עם ה-``user_id`` שלה. מחזיר את המסמך (מילון ריק כשאין למשתמש מסמך), או ``None`` כשהשליפה לא הצליחה: ``get_db`` החזיר ``None`` (חלון הצינון שלו), או שהמסד נכשל — כל ``PyMongoError``, ולא רק ניתוק. כל הקוראים מתייחסים ל-``None`` כברירות מחדל בטוחות: ``inject_globals`` מרנדר בהעדפות ברירת המחדל, הדשבורד בלי כרטיס "צעדים ראשונים", ועמוד ההגדרות בלי הקישור "הצג שוב". לפני שהם נוספו, ``inject_globals`` בלע את אותה שגיאה בכל דף, ושליפה צרה יותר כאן הייתה מפילה דווקא את שני הדפים האלה — בגלל תוספת. **``None`` אינו "אין העדפות"** — קורא שמחליט לפי דגל, כמו הסתרת הצ'קליסט, צריך להבחין בין השניים. גם הכשל נזכר עד סוף הבקשה: ניסיון אחד לבקשה. באג, כלומר חריגה שאינה של המסד, לא נתפס כאן ועולה לקורא. מחוץ להקשר בקשה אין ``g``, והפונקציה פשוט אינה זוכרת — כמו ``_resolve_files_compact_view``. """ try: cached = getattr(g, _REQUEST_USER_DOC_ATTR) except (RuntimeError, AttributeError): # ``RuntimeError`` — אין הקשר בקשה; ``AttributeError`` — יש, וטרם נשלף. cached = None if cached is not None and cached[0] == user_id: return cached[1] doc: Optional[Dict[str, Any]] = None try: db_ref = get_db() if db_ref is not None: doc = db_ref.users.find_one({'user_id': user_id}) or {} except PyMongoError: logger.warning("user document fetch failed", exc_info=True) doc = None try: setattr(g, _REQUEST_USER_DOC_ATTR, (user_id, doc)) except RuntimeError: pass # מחוץ להקשר בקשה — אין מה לזכור return doc @app.context_processor def inject_globals(): """הזרקת משתנים גלובליים לכל התבניות""" user_id = session.get('user_id') user_doc: Dict[str, Any] = {} db_ref = None if user_id: try: db_ref = get_db() user_doc = _request_user_doc(user_id) or {} except Exception: # fail-soft כמו כל בלוק כאן: דף בלי העדפות המשתמש עדיף על 500. logger.warning("inject_globals: user document unavailable", exc_info=True) user_doc = {} # קביעת גודל גופן מהעדפות משתמש/קוקי font_scale = 1.0 try: cookie_val = request.cookies.get('ui_font_scale') if cookie_val: try: v = float(cookie_val) if 0.85 <= v <= 1.6: font_scale = v except Exception: pass if user_id and user_doc: try: v = float(((user_doc.get('ui_prefs') or {}).get('font_scale')) or font_scale) if 0.85 <= v <= 1.6: font_scale = v except Exception: pass except Exception: pass # ערכת נושא try: from webapp.ui_theme_defaults import get_default_ui_theme_parts theme = get_default_ui_theme_parts()[2] except Exception: theme = "classic" theme_scope = _normalize_theme_scope(request.cookies.get('ui_theme_scope')) use_cookie_theme = False theme_raw = '' try: theme_raw, theme_scope, use_cookie_theme, _ = _resolve_theme_raw_token( user_id, user_doc=user_doc, ) except Exception: theme_raw = theme theme_type, theme_id, theme = _parse_theme_token(theme_raw) # Shared Theme — מהעדפת המשתמש, מה-cookie, או מ-``DEFAULT_UI_THEME``. # ערכה ציבורית היא מידע ציבורי, ולכן הטעינה שלה אינה תלויה בהתחברות. shared_theme = None if theme_type == "shared": shared_theme = _load_shared_theme_for_request(theme_id, user_id=user_id, db_ref=db_ref) if shared_theme is None: theme = "classic" theme_type = "builtin" # ערכת נושא מותאמת (אם קיימת) — מועברת לתבניות כדי לאפשר injection ב-base.html # תומך גם במבנה חדש (custom_themes[]) וגם בישן (custom_theme). custom_theme = None custom_theme_id = "" # ===================================================== # ADMIN IMPERSONATION - חישוב בזמן אמת # ===================================================== # 1. שליפת האמת האבסולוטית (לא תלויה ב-Impersonation) actual_is_admin = False actual_is_premium = False try: if user_id: actual_is_admin = bool(is_admin(int(user_id))) actual_is_premium = bool(is_premium(int(user_id))) except Exception: pass # 2. בדיקת מצב Impersonation עם Fail-Safe # - ?force_admin=1 → עקיפה לשעת חירום # - דגל פעיל + המשתמש אדמין באמת → מצב פעיל force_admin_override = request.args.get('force_admin') == '1' impersonation_flag = session.get(IMPERSONATION_SESSION_KEY, False) if force_admin_override: # 🆘 מנגנון מילוט: האדמין הוסיף ?force_admin=1 ל-URL user_is_impersonating = False else: # מצב Impersonation פעיל רק אם: # א. הדגל פעיל בסשן # ב. המשתמש אכן אדמין (הגנה מפני מניפולציה) user_is_impersonating = bool(impersonation_flag and actual_is_admin) # 3. חישוב הסטטוס האפקטיבי לתצוגה # - אם מתחזים → לא אדמין, לא פרימיום (רואים כמשתמש רגיל) # - אחרת → הסטטוס האמיתי if user_is_impersonating: effective_is_admin = False effective_is_premium = False else: effective_is_admin = actual_is_admin effective_is_premium = actual_is_premium # 4. user_is_admin משמש את ה-UI (מקבל את הערך האפקטיבי) user_is_admin = effective_is_admin def _normalize_custom_theme_doc(doc: dict, *, force_active: bool = False) -> dict: tdoc = dict(doc or {}) if not isinstance(tdoc.get('variables'), dict): tdoc = {**tdoc, 'variables': {}} if not isinstance(tdoc.get('syntax_css', ''), str): tdoc = {**tdoc, 'syntax_css': ''} if not isinstance(tdoc.get('syntax_colors'), dict): tdoc = {**tdoc, 'syntax_colors': {}} if force_active: tdoc = {**tdoc, 'is_active': True} return tdoc try: if user_id and user_doc: themes = user_doc.get('custom_themes') # בחירה לפי מזהה (כשנבחר custom: במכשיר הנוכחי) if theme_type == "custom" and theme_id and isinstance(themes, list): for tdoc in themes: if not isinstance(tdoc, dict): continue t_id = str(tdoc.get('id') or '').strip() if t_id and t_id == str(theme_id).strip(): custom_theme = _normalize_custom_theme_doc(tdoc, force_active=True) custom_theme_id = t_id break # מבנה חדש (מערך) – עדיפות if not custom_theme and isinstance(themes, list) and themes: for tdoc in themes: if isinstance(tdoc, dict) and tdoc.get('is_active'): custom_theme = _normalize_custom_theme_doc(tdoc) custom_theme_id = str(tdoc.get('id') or '').strip() break # Fallback למבנה ישן (אובייקט בודד) if not custom_theme: ct = user_doc.get('custom_theme') if isinstance(ct, dict) and ct: custom_theme = _normalize_custom_theme_doc(ct, force_active=(theme_type == "custom")) ct_id = str(ct.get('id') or '').strip() if ct_id: custom_theme_id = ct_id except Exception: custom_theme = None custom_theme_id = "" # Safety: אל תאפשר theme=custom בלי custom_theme פעיל. try: ct_active = bool(custom_theme and isinstance(custom_theme, dict) and custom_theme.get('is_active')) except Exception: ct_active = False if theme == 'custom' and not ct_active: theme = 'classic' theme_type = "builtin" # SRI map (optional): only set if provided via env to avoid mismatches sri_map = {} try: if FA_SRI_HASH: sri_map['fa'] = FA_SRI_HASH except Exception: sri_map = {} # Bust static cache optionally per-request (for debugging/force-refresh) try: no_cache_param = (request.args.get('no_cache') or request.args.get('nc') or '').strip().lower() force_bust = no_cache_param in ('1', 'true', 'yes') except Exception: force_bust = False try: static_ver = _STATIC_VERSION + ('.' + str(int(_time.time())) if force_bust else '') except Exception: static_ver = _STATIC_VERSION ui_theme_custom_id = custom_theme_id if theme == "custom" else "" # גופן הפתקים. ``fail-soft`` כמו שאר ההזרקה כאן: תקלה בהכרעה מחזירה # ברירת מחדל ואינה מפילה רינדור של כל עמוד באתר. try: note_fonts, note_fonts_scope = _resolve_note_fonts(user_id, user_doc) except Exception: note_fonts, note_fonts_scope = _note_fonts_default(), THEME_SCOPE_GLOBAL # גודל הטקסט בפתק. אותה הזרקה fail-soft, ואותו ``user_doc``. try: note_font_size, note_font_size_scope = _resolve_note_font_size(user_id, user_doc) except Exception: note_font_size, note_font_size_scope = NOTE_FONT_SIZE_DEFAULT, THEME_SCOPE_GLOBAL # התצוגה המצומצמת בעמוד הקבצים. ``user_doc`` כבר נשלף למעלה, ולכן אין # כאן קריאה נוספת למסד. fail-soft כמו שכניו: תקלה מחזירה את התצוגה המלאה. try: files_compact_view = _resolve_files_compact_view(user_id, user_doc) except Exception: files_compact_view = False return { 'bot_username': BOT_USERNAME_CLEAN, 'ui_font_scale': font_scale, 'ui_theme': theme, 'ui_theme_scope': theme_scope, 'note_fonts': note_fonts, 'note_fonts_scope': note_fonts_scope, 'note_font_size': note_font_size, 'note_font_size_scope': note_font_size_scope, # ברירת המחדל עצמה, ולא ההכרעה של המשתמש: הלוח מכריע בדפדפן, לפי ``localStorage``, ונופל לכאן. 'note_font_size_default': NOTE_FONT_SIZE_DEFAULT, 'files_compact_view': files_compact_view, 'ui_theme_custom_id': ui_theme_custom_id, 'custom_theme': custom_theme, 'shared_theme': shared_theme, # הרשאות (אפקטיביות - לשימוש ה-UI) 'user_is_admin': user_is_admin, 'user_is_premium': effective_is_premium, # --- Admin Impersonation --- 'user_is_impersonating': user_is_impersonating, 'actual_is_admin': actual_is_admin, 'can_impersonate': actual_is_admin, # Feature flags 'announcement_enabled': WEEKLY_TIP_ENABLED, 'weekly_tip_enabled': WEEKLY_TIP_ENABLED, # גרסה סטטית לצירוף לסטטיקה (cache-busting) 'static_version': static_ver, # קישור לתיעוד (לשימוש בתבניות) 'documentation_url': DOCUMENTATION_URL, # תקרת אורך פתק — מגיעה ל-JS מכאן ולא מוקלדת שם. בלי זה היו שני # מספרים שמסונכרנים בתקווה, ופער ביניהם נראה למשתמש כחיתוך בלי הסבר. 'max_note_chars': MAX_NOTE_CHARS_FOR_TEMPLATES, # תקרת תגובה בשרשור על פתק (``note_threads.MAX_COMMENT_CHARS``) — מונה התווים # בחלונית קורא אותה מכאן, באותו נימוק כמו ``max_note_chars`` שמעל. 'max_thread_comment_chars': MAX_THREAD_COMMENT_CHARS_FOR_TEMPLATES, # ימי השהות בסל — מאותה סיבה בדיוק: המודאל בעמוד הקובץ הבטיח "30 # יום" כמספר מוקלד, ולכן שינוי בקונפיג לא היה מגיע אליו. 'recycle_ttl_days': RECYCLE_TTL_DAYS, # תוקף הקישור הזמני במודאל השיתוף, מאותה סיבה: המודאל אמר רק "זמני", # ומספר מוקלד לידו היה נשאר מאחור ברגע ש-``PUBLIC_SHARE_TTL_DAYS`` משתנה. 'public_share_ttl_label': _hebrew_day_count(PUBLIC_SHARE_TTL_DAYS), # חלון הייצוא המעוצב: האם הקובץ נבנה בדפדפן, וטקסט ההערה שהשלד מחזיק במקום התוכן (מאותו קבוע שהשלד # נבנה ממנו). כאן ולא בכל אחת מקריאות ה-render של עמוד הקובץ, כדי שלא יהיו כמה עותקים שצריך לזכור. 'styled_export_browser_render': STYLED_EXPORT_BROWSER_RENDER, 'styled_export_content_marker': EDITOR_EXPORT_CONTENT_MARKER_TEXT, # External uptime config for templates (non-sensitive only) 'uptime_provider': UPTIME_PROVIDER, 'uptime_status_url': UPTIME_STATUS_URL, 'uptime_widget_script_url': UPTIME_WIDGET_SCRIPT_URL, 'uptime_widget_id': UPTIME_WIDGET_ID, # SRI hashes for CDN assets (optional; provided via env) 'cdn_sri': sri_map if sri_map else None, } # --- Theme helpers (single source of truth) --- ALLOWED_UI_THEMES = { 'classic', 'ocean', 'high-contrast', 'dark', 'dim', 'rose-pine-dawn', 'nebula', 'custom', } THEME_SCOPE_GLOBAL = "global" THEME_SCOPE_DEVICE = "device" _THEME_SCOPE_VALUES = {THEME_SCOPE_GLOBAL, THEME_SCOPE_DEVICE} _THEME_ID_SAFE_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{1,63}$") from webapp.ui_theme_defaults import get_default_ui_theme_parts, get_default_ui_theme_raw def _normalize_theme_scope(value: Optional[str]) -> str: v = str(value or "").strip().lower() return v if v in _THEME_SCOPE_VALUES else THEME_SCOPE_GLOBAL def _device_scoped_theme_cookie() -> str: """הערכה שנבחרה "רק במכשיר הזה" במכשיר של הבקשה, מנורמלת — או ``''`` כשאין כזו. ערכה במצב ``device`` אינה נכתבת למסד: היא ה-cookie ``ui_theme`` לצד ``ui_theme_scope`` ששווה ל-``THEME_SCOPE_DEVICE``. זה הכלל לשאלה "האם ה-cookie מכריע את הערכה", ומי שצריך אותו קורא כאן ולא את שני ה-cookies בעצמו: ``_resolve_theme_raw_token``, ``_etag_needs_user_doc``, והדשבורד, שמעביר את התשובה לצעד הערכה של הצ'קליסט "צעדים ראשונים" (``webapp/routes/dashboard_routes.py``). """ if _normalize_theme_scope(request.cookies.get('ui_theme_scope')) != THEME_SCOPE_DEVICE: return '' return (request.cookies.get('ui_theme') or '').strip().lower() def _stored_theme_pref(user_doc: Any) -> str: """הערכה ששמורה במסמך המשתמש (``ui_prefs.theme``), מנורמלת — או ``''`` כשאין. זו הבחירה "לכל המכשירים". ``_resolve_theme_raw_token`` קורא כאן, וגם הדשבורד, שמעביר את התשובה לצעד הערכה של הצ'קליסט "צעדים ראשונים" — כדי ששניהם יסכימו מה נחשב ערכה שמורה. השדות נבדקים בטיפוס שלהם: המסמך מגיע מהמסד, ומסמך שנערך ביד יכול לשאת בהם כל דבר. """ if not isinstance(user_doc, dict): return '' prefs = user_doc.get('ui_prefs') if not isinstance(prefs, dict): return '' theme = prefs.get('theme') return theme.strip().lower() if isinstance(theme, str) else '' # ─── גופן הפתקים, לפי משטח ────────────────────────────────────────────── # # שלושת המשטחים שמארחים פתקים. **הסדר הזה הוא הקידוד ל-cookie**, ולכן # ``NOTE_FONT_SURFACES`` הוא המקום **היחיד** בקוד שיודע אותו: הקידוד # והפענוח שניהם נגזרים ממנו, ומשטח רביעי בעתיד **נספח בסוף** ולא נדחף # באמצע. צימוד משמעות למיקום הוא בדיוק מה שנשך ב-``MD_INLINE_RE``, הרג'קס # שקרא פעם את המארקדאון בשורה של פתק, שם הוספה באמצע הייתה מזיזה בשקט את # כל האינדקסים שאחריה. NOTE_FONT_SURFACES = ("repo", "md", "board") # ``[01]{3}`` ולא JSON: הכתיבה ל-cookie למטה מאמתת כל ערך מול # ``re.fullmatch`` כהקשחה מול CodeQL, בדיוק כמו ``font_scale`` ו-``theme``. # שלושה ביטים הם הערך הצר ביותר שאפשר לאמת ב-regex יחיד. _NOTE_FONTS_COOKIE_RE = re.compile(r"[01]{%d}" % len(NOTE_FONT_SURFACES)) def _note_fonts_default() -> Dict[str, bool]: return {name: False for name in NOTE_FONT_SURFACES} def _encode_note_fonts(fonts: Optional[Dict[str, Any]]) -> str: """dict ← מחרוזת ביטים, לפי ``NOTE_FONT_SURFACES``.""" src = fonts if isinstance(fonts, dict) else {} return "".join("1" if src.get(name) else "0" for name in NOTE_FONT_SURFACES) def _decode_note_fonts(raw: Optional[str]) -> Optional[Dict[str, bool]]: """מחרוזת ביטים ← dict. ``None`` כשהערך אינו תקין — לא זריקה. מוחזר ``None`` ולא ברירת מחדל, כדי שהקורא יבחין בין "המכשיר הזה לא אמר כלום" לבין "המכשיר הזה אמר: הכל רגיל". ההבחנה הזו היא כל ההבדל בהכרעת התחולה: הראשון נופל ל-DB, השני גובר עליו. """ val = str(raw or "").strip() if not _NOTE_FONTS_COOKIE_RE.fullmatch(val): return None return {name: val[i] == "1" for i, name in enumerate(NOTE_FONT_SURFACES)} def _resolve_note_fonts( user_id: Optional[int], user_doc: Optional[Dict[str, Any]], ) -> tuple[Dict[str, bool], str]: """מחזיר ``(fonts, scope)`` — ערך המכשיר גובר רק במצב ``device``. זו אותה הכרעה בדיוק שמבצע ``_resolve_theme_raw_token`` עבור ערכת הנושא: cookie של המכשיר גובר **רק** כשה-cookie של התחולה אומר ``device``; בכל מקרה אחר ה-DB הוא המקור. במצב ``device`` הערך אינו נכתב ל-DB כלל, ולכן טאבלט וטלפון אינם דורסים זה את זה. ``_resolve_theme_raw_token`` **לא** עבר לכאן במכוון — זה היה מרחיב דיף של פיצ'ר לנגיעה במסלול הערכות. הוא המקור לצורה, לא נצרך ממנה. """ scope = _normalize_theme_scope(request.cookies.get('ui_note_fonts_scope')) device_fonts = _decode_note_fonts(request.cookies.get('ui_note_fonts')) if scope == THEME_SCOPE_DEVICE and device_fonts is not None: return device_fonts, scope # שליפה עצלה **רק** כשההכרעה הגיעה לכאן: במצב ``device`` עם ערך תקין # אין קריאה למסד כלל. ``_resolve_theme_raw_token`` עושה בדיוק את זה. if user_id and user_doc is None: try: user_doc = get_db().users.find_one( {'user_id': int(user_id)}, {'ui_prefs.note_fonts': 1} ) or {} except Exception: user_doc = None if user_id and isinstance(user_doc, dict): stored = (user_doc.get('ui_prefs') or {}).get('note_fonts') if isinstance(stored, dict): # ``is True`` ולא ``bool()``: ``bool("false")`` הוא ``True``, וכך # מסמך שנערך ביד או שנכתב לפני שהוולידציה נוספה היה מדליק את # הגופן דווקא כשהערך אומר את ההפך. הוולידציה ב-``/api/ui_prefs`` # סוגרת את הדלת קדימה; זה מגן על מה שכבר בפנים. return {name: stored.get(name) is True for name in NOTE_FONT_SURFACES}, scope return _note_fonts_default(), scope # ─── גודל הטקסט בפתק, מעמוד ההגדרות ───────────────────────────────────── # # **הגדרה אחת לשני משטחים** — דפדפן הריפו וקבצי Markdown — ולא אחת לכל # אחד. הלוחות **אינם** כאן: להם בורר משלהם במודאל הלוח, שנשמר # ב-``localStorage`` לכל לוח בנפרד. **אבל ברירת המחדל של שניהם היא אחת** — # ``NOTE_FONT_SIZE_DEFAULT`` שלמטה — ראו שם. # # הערכים הם הטוקנים ש-``STICKY_NOTE_FONT_MENUS.settings`` מציע # ב-``_note_fonts_head.html``, ומי ששומר על שני המקורות מיושרים הוא # בדיקה שמשווה ביניהם — בדיוק כמו הבורר שבמודאל הלוח מול המפה. # # **``mid`` ו-``lg`` אינם כאן בכוונה.** הם גדלים מהסולם שלפני אוקטובר # 2026, ויש משתמשים ששמרו אותם — ב-``ui_prefs.note_font_size`` וב-cookie # ``ui_note_font_size``. כאן הם נדחים כמו כל ערך לא מוכר: ``_decode_note_font_size`` # מחזירה ``None``, ושמירה חדשה שלהם נענית 400. cookie כזה במצב ``device`` # נופל לבחירה המשותפת שבמסד, ושדה כזה במסד — לברירת המחדל. הנימוק # לשמות החדשים, ולמה אין להחזיר את הישנים, ליד ``STICKY_NOTE_FONT_SIZES``. NOTE_FONT_SIZE_VALUES = ("normal", "large", "xlarge") #: הגודל של מי שעוד לא בחר — **בעמוד ההגדרות ובכל לוח**. המקום היחיד שקובע אותו: ``inject_globals`` #: מעביר אותו לתבניות כ-``note_font_size_default``, ו-``_note_fonts_head.html`` מרנדר אותו #: ל-``window.STICKY_NOTE_FONT_SIZE_DEFAULT``, שממנו הלוח קורא בכל מקום שבו חסרה בחירה. #: #: **"גדול מאוד" מנובמבר 2026, לבקשת המשתמש; עד אז "רגיל".** בחירה שנשמרה נשארת: בעמוד ההגדרות כל #: בחירה נשמרת במסד וב-cookie, גם "רגיל". בלוח, עד אותו שינוי, "רגיל" נשמר כהיעדר מפתח — ולכן לוח #: שבחרו בו "רגיל" עבר ל"גדול מאוד" כמו לוח שלא בחרו בו כלום. מאז הלוח שומר כל בחירה, כדי ששינוי #: עתידי כאן לא יגיע לבחירה של אף אחד. NOTE_FONT_SIZE_DEFAULT = "xlarge" def _decode_note_font_size(raw: Any) -> Optional[str]: """טוקן גודל תקין, או ``None`` כשלא נאמר כלום או שהערך פגום. ``None`` ולא ברירת מחדל, מאותה סיבה בדיוק כמו ב-``_decode_note_fonts``: "המכשיר הזה לא אמר כלום" נופל ל-DB, ואילו "המכשיר הזה אמר: רגיל" גובר עליו. פענוח שמחזיר ברירת מחדל בשני המקרים מוחק את ההבחנה. **בדיקת הטיפוס באה ראשונה, ולא כנימוס.** הערך מגיע מ-cookie או מגוף JSON — כלומר מחוץ לתהליך — ו-``.strip()`` על מה שאינו מחרוזת זורק. """ if not isinstance(raw, str): return None val = raw.strip() return val if val in NOTE_FONT_SIZE_VALUES else None def _resolve_note_font_size( user_id: Optional[int], user_doc: Optional[Dict[str, Any]], ) -> tuple[str, str]: """מחזיר ``(size, scope)`` — ערך המכשיר גובר רק במצב ``device``. אותה הכרעה בדיוק כמו ``_resolve_note_fonts``, על cookie משלה: המשתמש ביקש בורר תחולה **נפרד** לגודל, כדי שיוכל להחזיק גודל אחד בטאבלט וכתב יד בכל המכשירים. """ scope = _normalize_theme_scope(request.cookies.get('ui_note_font_size_scope')) device_size = _decode_note_font_size(request.cookies.get('ui_note_font_size')) if scope == THEME_SCOPE_DEVICE and device_size is not None: return device_size, scope # שליפה עצלה **רק** כשההכרעה הגיעה לכאן, כמו אצל שכנתה. if user_id and user_doc is None: try: user_doc = get_db().users.find_one( {'user_id': int(user_id)}, {'ui_prefs.note_font_size': 1} ) or {} except Exception: user_doc = None if user_id and isinstance(user_doc, dict): # ``isinstance`` על ``ui_prefs`` ולא ``or {}``: מסמך שנערך ביד יכול # להחזיק שם מחרוזת, ול-מחרוזת אין ``.get``. prefs = user_doc.get('ui_prefs') stored = _decode_note_font_size( prefs.get('note_font_size') if isinstance(prefs, dict) else None ) if stored is not None: return stored, scope return NOTE_FONT_SIZE_DEFAULT, scope def _note_fonts_etag_key( user_id: Optional[int], *, user_doc: Optional[Dict[str, Any]] = None, ) -> str: """מפתח קצר שמייצג את גופן הפתקים הנוכחי, ל-ETag ולמפתח הקאש. **למה זה נחוץ:** ``_note_fonts_head.html`` מרנדר את ההעדפה **לתוך ה-HTML**. בלי שהיא תיכנס לוולידטור, שינוי ההגדרה אינו משנה את ה-ETag, השרת מחזיר 304, והדפדפן מציג את העמוד הישן עם הדגל הישן — בלי קשר לשאלה אם קאש ה-Redis דלוק, כי מסלול ה-304 אינו נוגע בו. ``theme`` כבר נמצא ב-ETag ובמפתח הקאש מאותה סיבה בדיוק; זה אותו כלל שמוחל על הערך השני שמרונדר פר-משתמש. **המפתח נושא את שתי ההעדפות של גופן הפתקים** — כתב היד וגודל הטקסט — כי שתיהן מרונדרות לתוך אותו ``head``. הגודל שהתווסף מאוחר יותר היה נופל בדיוק לאותה מלכודת אילו נשאר בחוץ. """ try: fonts, _ = _resolve_note_fonts(user_id, user_doc) size, _ = _resolve_note_font_size(user_id, user_doc) return "nf:" + _encode_note_fonts(fonts) + ":" + size except Exception: return "nf:" + _encode_note_fonts(None) + ":" + NOTE_FONT_SIZE_DEFAULT # ─── ערכת המסמך ───────────────────────────────────────────────────────── # # ערכה מותאמת או ציבורית שחלה רק על כרטיס "תצוגת Markdown" ב-``/md/``, בזמן שהממשק סביבו נשאר בערכה # הפעילה. ההעדפה היא **מצביע** לערכה — ``custom:`` או ``shared:``, הפורמט של ``ui_prefs.theme`` — ולא # העתק שלה, ולכן עריכה של הערכה בבונה הערכות מגיעה למסמך מעצמה. התחולה כמו של גודל הטקסט בפתק: במצב ``device`` # הבחירה ב-cookie של המכשיר בלבד, ובכל מצב אחר במסד. ה-CSS נבנה ב-``build_md_doc_theme_css`` # (``services/theme_parser_service.py``), והתנאי שבו הוא חל כתוב שם בבורר ``MD_DOC_THEME_ROOT_SELECTOR``. # docs/webapp/custom_themes_guide.rst, md-doc-theme. #: השדה תחת ``ui_prefs``. חסר = אין ערכת מסמך. MD_DOC_THEME_PREF = "md_doc_theme" MD_DOC_THEME_COOKIE = "ui_md_doc_theme" MD_DOC_THEME_SCOPE_COOKIE = "ui_md_doc_theme_scope" #: הערך ב-cookie של המכשיר שאומר "כבויה במכשיר הזה". בלעדיו כיבוי במצב ``device`` לא היה יכול לגבור על בחירה #: ששמורה במסד: cookie חסר פירושו "המכשיר לא אמר כלום", וההכרעה נופלת למסד. MD_DOC_THEME_DEVICE_OFF = "none" def _decode_md_doc_theme(raw: Any) -> Optional[str]: """``custom:`` או ``shared:`` מנורמל; ``""`` לכבויה (רק ``MD_DOC_THEME_DEVICE_OFF``); ``None`` כשלא נאמר כלום או שהערך פגום. ``None`` ולא ``""`` על ערך פגום, מאותה סיבה כמו ב-``_decode_note_font_size``: "המכשיר לא אמר כלום" נופל למסד, ו"המכשיר אמר: כבויה" גובר עליו. ולא ``_parse_theme_token``: הוא מחזיר את ערכת ברירת המחדל על ערך פגום, ואם היא ציבורית ערך פגום היה נקרא כבחירה בה; וערכה מובנית אינה ערכת מסמך. הבדיקה של המזהה — ``_THEME_ID_SAFE_RE``, כמו שם. הערך מגיע מ-cookie, מגוף JSON או מהמסד, ולכן הטיפוס נבדק לפני כל דבר. """ if not isinstance(raw, str): return None val = raw.strip().lower() if val == MD_DOC_THEME_DEVICE_OFF: return "" kind, sep, theme_id = val.partition(":") if sep and kind in ("custom", "shared") and _THEME_ID_SAFE_RE.fullmatch(theme_id): return f"{kind}:{theme_id}" return None def _resolve_md_doc_theme_token( user_id: Optional[int], user_doc: Optional[Dict[str, Any]] = None, *, strict: bool = False, ) -> tuple[str, str, Optional[Dict[str, Any]]]: """``(token, scope, user_doc)`` — ``token`` ריק כשאין ערכת מסמך; ערך המכשיר גובר רק במצב ``device``. אותה הכרעה כמו ``_resolve_note_font_size``. מסמך המשתמש נשלף רק כשההכרעה מגיעה למסד, דרך ``_request_user_doc`` — השליפה ש-``inject_globals`` עושה ממילא באותה בקשה — והוא מוחזר, כדי שמי שטוען את הערכה לא ישלוף שוב. ``user_doc`` שמועבר חייב לכלול את ``ui_prefs.md_doc_theme`` ואת ``custom_themes`` (``ETAG_USER_PROJECTION`` כולל את שניהם). כשל במסד — ``_request_user_doc`` כבר רושם אותו ומחזיר ``None`` — מחזיר "אין ערכת מסמך": העמוד מוצג בערכת הממשק. ``strict`` הופך את הכשל הזה ל-``MdDocThemeUnavailable``, בשביל מי שמציג את הבחירה עצמה ולא את המסמך (``api_md_doc_theme_state``): שם "אין ערכת מסמך" היה מוצג כ"ללא", כשהתשובה האמיתית היא "לא ידוע". הכרעה שנגמרת ב-cookie של המכשיר אינה פונה למסד, ולכן אינה נכשלת גם ב-``strict``. """ scope = _normalize_theme_scope(request.cookies.get(MD_DOC_THEME_SCOPE_COOKIE)) device_value = _decode_md_doc_theme(request.cookies.get(MD_DOC_THEME_COOKIE)) if scope == THEME_SCOPE_DEVICE and device_value is not None: return device_value, scope, user_doc if user_id and user_doc is None: user_doc = _request_user_doc(user_id) if user_doc is None and strict: # ``_request_user_doc`` מחזיר ``None`` רק כשהמסד לא ענה (מסמך חסר הוא ``{}``), והוא כבר רשם את הכשל. raise MdDocThemeUnavailable("user_doc") if not isinstance(user_doc, dict): return "", scope, user_doc # ``isinstance`` על ``ui_prefs`` ולא ``or {}``: מסמך שנערך ביד יכול להחזיק שם מחרוזת. prefs = user_doc.get('ui_prefs') stored = _decode_md_doc_theme(prefs.get(MD_DOC_THEME_PREF) if isinstance(prefs, dict) else None) return stored or "", scope, user_doc class MdDocThemeUnavailable(Exception): """המסד לא ענה בטעינת ערכת המסמך — שונה מ"הערכה לא קיימת", שהוא ``None``.""" def _load_md_doc_theme( user_id: Optional[int], token: str, user_doc: Optional[Dict[str, Any]], ) -> Optional[Dict[str, Any]]: """הערכה ש-``token`` מצביע עליה: ``{token, name, variables, syntax_css, updated_at}``, או ``None`` כשאין כזו. שני ערוצים, כי לקוראים יש שתי החלטות שונות: ``None`` — אין ``token``, או שהערכה לא קיימת (נמחקה, או ערכה ציבורית שכובתה); ``MdDocThemeUnavailable`` — המסד לא ענה, ואי אפשר לדעת. העמוד מציג בשני המקרים את המסמך בערכת הממשק (``_resolve_md_doc_theme``), אבל ``/api/ui_prefs`` עונה 404 על הראשון ו-503 על השני — "לא נמצא" ו"נשבר" לא נראים אותו דבר. ערכה אישית נקראת מ-``custom_themes`` במסמך המשתמש; ציבורית — טרייה מ-``shared_themes``, כי ה-ETag של העמוד נגזר מה-``updated_at`` שלה (הנימוק ב-``_get_shared_theme_cached``). """ kind, _, theme_id = (token or "").partition(":") if kind == "custom" and theme_id: if user_doc is None and user_id: user_doc = _request_user_doc(user_id) if user_doc is None: # ``_request_user_doc`` מחזיר ``None`` רק כשהמסד לא ענה, והוא כבר רשם את הכשל. raise MdDocThemeUnavailable(token) themes = user_doc.get('custom_themes') if isinstance(user_doc, dict) else None if not isinstance(themes, list): return None for tdoc in themes: if isinstance(tdoc, dict) and str(tdoc.get('id') or '').strip() == theme_id: variables = tdoc.get('variables') syntax_css = tdoc.get('syntax_css') return { 'token': token, 'name': str(tdoc.get('name') or ''), 'variables': variables if isinstance(variables, dict) else {}, 'syntax_css': syntax_css if isinstance(syntax_css, str) else '', 'updated_at': tdoc.get('updated_at'), } return None if kind == "shared" and theme_id: db_ref = get_db() if db_ref is None: # ``get_db`` מחזיר ``None`` בחלון הצינון שאחרי כשל התחברות, והכשל עצמו כבר נרשם שם. raise MdDocThemeUnavailable(token) try: doc = db_ref.shared_themes.find_one({'_id': theme_id, 'is_active': True}) except PyMongoError as exc: raise MdDocThemeUnavailable(token) from exc theme = _shared_theme_from_doc(doc) if theme is None: return None return { 'token': token, 'name': str(theme.get('name') or ''), 'variables': theme.get('colors') or {}, 'syntax_css': theme.get('syntax_css') or '', 'updated_at': doc.get('updated_at') if isinstance(doc, dict) else None, } return None def _resolve_md_doc_theme( user_id: Optional[int], user_doc: Optional[Dict[str, Any]] = None, ) -> Optional[Dict[str, Any]]: """ערכת המסמך של הבקשה — ``_load_md_doc_theme`` על מה ש-``_resolve_md_doc_theme_token`` הכריע — או ``None``. הכרעה אחת לבקשה, שממנה נגזרים גם ה-ETag ומפתח הקאש של ``/md/`` וגם ה-CSS שמרונדר — כך שהם לא יכולים לתאר שני מצבים שונים. """ token, _, user_doc = _resolve_md_doc_theme_token(user_id, user_doc) if not token: return None try: return _load_md_doc_theme(user_id, token, user_doc) except MdDocThemeUnavailable as exc: # המסמך מוצג בערכת הממשק במקום בערכה שנבחרה לו — נרשם, כדי שאפשר יהיה לספור כמה פעמים זה קרה. logger.warning( "md doc theme %s: DB unavailable (%s); showing the document in the UI theme", token, type(exc.__cause__).__name__ if exc.__cause__ else "no connection", ) return None def _md_doc_theme_etag_key(theme: Optional[Dict[str, Any]]) -> str: """מפתח קצר לערכת המסמך, ל-ETag ולמפתח הקאש של ``/md/``; ``""`` כשאין. ה-CSS שלה מרונדר לתוך ה-HTML, ולכן בלי המפתח בחירה, כיבוי או עריכה של הערכה היו מחזירים 304 עם המראה הישן — אותו נימוק כמו ב-``_note_fonts_etag_key``. ``updated_at`` מקודם בכל עריכה של ערכה אישית (``update_theme``) ושל ציבורית. בלעדיו — בלי חותמת, ולא ``_safe_dt_from_doc``, שמחזיר את השעה הנוכחית על ``None`` ומשנה את המפתח בכל בקשה. """ if not theme: return "" stamp = "" updated_at = theme.get('updated_at') if updated_at is not None: stamp = _safe_dt_from_doc(updated_at).isoformat() return f"dt:{theme.get('token')}:{stamp}" def _md_doc_theme_template_context(theme: Optional[Dict[str, Any]]) -> Optional[Dict[str, str]]: """מה ש-``md_preview.html`` ו-``base.html`` מקבלים: ``{name, css}``, או ``None`` כשאין ערכת מסמך.""" if not theme: return None return { 'name': theme.get('name') or '', 'css': build_md_doc_theme_css(theme.get('variables'), theme.get('syntax_css')), } #: מפתח ההעדפה של התצוגה המצומצמת בעמוד הקבצים, תחת ``ui_prefs``. #: השם צר בכוונה. ``webapp/FEATURE_SUGGESTIONS/DISPLAY_MODES_SPECIFICATION.md`` #: מציע ``display_mode`` עם ``focus``/``classic``/``power``, אבל זו טיוטה #: שלא מומשה ושני המצבים שלה שונים לגמרי — ``focus`` מסתיר גם את כל #: הכפתורים ומוסיף רקע מטושטש, ו-``power`` הופך את הרשימה לטבלה ו**מוסיף** #: מידע. שם רחב היה מצהיר על מימוש שלא קרה, ומתנגש ביום שהאפיון ההוא ייבנה. FILES_COMPACT_VIEW_PREF = "files_compact_view" def _resolve_files_compact_view( user_id: Optional[int], user_doc: Optional[Dict[str, Any]] = None, ) -> bool: """האם עמוד הקבצים מוצג במצב מצומצם. ברירת המחדל היא ``False``. **הכרעה אחת לכל בקשה, ולא רק פונקציה אחת.** ``/files`` בונה את מפתח הקאש לפני הרינדור, ו-``inject_globals`` מזין את התבנית — שתי קריאות נפרדות באותה בקשה. אילו כל אחת הייתה קוראת את המסד בנפרד, שינוי העדפה שנוחת בין השתיים היה גורם ל-HTML של מצב אחד להישמר תחת התגית של המצב השני, והמשתמש היה רואה בדיוק את ההפך ממה שביקש עד שה-TTL פוקע. לכן התוצאה נשמרת על ``g`` — ההיקף היחיד שמובטח שהוא בדיוק בקשה אחת. מחוץ להקשר בקשה (בדיקות יחידה) אין ``g``, והפונקציה פשוט אינה זוכרת. **בלי בורר תחולה global/device ובלי cookie**, בשונה מגופן הפתקים: אין כאן צורך אמיתי בהעדפה שונה פר-מכשיר, וכל cookie חדש היה נכנס לרשימת ``needs_cookie_update`` שב-``/api/ui_prefs`` — שומר שכבר בלע בשקט את ``ui_note_fonts`` כשהוא נשכח. ``is True`` ולא ``bool()``: ``bool("false")`` הוא ``True``, ולכן מסמך שנערך ביד או שנכתב לפני שהוולידציה נוספה היה מדליק את המצב דווקא כשהערך אומר את ההפך. אותו שיקול בדיוק כמו ב-``_resolve_note_fonts``. """ cache_attr = '_files_compact_view' try: cached = getattr(g, cache_attr) except (RuntimeError, AttributeError): # ``RuntimeError`` — אין הקשר בקשה; ``AttributeError`` — יש, וטרם נקבע. cached = None if cached is not None: return cached resolved = False if user_id: # שליפה מוקרנת ועצלה, כמו ב-``_resolve_note_fonts``: הקורא שכבר מחזיק # את מסמך המשתמש (``inject_globals``) אינו משלם על קריאה שנייה. if user_doc is None: try: user_doc = get_db().users.find_one( {'user_id': int(user_id)}, {f'ui_prefs.{FILES_COMPACT_VIEW_PREF}': 1} ) or {} except Exception: user_doc = None if isinstance(user_doc, dict): resolved = (user_doc.get('ui_prefs') or {}).get(FILES_COMPACT_VIEW_PREF) is True try: setattr(g, cache_attr, resolved) except RuntimeError: pass # מחוץ להקשר בקשה — אין מה לזכור return resolved def _parse_theme_token(raw: Optional[str]) -> tuple[str, str, str]: """מפרק ערכת נושא: (type, id, theme_attr).""" default_type, default_id, default_attr = get_default_ui_theme_parts() val = str(raw or "").strip() if not val: return default_type, default_id, default_attr low = val.lower() if low.startswith("shared:"): theme_id = low.split(":", 1)[1].strip() if theme_id and _THEME_ID_SAFE_RE.fullmatch(theme_id): return "shared", theme_id, f"shared:{theme_id}" return default_type, default_id, default_attr if low.startswith("custom:"): theme_id = low.split(":", 1)[1].strip() if theme_id and _THEME_ID_SAFE_RE.fullmatch(theme_id): return "custom", theme_id, "custom" return default_type, default_id, default_attr if low == "custom": return "custom", "", "custom" if low in ALLOWED_UI_THEMES: return "builtin", low, low return default_type, default_id, default_attr def _resolve_theme_raw_token( user_id: Optional[int], *, user_doc: Optional[Dict[str, Any]] = None, projection: Optional[Dict[str, int]] = None, ) -> Tuple[str, str, bool, Optional[Dict[str, Any]]]: """מחזיר theme_raw לפי cookie/DB, כולל scope ומסמך משתמש (אם נשלף).""" theme_scope = _normalize_theme_scope(request.cookies.get('ui_theme_scope')) cookie_theme = (request.cookies.get('ui_theme') or '').strip().lower() use_cookie_theme = bool(_device_scoped_theme_cookie()) theme_raw = cookie_theme or '' if user_id and not use_cookie_theme: if user_doc is None: try: db_ref = get_db() if projection is None: projection = {'ui_prefs.theme': 1} elif 'ui_prefs.theme' not in projection: projection = dict(projection) projection['ui_prefs.theme'] = 1 user_doc = db_ref.users.find_one( {'user_id': int(user_id)}, projection, ) or {} except Exception: user_doc = None pref = _stored_theme_pref(user_doc) if pref: theme_raw = pref if not theme_raw: theme_raw = get_default_ui_theme_raw() return theme_raw, theme_scope, use_cookie_theme, user_doc # ─── ערכה ציבורית (shared:) לרינדור ─────────────────────────────── #: כמה זמן מבקר שאינו מחובר מקבל ערכה ציבורית מהזיכרון בלי לפנות למסד. זה #: גם הגבול לכמה זמן מבקר עוד רואה ערכה אחרי שאדמין ערך או כיבה אותה: אין #: ניקוי בזמן כתיבה, ומה שמגביל את ההתיישנות הוא הערך הזה. _SHARED_THEME_CACHE_TTL_SECONDS = 60.0 #: ``theme_id`` ← (מועד תפוגה לפי ``_time.monotonic()``, הערכה המנורמלת) _SHARED_THEME_CACHE: Dict[str, Tuple[float, Dict[str, Any]]] = {} _SHARED_THEME_CACHE_LOCK = threading.Lock() def _shared_theme_from_doc(doc: Any) -> Optional[Dict[str, Any]]: """ממיר מסמך מ-``shared_themes`` למבנה ``shared_theme`` שהתבניות קוראות. ``None`` כשאין מסמך תקין. כל שדה נבדק בטיפוס שלו: הוא מגיע מהמסד, ומסמך שנערך ביד יכול לשאת שם כל דבר. """ if not isinstance(doc, dict) or not doc.get("_id"): return None colors = doc.get("colors", {}) if not isinstance(colors, dict): colors = {} syntax_css = doc.get("syntax_css", "") if not isinstance(syntax_css, str): syntax_css = "" syntax_colors = doc.get("syntax_colors", {}) if not isinstance(syntax_colors, dict): syntax_colors = {} return { "id": doc.get("_id"), "name": doc.get("name"), "description": doc.get("description", ""), "colors": colors, "syntax_css": syntax_css, "syntax_colors": syntax_colors, "is_featured": bool(doc.get("is_featured", False)), } def _fetch_shared_theme(db_ref, theme_id: str) -> Optional[Dict[str, Any]]: """שליפה טרייה של ערכה ציבורית פעילה. ``None`` — אין ערכה פעילה בשם הזה (לא קיימת, או ש-``is_active`` כבוי). כשל במסד **זורק** ואינו מתורגם ל-``None``, כדי ש"לא נמצא" ו"נשבר" לא ייראו אותו דבר. """ doc = db_ref.shared_themes.find_one({"_id": theme_id, "is_active": True}) return _shared_theme_from_doc(doc) def _get_shared_theme_cached(theme_id: str) -> Optional[Dict[str, Any]]: """ערכה ציבורית למבקר שאינו מחובר, דרך קאש בזיכרון של התהליך. החוזה הוא של ``_fetch_shared_theme``: ערכה, או ``None`` כשאין ערכה פעילה, וכשל במסד זורק. יוצא אחד: ``get_db()`` מחזיר ``None`` בחלון הצינון שאחרי כשל התחברות (ה-docstring שלו), וזה חוזר מכאן כ-``None``. הכשל עצמו כבר נרשם ב-``get_db`` ברגע שקרה, ורישום שלו שוב בכל בקשה בתוך החלון היה רק רעש. **נשמרת רק ערכה שנמצאה.** ``theme_id`` יכול להגיע מ-cookie שהלקוח שולט בו, וקאש של "לא נמצא" היה גדל לפי מה שנשלח אליו. כך מספר הרשומות חסום במספר הערכות הפעילות בספרייה, וכשל אף פעם אינו נזכר כ"לא קיים". **ולמה רק למבקר.** עמודי הקובץ, ה-md וה-reader מחשבים ETag מ-``updated_at`` טרי (``_get_theme_etag_key``). גוף שנבנה מהקאש תחת ETag טרי היה נשמר בדפדפן, ובבקשה הבאה הוא היה מקבל 304 על הצבעים הישנים, גם אחרי שהקאש פג. העמודים האלה דורשים התחברות, ולכן מבקר אינו מגיע אליהם. """ now = _time.monotonic() with _SHARED_THEME_CACHE_LOCK: hit = _SHARED_THEME_CACHE.get(theme_id) if hit is not None and hit[0] > now: # עותק: מי שמשנה את מה שקיבל לא ישנה את מה שהבקשה הבאה תקבל return copy.deepcopy(hit[1]) db_ref = get_db() if db_ref is None: return None theme = _fetch_shared_theme(db_ref, theme_id) with _SHARED_THEME_CACHE_LOCK: if theme is None: # הערכה נמחקה או כובתה מאז שנשמרה — לא משאירים רשומה שפגה _SHARED_THEME_CACHE.pop(theme_id, None) else: _SHARED_THEME_CACHE[theme_id] = ( _time.monotonic() + _SHARED_THEME_CACHE_TTL_SECONDS, theme, ) return copy.deepcopy(theme) if theme is not None else None def _load_shared_theme_for_request( theme_id: str, *, user_id: Optional[int], db_ref, ) -> Optional[Dict[str, Any]]: """הערכה הציבורית לרינדור הבקשה הנוכחית, או ``None`` ← ``classic``. אינו זורק: ``inject_globals`` רץ בכל רינדור, וחריגה כאן הייתה מפילה כל עמוד באתר. משתמש מחובר נקרא טרי דרך ``db_ref`` שכבר נפתח לבקשה, ומבקר דרך ``_get_shared_theme_cached`` (שם גם הנימוק לחלוקה). """ if not theme_id: return None try: if user_id: if db_ref is None: # המסד כבר נכשל בבקשה הזו, בשליפת המשתמש בראש # ``inject_globals``. ניסיון נוסף כאן היה רק עוד המתנה. return None return _fetch_shared_theme(db_ref, theme_id) return _get_shared_theme_cached(theme_id) except PyMongoError as exc: logger.warning( "shared theme %r: DB read failed (%s); rendering classic", theme_id, type(exc).__name__, ) except Exception: # לא תקלת מסד אלא באג או תצורה (למשל ``MONGODB_URL`` חסר) — נרשם # עם traceback ובתווית משלו, כדי שלא ייספר כתקלת מסד. logger.exception("shared theme %r: unexpected error; rendering classic", theme_id) return None # NOTE: # כל הלוגיקה של Themes API (כולל validation + activate) הועברה ל-`webapp/themes_api.py` # כדי למנוע פיצול בין `app.py` לבין Blueprint ייעודי. # def get_custom_theme(user_id) -> Optional[Dict[str, Any]]: """ טען את הערכה המותאמת הפעילה של המשתמש. תומך גם במבנה הישן (custom_theme) וגם בחדש (custom_themes[]). """ if not user_id: return None try: db_ref = get_db() user_doc = db_ref.users.find_one( {"user_id": user_id}, {"custom_theme": 1, "custom_themes": 1}, ) if not user_doc: return None # מבנה חדש (מערך) – עדיפות themes = user_doc.get("custom_themes") if isinstance(themes, list) and themes: for theme in themes: if isinstance(theme, dict) and theme.get("is_active"): if not isinstance(theme.get("variables"), dict): theme = {**theme, "variables": {}} if not isinstance(theme.get("syntax_css", ""), str): theme = {**theme, "syntax_css": ""} if not isinstance(theme.get("syntax_colors"), dict): theme = {**theme, "syntax_colors": {}} return theme # Fallback למבנה ישן (אובייקט בודד) old_theme = user_doc.get("custom_theme") if isinstance(old_theme, dict) and old_theme.get("is_active"): if not isinstance(old_theme.get("variables"), dict): old_theme = {**old_theme, "variables": {}} if not isinstance(old_theme.get("syntax_css", ""), str): old_theme = {**old_theme, "syntax_css": ""} if not isinstance(old_theme.get("syntax_colors"), dict): old_theme = {**old_theme, "syntax_colors": {}} return old_theme return None except Exception as e: logger.warning("get_custom_theme failed: %s", e) return None def get_current_theme() -> str: """קובע את ערכת הנושא הנוכחית לפי cookie ו/או העדפות משתמש (DB). נופל חזרה ל-classic אם הערך לא חוקי. """ t = get_default_ui_theme_raw() try: uid = session.get('user_id') theme_raw, _, _, _ = _resolve_theme_raw_token(uid) if theme_raw: t = theme_raw except Exception: pass _, _, theme_attr = _parse_theme_token(t) # Shared themes (shared:) אינם חלק מ-ALLOWED_UI_THEMES, אבל הם ערכים תקינים ל-UI. try: if str(theme_attr).lower().startswith("shared:"): return theme_attr except Exception: pass if theme_attr not in ALLOWED_UI_THEMES: # אם ברירת המחדל היא builtin – נחזור אליה; אם היא shared – נאפשר גם אותה; אחרת fallback ל-classic _, _, default_attr = get_default_ui_theme_parts() try: if default_attr in ALLOWED_UI_THEMES or str(default_attr).lower().startswith("shared:"): return default_attr except Exception: pass return "classic" return theme_attr @lru_cache(maxsize=32) def _style_exists(style: str) -> bool: """בודק אם style של Pygments זמין בהתקנה הנוכחית.""" if not style: return False try: get_style_by_name(style) return True except ClassNotFound: return False @lru_cache(maxsize=32) def get_pygments_style(theme_name: str) -> str: """מיפוי ערכת נושא ל־Pygments style עם נפילה חכמה ל-default. הערה: במצב כהה נעדיף ערכות כהות זמינות כדי למנוע טקסט כהה על רקע כהה במקרה שבו ערכות כמו github-dark אינן מותקנות בסביבת הריצה. """ theme = (theme_name or '').strip().lower() preferred = 'github' # custom themes נחשבים כהים כברירת מחדל (רוב הערכות המיובאות הן כהות) if theme in ('dark', 'dim', 'nebula', 'custom'): preferred = 'github-dark' elif theme == 'high-contrast': preferred = 'monokai' for candidate in (preferred, 'monokai', 'friendly', 'default'): if candidate == 'default' or _style_exists(candidate): return candidate return 'default' def _connect_cooldown_seconds() -> float: """כמה זמן לא מנסים להתחבר שוב אחרי כשל. נקרא בכל פעם, כדי שאפשר יהיה לכוון בזמן ריצה בלי לטעון מחדש את המודול.""" try: raw = str(os.getenv("MONGODB_CONNECT_RETRY_COOLDOWN_SECONDS", "30")).strip() return max(0.0, float(raw)) if raw else 30.0 except Exception: return 30.0 def _connect_is_cooling_down() -> bool: at = globals().get("_DB_LAST_CONNECT_FAILURE_AT") if at is None: return False cooldown = _connect_cooldown_seconds() if cooldown <= 0: return False # שעון מונוטוני: שינוי שעון מערכת לא יאריך או יקצר את החלון. return (_time.monotonic() - float(at)) < cooldown def _note_connect_failure() -> None: globals()["_DB_LAST_CONNECT_FAILURE_AT"] = _time.monotonic() def _note_connect_success() -> None: globals()["_DB_LAST_CONNECT_FAILURE_AT"] = None def get_db(): """מחזיר חיבור למסד הנתונים. **סדר הפרסום של הגלובלים הוא חלק מהחוזה, לא סגנון.** ``client`` הוא השומר של המסלול המהיר (``if client is None``) — מי שרואה אותו מאותחל מדלג על הנעילה ומחזיר את ``db`` כמו שהוא. לכן החיבור נבנה במשתנים מקומיים, ושני הגלובלים נכתבים רק כשהוא מוכן, כשהשומר אחרון. בלי זה נפתחו שני חורים, ושניהם החזירו ``None`` במקום מסד: 1. **מרוץ.** ``server_info()`` הוא סיבוב רשת שלם. קורא מקביל שנכנס באמצעו ראה ``client`` כבר מוצב ואת ``db`` עדיין ``None``. 2. **הרעלה קבועה.** אם ``server_info()`` נכשל, הגלובל ``client`` נשאר מוצב על לקוח שבור. ה-``except`` זרק הלאה, אבל כל קריאה עתידית כבר דילגה על האתחול והחזירה ``None`` — כלומר תקלת רשת חולפת אחת שיתקה את התהליך עד ריסטארט. **חלון הצינון, ולמה הוא לא קישוט.** ההרעלה שמעל הייתה גם מפסק: אחרי הכשל הראשון כל קריאה חזרה מיד, בלי לנסות להתחבר. הבעיה בה מעולם לא הייתה המהירות אלא ש**היא לנצח**. הסרתה לבדה גררה את הקצה השני — כל קריאה מנסה מחדש ומשלמת ``serverSelectionTimeoutMS`` שלם. נמדד מול כתובת שאינה נפתרת, 20 קריאות: **5 שניות** בקוד הישן מול **111** בלעדיו. בסוויטה זה חצה את ``timeout = 60`` שב-``pytest.ini``, ו-``timeout_method = thread`` הרג עובד xdist שלם. לכן הכשל נרשם עם **זמן**, ובתוך ``MONGODB_CONNECT_RETRY_COOLDOWN_SECONDS`` (ברירת מחדל 30) הקריאה חוזרת מיד עם ``None`` — בדיוק כמו הקוד הישן. אחרי שהחלון עובר, ההתחברות מנוסה שוב באמת. מפסק עם זמן פתיחה **סופי**. ⚠️ ערך ההחזרה ``None`` הוא חוזה קיים, לא חדש: מתוך 211 אתרי הקריאה בקוד הייצור, 96 אינם עטופים ב-``try``. שינויו ל"זורק תמיד" הוא ריפקטור נפרד, ואינו חלק מהתיקון הזה. """ global client, db # Proper double-checked locking: perform initialization under the lock if client is None: if _connect_is_cooling_down(): # כשל טרי: חוזרים מיד, בלי לשלם עוד timeout של בחירת שרת. return None _db_lock = globals().setdefault("_DB_INIT_LOCK", threading.Lock()) with _db_lock: if client is None: if _connect_is_cooling_down(): # נכשל בזמן שחיכינו לנעילה — לא מנסים שוב מיד. return None if not MONGODB_URL: raise Exception("MONGODB_URL is not configured") _new_client = None try: # חשוב: ב-ENV יש MONGODB_SERVER_SELECTION_TIMEOUT_MS, אבל בעבר לא חיווטנו אותו לכאן # ולכן בפועל נשאר timeout קשיח של 5 שניות. try: _raw_ms = str(os.getenv("MONGODB_SERVER_SELECTION_TIMEOUT_MS", "5000")).strip() _server_selection_timeout_ms = int(_raw_ms) if _raw_ms else 5000 except Exception: _server_selection_timeout_ms = 5000 # החזר אובייקטי זמן tz-aware כדי למנוע השוואות naive/aware _t0 = _time.perf_counter() _new_client = MongoClient( MONGODB_URL, serverSelectionTimeoutMS=_server_selection_timeout_ms, tz_aware=True, tzinfo=timezone.utc, ) # בדיקת חיבור _new_client.server_info() duration = max(0.0, float(_time.perf_counter() - _t0)) _new_db = _new_client[DATABASE_NAME] # פרסום: קודם הערך, ורק אחריו השומר שמגן עליו db = _new_db client = _new_client _new_client = None _note_connect_success() try: record_dependency_init("mongodb", duration) except Exception: pass try: _record_startup_metric('mongo', duration) except Exception: pass except Exception: # הלקוח לא פורסם, ולכן איש לא יחזיק בו — סוגרים אותו כאן # כדי שכשל חוזר לא ידלוף חיבורים ו-monitor threads. if _new_client is not None: try: _new_client.close() except Exception: pass _note_connect_failure() logger.exception("Failed to connect to MongoDB") raise # מחוץ לנעילה: הבטח אינדקסים פעם אחת, ללא קריאה חוזרת ל-get_db try: ensure_recent_opens_indexes() except Exception: pass try: ensure_code_snippets_indexes() except Exception: pass # אינדקסים לבאנרי הכרזות (Announcements) try: ensure_announcements_indexes() except Exception: pass # אינדקסים למשתמשים (Themes) try: ensure_users_indexes() except Exception: pass # אינדקסים לערכות ציבוריות (Shared Themes) try: ensure_shared_themes_indexes() except Exception: pass return db # --- Graceful MongoClient shutdown on process exit --- def _close_mongo_client_on_exit() -> None: try: global client if client is not None: try: client.close() except Exception: pass finally: client = None except Exception: pass atexit.register(_close_mongo_client_on_exit) # --- Ensure indexes for recent_opens once per process --- _recent_opens_indexes_ready = False def ensure_recent_opens_indexes() -> None: """יוצר אינדקסים נחוצים לאוסף recent_opens פעם אחת בתהליך.""" global _recent_opens_indexes_ready if _recent_opens_indexes_ready: return _start = _time.perf_counter() _did_work = False try: # השתמש ב-db גלובלי אם כבר מאותחל; אל תקרא get_db() כדי להימנע מ-deadlock בזמן אתחול _db = db if db is not None else None if _db is None: return _did_work = True coll = _db.recent_opens try: from pymongo import ASCENDING, DESCENDING coll.create_index([('user_id', ASCENDING), ('file_name', ASCENDING)], name='user_file_unique', unique=True) coll.create_index([('user_id', ASCENDING), ('last_opened_at', DESCENDING)], name='user_last_opened_idx') except Exception: # גם אם יצירת אינדקס נכשלה, לא נכשיל את היישום pass _recent_opens_indexes_ready = True except Exception: # אין להפיל את השרת במקרה של בעיית DB בתחילת חיים pass finally: if _did_work: try: _record_startup_metric('indexes_recent', max(0.0, float(_time.perf_counter() - _start)), accumulate=True) except Exception: pass # --- Ensure indexes for announcements once per process --- _announcements_indexes_ready = False def ensure_announcements_indexes() -> None: """יוצר אינדקסים לאוסף announcements פעם אחת בתהליך. אינדקסים: - (is_active, updated_at) - created_at desc """ global _announcements_indexes_ready if _announcements_indexes_ready: return _start = _time.perf_counter() _did_work = False try: _db = db if db is not None else None if _db is None: return _did_work = True coll = _db.announcements try: from pymongo import ASCENDING, DESCENDING coll.create_index([('is_active', ASCENDING), ('updated_at', DESCENDING)], name='active_updated_idx', background=True) coll.create_index([('created_at', DESCENDING)], name='created_desc_idx', background=True) except Exception: pass _announcements_indexes_ready = True except Exception: pass finally: if _did_work: try: _record_startup_metric('indexes_announcements', max(0.0, float(_time.perf_counter() - _start)), accumulate=True) except Exception: pass # --- Ensure indexes for users (themes) once per process --- _users_indexes_ready = False def ensure_users_indexes() -> None: """יוצר אינדקסים לאוסף users עבור Themes פעם אחת בתהליך. אינדקסים: - (user_id, custom_themes.is_active) - (user_id, custom_themes.id) """ global _users_indexes_ready if _users_indexes_ready: return _start = _time.perf_counter() _did_work = False try: _db = db if db is not None else None if _db is None: return _did_work = True coll = _db.users try: from pymongo import ASCENDING coll.create_index( [('user_id', ASCENDING), ('custom_themes.is_active', ASCENDING)], name='user_custom_themes_active', background=True, ) coll.create_index( [('user_id', ASCENDING), ('custom_themes.id', ASCENDING)], name='user_custom_themes_id', background=True, ) except Exception: pass _users_indexes_ready = True except Exception: pass finally: if _did_work: try: _record_startup_metric('indexes_users', max(0.0, float(_time.perf_counter() - _start)), accumulate=True) except Exception: pass # --- Ensure indexes for shared_themes once per process --- _shared_themes_indexes_ready = False def ensure_shared_themes_indexes() -> None: """יוצר אינדקסים לאוסף shared_themes פעם אחת בתהליך. אינדקסים: - (is_active) - (created_at DESC) - (created_by) """ global _shared_themes_indexes_ready if _shared_themes_indexes_ready: return _start = _time.perf_counter() _did_work = False try: _db = db if db is not None else None if _db is None: return _did_work = True coll = _db.shared_themes try: from pymongo import ASCENDING, DESCENDING coll.create_index( [("is_active", ASCENDING)], name="shared_themes_is_active_idx", background=True, ) coll.create_index( [("created_at", DESCENDING)], name="shared_themes_created_at_desc_idx", background=True, ) coll.create_index( [("created_by", ASCENDING)], name="shared_themes_created_by_idx", background=True, ) except Exception: pass _shared_themes_indexes_ready = True except Exception: pass finally: if _did_work: try: _record_startup_metric( "indexes_shared_themes", max(0.0, float(_time.perf_counter() - _start)), accumulate=True, ) except Exception: pass # --- HTTP caching helpers (ETag / Last-Modified) --- def _safe_dt_from_doc(value) -> datetime: """Normalize a datetime-like value from Mongo into tz-aware datetime (UTC).""" try: if isinstance(value, datetime): dt = value elif value is not None: # ISO string or other repr dt = datetime.fromisoformat(str(value)) else: dt = datetime.now(timezone.utc) except Exception: dt = datetime.now(timezone.utc) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) return dt def _file_last_modified(doc: Dict[str, Any]) -> datetime: """מתי הייצוג שהעמוד מגיש השתנה לאחרונה. ``updated_at`` לבדו אינו מספיק: הוא מציין מתי **התוכן** נערך, ואילו העמוד מרנדר גם את מצב המועדף והנעיצה. פעולות המטא-דאטה האלה אינן נוגעות ב-``updated_at`` (ראו ``docs/database/detailed-schema.rst``), ולכן בלי השדות שלהן דפדפן ששולח רק ``If-Modified-Since`` היה מקבל 304 עם מצב ישן. ``If-None-Match`` גובר לפי RFC 7232 §3.3 ולכן המסלול הזה נדיר — אבל הוא קיים, ו-``curl -z`` מגיע דרכו. """ candidates = [doc.get('updated_at'), doc.get('favorited_at'), doc.get('pinned_at')] stamps = [_safe_dt_from_doc(v) for v in candidates if v is not None] if not stamps: return _safe_dt_from_doc(doc.get('created_at')) return max(stamps) #: הפרויקציה שהילפרי ה-ETag צריכים. מוגדרת פעם אחת כדי שקורא שרוצה #: לשלוף את המסמך **בעצמו** ולחסוך שאילתה יוכל לבקש בדיוק את מה שהם #: קוראים — בלי לנחש ובלי שהרשימות ייסחפו זו מזו. ETAG_USER_PROJECTION = { 'ui_prefs.theme': 1, 'ui_prefs.note_fonts': 1, 'ui_prefs.note_font_size': 1, # ערכת המסמך של ``/md/`` (``_resolve_md_doc_theme``): הבחירה, וממנה הערכה עצמה ב-``custom_themes``. f'ui_prefs.{MD_DOC_THEME_PREF}': 1, 'custom_themes': 1, 'custom_theme': 1, } def _etag_needs_user_doc() -> bool: """האם מישהו מהוולידטורים באמת יזדקק למסמך המשתמש בבקשה הזו. שני ההילפרים נופלים ל-DB רק כשה-cookie אינו מכריע: ערכה במצב ``device`` עם ערך תקף, וגופן במצב ``device`` עם ערך שנפרס בהצלחה. כששניהם מוכרעים מה-cookie — אין למסד מה לתרום, והשליפה המשותפת היא עלות מיותרת על המסלול החם ביותר. """ theme_decided = bool(_device_scoped_theme_cookie()) fonts_decided = ( _normalize_theme_scope(request.cookies.get('ui_note_fonts_scope')) == THEME_SCOPE_DEVICE and _decode_note_fonts(request.cookies.get('ui_note_fonts')) is not None ) # **גם הגודל.** הוא נכנס ל-``_note_fonts_etag_key``, ולכן הכרעה # שמדלגת על המסד בזמן שהוא עדיין תלוי בו הייתה מחשבת מפתח לפי ברירת # המחדל — כלומר ETag שלא זז אחרי שינוי ההגדרה, שזה הכשל שהמפתח נועד # למנוע מלכתחילה. size_decided = ( _normalize_theme_scope(request.cookies.get('ui_note_font_size_scope')) == THEME_SCOPE_DEVICE and _decode_note_font_size(request.cookies.get('ui_note_font_size')) is not None ) return not (theme_decided and fonts_decided and size_decided) def _get_theme_etag_key( user_id: Optional[int], *, user_doc: Optional[Dict[str, Any]] = None, ) -> str: """מפתח קצר שמייצג את ערכת הנושא הנוכחית (כולל שינויי גרסה). ``user_doc`` חוסך שליפה כשהקורא כבר החזיק את המסמך. חייב להיות מסמך שנשלף עם ``ETAG_USER_PROJECTION`` (או רחב ממנה). """ theme_raw = get_default_ui_theme_raw() try: theme_raw, _, _, user_doc = _resolve_theme_raw_token( user_id, user_doc=user_doc, projection={'ui_prefs.theme': 1, 'custom_themes': 1, 'custom_theme': 1}, ) except Exception: theme_raw = get_default_ui_theme_raw() user_doc = None theme_type, theme_id, theme_attr = _parse_theme_token(theme_raw) base = theme_attr if theme_attr in ALLOWED_UI_THEMES else 'classic' if theme_type == 'shared' and theme_id: base = f"shared:{theme_id}" elif theme_type == 'custom' and theme_id: base = f"custom:{theme_id}" elif theme_type == 'custom': base = 'custom' version_parts = [] if theme_type == 'custom': updated_at = None theme_ident = '' if user_id and user_doc is None: try: db_ref = get_db() user_doc = db_ref.users.find_one( {'user_id': int(user_id)}, {'custom_themes': 1, 'custom_theme': 1}, ) or {} except Exception: user_doc = None found_custom = False if isinstance(user_doc, dict): themes = user_doc.get('custom_themes') if theme_id and isinstance(themes, list): for tdoc in themes: if isinstance(tdoc, dict) and str(tdoc.get('id') or '').strip() == theme_id: updated_at = tdoc.get('updated_at') found_custom = True break if updated_at is None and isinstance(themes, list): for tdoc in themes: if isinstance(tdoc, dict) and tdoc.get('is_active'): updated_at = tdoc.get('updated_at') if not theme_id: theme_ident = str(tdoc.get('id') or '').strip() found_custom = True break if updated_at is None: ct = user_doc.get('custom_theme') if isinstance(ct, dict) and (ct.get('is_active') or theme_id): updated_at = ct.get('updated_at') if not theme_id: theme_ident = str(ct.get('id') or '').strip() found_custom = True if not found_custom: base = 'classic' if theme_ident: version_parts.append(theme_ident) if updated_at: try: updated_str = _safe_dt_from_doc(updated_at).isoformat() except Exception: updated_str = str(updated_at) if updated_str: version_parts.append(updated_str) elif theme_type == 'shared' and theme_id: try: db_ref = get_db() doc = db_ref.shared_themes.find_one( {'_id': theme_id, 'is_active': True}, {'updated_at': 1}, ) or {} if not doc: base = 'classic' else: updated_at = doc.get('updated_at') if updated_at: updated_str = _safe_dt_from_doc(updated_at).isoformat() if updated_str: version_parts.append(updated_str) except Exception: base = 'classic' if version_parts: return f"{base}|{'|'.join(version_parts)}" return base def _etag_tags(tags: Any) -> List[str]: """התגיות כפי שהן נכנסות לוולידטור — רשימת מחרוזות שאפשר לסדר ב-JSON. הרשימה כמו שהיא, כולל הסדר: העמוד מציג אותן בסדר הזה. ערך שאינו רשימה (מסמך ישן, ``None``) נכנס כרשימה ריקה, ופריט שאינו מחרוזת — כמחרוזת, כדי ש-``json.dumps`` לא ייפול ויגרור את ה-ETag ל-fallback מבוסס-זמן. """ if not isinstance(tags, list): return [] return [t if isinstance(t, str) else str(t) for t in tags] def _compute_file_etag(doc: Dict[str, Any], *, variant: str = '') -> str: """Compute a weak ETag for a file document based on updated_at and raw content. We intentionally include only fields that impact the rendered output to keep the validator stable but sensitive to relevant changes. """ try: updated_at = doc.get('updated_at') if isinstance(updated_at, datetime): updated_str = updated_at.isoformat() elif updated_at is not None: updated_str = str(updated_at) else: updated_str = '' except Exception: updated_str = '' raw_code = (doc.get('code') or doc.get('content') or '') file_name = (doc.get('file_name') or '') version = str(doc.get('version') or '') # Hash a compact JSON string of identifying fields + content digest try: payload_data = { 'u': updated_str, 'n': file_name, 'v': version, 'sha': hashlib.sha256(raw_code.encode('utf-8')).hexdigest(), # מצב מועדף/נעוץ מרונדר לתוך ה-HTML (תוויות הכפתורים, # ``aria-pressed``, ``data-is-pinned``), ולכן הוא חלק מהפלט ולא # רק מטא-דאטה. עד כה הוא נעדר מכאן, ונכונות הקאש ניצלה רק בגלל # ש-toggle_favorite/toggle_pin הזיזו את ``updated_at`` — תופעת # לוואי של חותמת שמשמעותה "התוכן נערך". משנרשם כאן, הוולידטור # נשען על מה שהעמוד באמת מציג. 'f': '1' if doc.get('is_favorite') else '0', 'p': '1' if doc.get('is_pinned') else '0', # התגיות מרונדרות לתוך העמוד, ושינוי שלהן **בכוונה** אינו מזיז את # ``updated_at`` — לא ב-``quick-update`` ולא בתיוג מרובה (תגיות הן # מטא-דאטה, כמו מועדף ונעיצה). בלי השדה הזה ``If-None-Match`` קיבל # 304 אחרי שינוי תגיות, והדפדפן הציג את התגיות הישנות — ומודאל # התגיות נפתח איתן, כך ששמירה דרסה את החדשות. 't': _etag_tags(doc.get('tags')), # גרסת ה-deploy: בלעדיה קובץ שלא נערך מחזיר ETag זהה בין deploys, # והדפדפן מקבל 304 ומציג תבנית ישנה (בלי אלמנטים חדשים). 'sv': _STATIC_VERSION, } if variant: payload_data['var'] = variant payload = json.dumps(payload_data, sort_keys=True, ensure_ascii=False, separators=(',', ':')) tag = hashlib.sha256(payload.encode('utf-8')).hexdigest()[:16] return f'W/"{tag}"' except Exception: # Fallback: time-based weak tag return f'W/"{int(time.time())}"' def _get_user_any_file_by_id(db_ref, user_id: int, file_id: str) -> Tuple[Optional[Dict[str, Any]], str]: """שליפת קובץ לפי ObjectId ממסמך רגיל או large_files, עם וידוא בעלות משתמש. מחזיר (doc, kind) כאשר kind הוא "regular" או "large" או "" אם לא נמצא. """ if not file_id: return None, "" try: obj_id = ObjectId(file_id) except (InvalidId, TypeError): return None, "" try: doc = db_ref.code_snippets.find_one({'_id': obj_id, 'user_id': user_id}) if isinstance(doc, dict): return doc, "regular" except Exception: pass try: large_coll = getattr(db_ref, 'large_files', None) if large_coll is None: return None, "" doc = large_coll.find_one({ '_id': obj_id, 'user_id': user_id, 'is_active': {'$ne': False}, }) if isinstance(doc, dict): return doc, "large" except Exception: pass return None, "" _SOURCE_URL_SCHEMES = {'http', 'https'} def _normalize_source_url_value(raw: str) -> Tuple[Optional[str], Optional[str]]: """מאמת ומנרמל קישור מקור של משתמש (http/https בלבד).""" value = (raw or '').strip() if not value: return None, None candidate = value if candidate.startswith('//'): candidate = f'https:{candidate}' elif '://' not in candidate: candidate = f'https://{candidate}' if any(ch.isspace() for ch in candidate): return None, 'קישור למקור לא יכול להכיל רווחים' try: parsed = urlparse(candidate) except Exception: return None, 'קישור למקור אינו תקין' scheme = (parsed.scheme or '').lower() if scheme not in _SOURCE_URL_SCHEMES: return None, 'ניתן להזין רק קישורי http או https' netloc = (parsed.netloc or '').strip() if not netloc or ' ' in netloc: return None, 'שם המארח בקישור אינו תקין' cleaned = urlunparse(( scheme, netloc, parsed.path or '', parsed.params or '', parsed.query or '', parsed.fragment or '', )) return cleaned, None def _extract_source_hostname(url: str) -> str: """מחזיר שם מארח לתצוגה בלחצן הקישור.""" if not url: return '' try: parsed = urlparse(url) except Exception: return '' host = (parsed.netloc or '').strip() if not host: return '' host = host.split('@')[-1] if ':' in host: host = host.split(':', 1)[0] return host # --- Ensure indexes for code_snippets once per process --- _code_snippets_indexes_ready = False def ensure_code_snippets_indexes() -> None: """יוצר אינדקסים קריטיים עבור אוסף code_snippets פעם אחת בתהליך. אינדקסים: - (user_id, created_at) - (user_id, programming_language) - (user_id, tags) - (user_id, is_favorite) - Text index על (file_name, description, tags) – אם אין כבר. """ global _code_snippets_indexes_ready if _code_snippets_indexes_ready: return _start = _time.perf_counter() _did_work = False try: # השתמש ב-db גלובלי אם כבר מאותחל; אל תקרא get_db() כדי להימנע מ-deadlock בזמן אתחול _db = db if db is not None else None if _db is None: return _did_work = True coll = _db.code_snippets try: from pymongo import ASCENDING, DESCENDING # זוגות פשוטים try: coll.create_index([('user_id', ASCENDING), ('created_at', DESCENDING)], name='user_created_at', background=True) except Exception: pass try: coll.create_index([('user_id', ASCENDING), ('programming_language', ASCENDING)], name='user_lang', background=True) except Exception: pass try: coll.create_index([('user_id', ASCENDING), ('tags', ASCENDING)], name='user_tags', background=True) except Exception: pass try: coll.create_index([('user_id', ASCENDING), ('is_favorite', ASCENDING)], name='user_favorite', background=True) except Exception: pass # אינדקסים לשדות מטא חדשים (מסייעים לפילטרים/מיונים עתידיים כמו min_size/max_size) try: coll.create_index([('user_id', ASCENDING), ('file_size', ASCENDING)], name='user_file_size', background=True) except Exception: pass try: coll.create_index([('user_id', ASCENDING), ('lines_count', ASCENDING)], name='user_lines_count', background=True) except Exception: pass # אינדקסים לתמיכה ב-"גרסה אחרונה לכל file_name" (פייפליינים עם sort+group) try: coll.create_index( [('user_id', ASCENDING), ('file_name', ASCENDING), ('version', DESCENDING)], name='user_file_version_desc', background=True, ) except Exception: pass # אינדקסים למיונים נפוצים במסכי רשימות try: coll.create_index([('user_id', ASCENDING), ('updated_at', DESCENDING)], name='user_updated_at', background=True) except Exception: pass try: coll.create_index( [('user_id', ASCENDING), ('is_favorite', ASCENDING), ('favorited_at', DESCENDING)], name='user_favorite_favorited_at', background=True, ) except Exception: pass try: # Pinned files (Dashboard): ensure correct index by name. # If an older deployment created this index name with a different key order, # drop+recreate best-effort to avoid silently keeping a suboptimal index. desired_name = 'user_pinned_pin_order_idx' desired_keys = [ ('user_id', ASCENDING), ('is_active', ASCENDING), ('is_pinned', ASCENDING), ('pin_order', ASCENDING), ('pinned_at', DESCENDING), ] try: info = coll.index_information() or {} meta = info.get(desired_name) if isinstance(info, dict) else None existing_key = meta.get('key') if isinstance(meta, dict) else None if existing_key and existing_key != desired_keys: try: coll.drop_index(desired_name) except Exception: pass except Exception: pass coll.create_index(desired_keys, name=desired_name, background=True) except Exception: pass # Text index – רק אם לא קיים כבר אינדקס מסוג text try: has_text = False try: for ix in coll.list_indexes(): for k, spec in ix.to_dict().get('key', {}).items(): if str(spec).lower() == 'text': has_text = True break if has_text: break except Exception: # Fallback ל-index_information() try: for _name, info in (coll.index_information() or {}).items(): key = info.get('key') or [] for pair in key: if isinstance(pair, (list, tuple)) and len(pair) >= 2 and str(pair[1]).lower() == 'text': has_text = True break if has_text: break except Exception: has_text = False if not has_text: coll.create_index([ ('file_name', 'text'), ('description', 'text'), ('tags', 'text'), ], name='text_file_desc_tags', background=True) except Exception: pass except Exception: # אם pymongo לא נטען/סביבת Docs – לא נכשיל pass _code_snippets_indexes_ready = True except Exception: # אין להפיל את האפליקציה במקרה של בעיית DB בתחילת חיים pass finally: if _did_work: try: _record_startup_metric('indexes_code', max(0.0, float(_time.perf_counter() - _start)), accumulate=True) except Exception: pass # (הוסר שימוש ב-before_first_request; ראה הקריאה בתוך get_db למניעת שגיאה בפלאסק 3) # --- Cursor encoding helpers for pagination --- def _encode_cursor(created_at: datetime, oid: ObjectId) -> str: try: dt = created_at if isinstance(created_at, datetime) else _safe_dt_from_doc(created_at) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) ts = int(dt.timestamp()) except Exception: ts = int(time.time()) try: raw = json.dumps({'t': ts, 'id': str(oid)}, separators=(',', ':'), sort_keys=True).encode('utf-8') return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii') except Exception: return '' def _decode_cursor(cursor: str) -> tuple[datetime | None, ObjectId | None]: if not cursor: return (None, None) try: padding = '=' * (-len(cursor) % 4) data = base64.urlsafe_b64decode((cursor + padding).encode('ascii')) obj = json.loads(data.decode('utf-8')) ts = int(obj.get('t')) oid_str = str(obj.get('id') or '') last_dt = datetime.fromtimestamp(ts, tz=timezone.utc) last_oid = ObjectId(oid_str) if oid_str else None return (last_dt, last_oid) except Exception: return (None, None) # --- Simple in-process cache for external uptime calls --- _uptime_cache_lock = threading.Lock() _uptime_cache: Dict[str, Any] = { 'data': None, 'provider': None, 'fetched_at': 0.0, } def _get_uptime_cached() -> Optional[Dict[str, Any]]: now_ts = time.time() with _uptime_cache_lock: data = _uptime_cache.get('data') ts = float(_uptime_cache.get('fetched_at') or 0) if data and (now_ts - ts) < UPTIME_CACHE_TTL_SECONDS: return data return None def _set_uptime_cache(payload: Dict[str, Any]) -> None: with _uptime_cache_lock: _uptime_cache['data'] = payload _uptime_cache['provider'] = UPTIME_PROVIDER _uptime_cache['fetched_at'] = time.time() def _fetch_uptime_from_betteruptime() -> Optional[Dict[str, Any]]: if not (UPTIME_API_KEY and UPTIME_MONITOR_ID): return None try: # SLA endpoint per issue suggestion url = f'https://uptime.betterstack.com/api/v2/monitors/{UPTIME_MONITOR_ID}/sla' headers = {'Authorization': f'Bearer {UPTIME_API_KEY}'} resp = http_request('GET', url, headers=headers, timeout=8) if resp.status_code != 200: return None body = resp.json() if resp.content else {} # Normalize output availability = None try: availability = float(((body or {}).get('data') or {}).get('availability') or 0) except Exception: availability = None result = { 'provider': 'betteruptime', 'uptime_percentage': round(availability, 2) if isinstance(availability, (int, float)) else None, 'raw': body, 'status_url': UPTIME_STATUS_URL or None, } return result except Exception: return None def _fetch_uptime_from_uptimerobot() -> Optional[Dict[str, Any]]: """Fetch uptime from UptimeRobot. Notes: - UptimeRobot v2 מחזיר שדה custom_uptime_ratios (לא ranges) כשמבקשים יחסי זמינות עבור X ימים אחרונים. ערך '1' משמע 24 שעות אחרונות. - נתמוך גם ב-custom_uptime_ranges אם יוחזר (תאימות עתידית/ישנה). """ if not UPTIME_API_KEY: return None try: url = 'https://api.uptimerobot.com/v2/getMonitors' payload = { 'api_key': UPTIME_API_KEY, # יחס זמינות ל-1 יום (24 שעות) 'custom_uptime_ratios': '1', 'format': 'json', } # אם זה לא מפתח monitor‑specific (שמתחיל ב-'m'), ונמסר מזהה monitor – נשלח אותו try: api_key_is_monitor_specific = str(UPTIME_API_KEY).strip().lower().startswith('m') except Exception: api_key_is_monitor_specific = False if UPTIME_MONITOR_ID and not api_key_is_monitor_specific: payload['monitors'] = UPTIME_MONITOR_ID # שמירה על זמן תגובה קצר בעמוד הבית – timeout אגרסיבי כדי לא לחסום את ה-WSGI resp = http_request('POST', url, data=payload, timeout=3) if resp.status_code != 200: return None body = resp.json() if resp.content else {} monitors = (body or {}).get('monitors') or [] uptime_percentage = None if (body or {}).get('stat') == 'fail': return None if monitors: # נסה את כל הוריאציות הידועות val = ( monitors[0].get('custom_uptime_ratio') or monitors[0].get('custom_uptime_ratios') or monitors[0].get('custom_uptime_range') or monitors[0].get('custom_uptime_ranges') ) try: if isinstance(val, str): # custom_uptime_ratios יכול להיות "99.99" או "99.99-..." – ניקח את הראשון first = val.split('-')[0].strip() uptime_percentage = round(float(first), 2) elif isinstance(val, (int, float)): uptime_percentage = round(float(val), 2) except Exception: uptime_percentage = None return { 'provider': 'uptimerobot', 'uptime_percentage': uptime_percentage, 'raw': body, 'status_url': UPTIME_STATUS_URL or None, } except Exception: return None def fetch_external_uptime() -> Optional[Dict[str, Any]]: """Fetch uptime according to configured provider with basic caching.""" # Return from cache if fresh cached = _get_uptime_cached() if cached is not None: return cached result: Optional[Dict[str, Any]] = None provider = (UPTIME_PROVIDER or '').strip().lower() if provider == 'betteruptime': result = _fetch_uptime_from_betteruptime() elif provider == 'uptimerobot': result = _fetch_uptime_from_uptimerobot() elif provider in {'statuscake', 'pingdom'}: # Not implemented: fall back to None to avoid errors result = None if result is not None: _set_uptime_cache(result) return result @lru_cache(maxsize=1) def _load_user_guide_markdown() -> Optional[Tuple[str, datetime]]: """טוען את קובץ המדריך המקומי ומחזיר את התוכן והזמן האחרון שבו עודכן.""" try: content = USER_GUIDE_PATH.read_text(encoding='utf-8') except FileNotFoundError: try: logger.warning("USER_GUIDE markdown file missing", extra={'path': str(USER_GUIDE_PATH)}) except Exception: pass return None except Exception: try: logger.exception("Failed reading USER_GUIDE markdown", extra={'path': str(USER_GUIDE_PATH)}) except Exception: pass return None try: updated_at = datetime.fromtimestamp(USER_GUIDE_PATH.stat().st_mtime, timezone.utc) except Exception: updated_at = datetime.now(timezone.utc) return content, updated_at def _get_builtin_share_doc(share_id: str) -> Optional[Dict[str, Any]]: """בניית מסמך שיתוף מובנה מהמדריך המקומי (למזהי welcome).""" if not share_id or share_id not in WELCOME_GUIDE_SHARE_ALIASES: return None loaded = _load_user_guide_markdown() if not loaded: return None code, updated_at = loaded return { 'share_id': share_id, 'file_name': WELCOME_GUIDE_FILE_NAME, 'code': code, 'language': 'markdown', 'description': WELCOME_GUIDE_DESCRIPTION, 'created_at': updated_at, 'updated_at': updated_at, 'views': 0, 'is_builtin': True, } def get_internal_share(share_id: str) -> Optional[Dict[str, Any]]: """שליפת שיתוף פנימי מה-DB (internal_shares) עם בדיקת תוקף — המסמך המלא, כולל ``code``. **שיתוף הוא תצוגה של קובץ בודד, ולכן התוכן המלא נמשך תמיד.** זה המקרה שכלל ה-Smart Projection ב-CLAUDE.md מחריג במפורש ("משיכת תוכן מלא ... עבור צפייה או עריכה של קובץ בודד"). מ-#2235 ועד התיקון הזה העמוד הציבורי קרא את המסמך בלי ``code`` והציג רק את תחילת הקובץ, ושיתוף שנוצר בבוט — שנשמר בלי תצוגה מקדימה — הוצג ריק. """ builtin_doc = _get_builtin_share_doc(share_id) if builtin_doc: return builtin_doc try: db = get_db() coll = db.internal_shares doc = coll.find_one({"share_id": share_id}) if not doc: return None # TTL אמור לטפל במחיקה, אבל אם עדיין לא נמחק — נבדוק תוקף ידנית באופן חסין tz exp = doc.get("expires_at") if isinstance(exp, datetime): exp_aware = exp if exp.tzinfo is not None else exp.replace(tzinfo=timezone.utc) now_utc = datetime.now(timezone.utc) if exp_aware < now_utc: return None elif isinstance(exp, str): try: exp_dt = datetime.fromisoformat(exp) exp_aware = exp_dt if exp_dt.tzinfo is not None else exp_dt.replace(tzinfo=timezone.utc) if exp_aware < datetime.now(timezone.utc): return None except Exception: pass try: coll.update_one({"_id": doc["_id"]}, {"$inc": {"views": 1}}) except Exception: pass return doc except Exception as e: logger.exception("Error fetching internal share") return None def _shared_code_or_none(doc: Dict[str, Any]) -> Optional[str]: """התוכן שעמוד שיתוף ציבורי מציג, או ``None`` כשאין בשיתוף תוכן להציג. ``None`` מוביל ל-404 אצל הקוראים (``public_share``, ``public_reader_mode``), ולא לעמוד ריק: עמוד ריק עם 200 נראה בדיוק כמו קובץ ריק, וזה מה שהסתיר את שיתופי הבוט שהוצגו ריקים מ-#2235. המקרה הצפוי היחיד הוא שיתוף שנוצר לפני שהשיתוף התחיל לשמור את התוכן המלא, ולכן הוא נספר באירוע ``share_without_content`` — בלי ``share_id``, שהוא הטוקן שפותח את הקישור. קובץ ריק (``""``) הוא תוכן תקין ומוצג כמו שהוא. """ code = doc.get('code') if isinstance(code, str): return code emit_event( 'share_without_content', severity='warn', code_type=type(code).__name__, has_source_file=bool(doc.get('source_file_id')), ) return None # Telegram Login Widget Verification def verify_telegram_auth(auth_data: Dict[str, Any]) -> bool: """מאמת את הנתונים מ-Telegram Login Widget DEPRECATED: Use webapp.routes.auth_routes._verify_telegram_auth instead. That version has better error handling for missing BOT_TOKEN. This function will be removed when route migration is complete. """ check_hash = auth_data.get('hash') if not check_hash: return False # יצירת data-check-string data_items = [] for key, value in sorted(auth_data.items()): if key != 'hash': data_items.append(f"{key}={value}") data_check_string = '\n'.join(data_items) # חישוב hash secret_key = hashlib.sha256(BOT_TOKEN.encode()).digest() calculated_hash = hmac.new( secret_key, data_check_string.encode(), hashlib.sha256 ).hexdigest() # בדיקת תוקף if calculated_hash != check_hash: return False # בדיקת זמן (עד שעה מהחתימה) auth_date = int(auth_data.get('auth_date', 0)) if (time.time() - auth_date) > 3600: return False return True def login_required(f): """דקורטור לבדיקת התחברות""" try: is_async = asyncio.iscoroutinefunction(f) # type: ignore[attr-defined] except Exception: is_async = False if is_async: @wraps(f) async def decorated_function(*args, **kwargs): if 'user_id' not in session: try: wants_json = ( (request.path or '').startswith('/api/') or ('application/json' in (request.headers.get('Accept') or '')) ) except Exception: wants_json = False if wants_json: return jsonify({'error': 'נדרש להתחבר'}), 401 next_url = request.full_path if request.query_string else request.path return redirect(url_for('auth.login', next=next_url)) return await f(*args, **kwargs) return decorated_function @wraps(f) def decorated_function(*args, **kwargs): if 'user_id' not in session: # אם זו בקשת API או שהלקוח מצפה ל-JSON – נחזיר 401 JSON כדי שה-frontend יפנה ל-/login try: wants_json = ( (request.path or '').startswith('/api/') or ('application/json' in (request.headers.get('Accept') or '')) ) except Exception: wants_json = False if wants_json: return jsonify({'error': 'נדרש להתחבר'}), 401 # אחרת: הפניה רגילה לעמוד ההתחברות, עם next לחזרה next_url = request.full_path if request.query_string else request.path return redirect(url_for('auth.login', next=next_url)) return f(*args, **kwargs) return decorated_function def get_current_user_id() -> Optional[int]: """פונקציה תואמת-מדריך להחזרת מזהה משתמש נוכחי (או None אם לא מחובר).""" try: uid = session.get('user_id') if uid is None: return None return int(uid) except Exception: return None # --- Compare API - API להשוואת קבצים (לפי המדריך) --- compare_bp = Blueprint('compare', __name__, url_prefix='/api/compare') def _default_compare_pair(versions, fallback: int): """שתי הגרסאות שמוצגות כשלא ביקשו אחרות — כלל אחד לעמוד ול-API. **נגזר מהקבוצה ולא מחשבון.** ``current_version - 1`` מניח שהמספור רציף, והוא אינו: העברה לסל ואז שמירה מחדש משאירה את הגרסאות הישנות לא פעילות ויוצרת מספר חדש, ומחיקת גרסה בודדת מייצרת חור באמצע. עבור ``{2, 7, 9}`` החשבון נותן 8, שאינה קיימת — הדיף חוזר 400 והרשימה הנפתחת מסמנת משהו אחר. הפונקציה טהורה ומקבלת מספרים, כי לשני הקוראים יש מקור אחר: העמוד כבר מחזיק את כל הרשימה, וה-API שולף רק את שתי העליונות. מה שאסור שיהיה שונה הוא **הכלל**, לא הדרך להשיג את הנתונים. """ ordered = sorted({v for v in versions if v is not None}, reverse=True) if not ordered: return max(1, fallback - 1), fallback right = ordered[0] left = ordered[1] if len(ordered) > 1 else right return left, right def _compare_version_arg( name: str, default: int, available: Optional[set] = None, ) -> Tuple[Optional[int], Optional[str]]: """קריאת ``left``/``right`` מהכתובת — כלל אחד לעמוד ול-API. ``request.args.get(name, type=int, default=...)`` נראה כמו אימות ואינו כזה: ב-Flask המרה כושלת מחזירה את ברירת המחדל **בשקט**, כלומר ``?left=abc`` הציג דיף של גרסה אחרת בלי לומר דבר. מספר גרסה שהגיע מהכתובת הוא טקסט של מישהו, לא נתון. ``available`` נמסר רק כשקבוצת הגרסאות כבר בידי הקורא (העמוד שולף אותה ממילא). ה-API אינו שולף רשימה רק כדי לאמת — שם הקיום נבדק ממילא ב-``diff_service.compare_versions``, שמחזיר ``None`` כשאחד הצדדים חסר. מחזיר ``(value, error)``: בדיוק אחד מהם אינו ``None``. """ raw = request.args.get(name) if raw is None or raw == '': return default, None value = normalized_version(raw) if value is None: return None, f"פרמטר {name} אינו מספר גרסה תקין" if available is not None and value not in available: return None, f"גרסה {value} אינה קיימת לקובץ הזה" return value, None @compare_bp.route('/versions/', methods=['GET']) def compare_versions(file_id: str): """ השוואה בין גרסאות של קובץ. Query params: - left: מספר גרסה שמאלית (ברירת מחדל: גרסה אחרונה - 1) - right: מספר גרסה ימנית (ברירת מחדל: גרסה אחרונה) Returns: JSON עם תוצאת ההשוואה """ user_id = get_current_user_id() if not user_id: return jsonify({"error": "Unauthorized"}), 401 from database import db as _db db = _db # קבלת הקובץ לפי ID file_doc = db.get_file_by_id(file_id) if not file_doc: return jsonify({"error": "File not found"}), 404 if file_doc.get("user_id") != user_id: return jsonify({"error": "Forbidden"}), 403 file_name = file_doc.get("file_name") # "הגרסה הנוכחית" היא של **הקובץ**, לא של המסמך שב-URL: ``file_id`` # יכול להיות ה-``_id`` של גרסה ישנה, כי כל גרסה היא מסמך משלה. בלי # זה, בקשה בלי פרמטרים על מזהה של גרסה ישנה הייתה מחזירה דיף אחר # מזה שהעמוד מציג על אותו קובץ — אותה שאלה, שתי תשובות. # # **והשאילתה רצה רק כשצריך אותה.** ``current_version`` משמש אך ורק # כברירת מחדל לפרמטר חסר, והממשק שולח תמיד את שניהם; שליפה בכל # בקשה הייתה עבודה שאיש לא קורא את תוצאתה. current_version = normalized_version(file_doc.get("version")) or 1 default_left, default_right = max(1, current_version - 1), current_version if not request.args.get('left') or not request.args.get('right'): # **שתיים, לא אחת.** ברירת המחדל היא זוג, ו"הגרסה שלפני" אינה # ``האחרונה - 1`` כשהמספור אינו רציף. ההיטלה היא ``version`` # בלבד ו-``limit(2)`` — עדיין שאילתה אחת על אותו אינדקס. try: top = list( get_db().code_snippets.find( {"user_id": user_id, "file_name": file_name, "is_active": True}, {"version": 1}, sort=[("version", DESCENDING)], ).limit(2) ) except Exception: logger.warning("could not resolve the compare defaults", extra={"file_name": file_name}, exc_info=True) top = [] if top: default_left, default_right = _default_compare_pair( (normalized_version(d.get("version")) for d in top), current_version ) # קבלת פרמטרים version_left, err_left = _compare_version_arg('left', default_left) version_right, err_right = _compare_version_arg('right', default_right) error = err_left or err_right if error: return jsonify({"error": error}), 400 # חישוב ההשוואה diff_service = get_diff_service(db) result = diff_service.compare_versions(user_id, file_name, version_left, version_right) if not result: return jsonify({ "error": f"אחת מהגרסאות אינה קיימת לקובץ הזה ({version_left} או {version_right})" }), 400 return jsonify(result.to_dict()) @compare_bp.route('/files', methods=['POST']) def compare_files(): """ השוואה בין שני קבצים שונים. Body (JSON): - left_file_id: מזהה קובץ שמאלי - right_file_id: מזהה קובץ ימני Returns: JSON עם תוצאת ההשוואה """ user_id = get_current_user_id() if not user_id: return jsonify({"error": "Unauthorized"}), 401 data = request.get_json() or {} left_id = data.get('left_file_id') right_id = data.get('right_file_id') if not left_id or not right_id: return jsonify({"error": "Missing file IDs"}), 400 from database import db as _db db = _db diff_service = get_diff_service(db) result = diff_service.compare_files(user_id, left_id, right_id) if not result: return jsonify({"error": "Could not compare files"}), 400 return jsonify(result.to_dict()) @compare_bp.route('/diff', methods=['POST']) def compare_raw(): """ השוואה בין שני טקסטים גולמיים. Body (JSON): - left_content: תוכן שמאלי - right_content: תוכן ימני Returns: JSON עם תוצאת ההשוואה """ user_id = get_current_user_id() if not user_id: return jsonify({"error": "Unauthorized"}), 401 data = request.get_json() or {} left_content = data.get('left_content', '') right_content = data.get('right_content', '') diff_service = get_diff_service() result = diff_service.compute_diff(left_content, right_content) return jsonify(result.to_dict()) app.register_blueprint(compare_bp) # before_request: אם אין סשן אבל יש cookie "remember_me" תקף — נבצע התחברות שקופה @app.before_request def try_persistent_login(): try: if 'user_id' in session: return token = request.cookies.get(REMEMBER_COOKIE_NAME) if not token: return db = get_db() doc = db.remember_tokens.find_one({ 'token': token }) if not doc: return # בדיקת תוקף exp = doc.get('expires_at') now = datetime.now(timezone.utc) if isinstance(exp, datetime): if exp < now: return else: try: if datetime.fromisoformat(str(exp)) < now: return except Exception: return # שחזור סשן בסיסי user_id = int(doc.get('user_id')) user = db.users.find_one({'user_id': user_id}) or {} session['user_id'] = user_id session['user_data'] = { 'id': user_id, 'first_name': user.get('first_name', ''), 'last_name': user.get('last_name', ''), 'username': user.get('username', ''), 'photo_url': '', 'is_admin': is_admin(user_id), 'is_premium': is_premium(user_id), } session.permanent = True except Exception: # אל תכשיל בקשות בגלל כשל חיבור/פרסר pass # --- Queue delay (request queueing) instrumentation --- _QUEUE_DELAY_HEADERS = ("X-Queue-Start", "X-Request-Start") _QUEUE_DELAY_EPOCH_RE = re.compile(r"(-?\d+(?:\.\d+)?)") def _queue_delay_warn_threshold_ms() -> int: try: return max(0, int(float(os.getenv("QUEUE_DELAY_WARN_MS", "500") or 500))) except Exception: return 500 def _parse_request_start_to_epoch_seconds(raw: str | None) -> float | None: """Parse ingress timestamp headers into epoch seconds (best-effort).""" try: text = str(raw or "").strip() except Exception: return None if not text: return None if text.lower().startswith("t="): text = text.split("=", 1)[1].strip() m = _QUEUE_DELAY_EPOCH_RE.search(text) if not m: return None token = m.group(1) if not token: return None if "." in token: try: value = float(token) except Exception: return None return value if value > 0 else None try: value_int = int(token) except Exception: return None if value_int <= 0: return None digits = len(token.lstrip("+-")) if digits <= 10: return float(value_int) if digits <= 13: return float(value_int) / 1_000.0 if digits <= 16: return float(value_int) / 1_000_000.0 return float(value_int) / 1_000_000_000.0 def _compute_queue_delay_ms(headers, *, now_epoch_seconds: float) -> tuple[int, str | None]: for header_name in _QUEUE_DELAY_HEADERS: try: raw = headers.get(header_name) except Exception: raw = None if not raw: continue ts = _parse_request_start_to_epoch_seconds(raw) if ts is None: continue try: delay_ms = int(round(max(0.0, float(now_epoch_seconds - float(ts)) * 1000.0))) except Exception: delay_ms = 0 return delay_ms, header_name return 0, None def _bind_queue_delay_context(queue_delay_ms: int, source_header: str | None) -> None: """Bind queue delay to structlog contextvars (best-effort).""" try: import structlog # type: ignore payload: Dict[str, Any] = {"queue_delay": int(queue_delay_ms)} if source_header: payload["queue_delay_source"] = str(source_header) structlog.contextvars.bind_contextvars(**payload) except Exception: return @app.before_request def _correlation_bind(): """Bind a short request_id to structlog context and store for response header.""" try: # Queue delay must be captured as early as possible (before business logic). try: now_epoch = float(time.time()) q_ms, q_src = _compute_queue_delay_ms(request.headers, now_epoch_seconds=now_epoch) setattr(g, "_queue_delay_ms", int(q_ms)) setattr(g, "_queue_delay_source", q_src) _bind_queue_delay_context(int(q_ms), q_src) except Exception: setattr(g, "_queue_delay_ms", 0) setattr(g, "_queue_delay_source", None) try: incoming = str(request.headers.get("X-Request-ID", "")).strip() except Exception: incoming = "" rid = incoming or (_gen_rid() or "") if rid: try: _bind_rid(rid) except Exception: pass try: # attach to request for after_request header setattr(request, "_req_id", rid) except Exception: pass try: set_current_span_attributes({"request_id": rid}) except Exception: pass try: uid = session.get("user_id") if "user_id" in session else None except Exception: uid = None try: bind_user_context(user_id=uid) except Exception: pass try: ctx = get_observability_context() or {} except Exception: ctx = {} try: updates: Dict[str, Any] = {} if isinstance(ctx, dict): if ctx.get("user_id"): updates["user_id_hash"] = ctx["user_id"] if ctx.get("chat_id"): updates["chat_id_hash"] = ctx["chat_id"] if updates: set_current_span_attributes(updates) except Exception: pass try: method = getattr(request, "method", "") or "" endpoint = getattr(request, "endpoint", "") or "" path_hint = getattr(request, "path", "") or "" identifier = endpoint or path_hint if identifier: cmd = f"webapp:{method.upper()}:{identifier}" if method else f"webapp:{identifier}" bind_command(cmd) try: set_current_span_attributes({"command": cmd}) except Exception: pass except Exception: pass except Exception: pass @app.after_request def _add_request_id_header(resp): try: rid = getattr(request, "_req_id", "") if rid: resp.headers["X-Request-ID"] = rid except Exception: pass return resp @app.before_request def _metrics_start_timer(): # minimal, best-effort try: request._metrics_start = _time.perf_counter( ) setattr(g, "_otel_cache_hit", None) note_request_started() except Exception: pass @app.after_request def _metrics_after(resp): try: start = float(getattr(request, "_metrics_start", 0.0) or 0.0) if start: dur = max(0.0, float(_time.perf_counter() - start)) status = int(getattr(resp, "status_code", 0) or 0) endpoint = getattr(request, "endpoint", None) path_label = getattr(request, "path", "") method_label = getattr(request, "method", "GET") handler_label = endpoint or path_label cache_flag = getattr(g, "_otel_cache_hit", None) record_request_outcome( status, dur, source="webapp", handler=handler_label, method=method_label, path=path_label, cache_hit=cache_flag, ) # חשוב: /triage משתמש ב-alert_manager. בפועל ייתכן שהמודול metrics (או ה-bridge שלו) # לא מזין את alert_manager בסביבה מסוימת, ולכן כאן אנחנו מדווחים תמיד (best-effort). # כדי למנוע רעש, אנחנו עדיין מסננים נתיבים סטטיים/בריאות כאשר הבקשה "ok". try: from alert_manager import note_request as _am_note_request # type: ignore # דילוג על רעש (סטטי/בריאות) רק כשהבקשה "ok". שגיאות עדיין נרשמות. try: p = str(path_label or "") except Exception: p = "" is_static = p.startswith("/static/") silent_paths = {"/metrics", "/health", "/healthz", "/favicon.ico"} is_silent_ok = (p in silent_paths) and int(status) < 400 if (not is_static) or int(status) >= 400: if not is_silent_ok: ctx: Dict[str, Any] = { "path": p, "method": str(method_label or ""), } try: if endpoint: ctx["endpoint"] = str(endpoint) except Exception: pass try: rid = getattr(request, "_req_id", None) if rid: ctx["request_id"] = str(rid) except Exception: pass try: q_ms = int(getattr(g, "_queue_delay_ms", 0) or 0) except Exception: q_ms = 0 if q_ms > 0: ctx["queue_delay_ms"] = int(q_ms) ctx = {k: v for k, v in (ctx or {}).items() if v not in (None, "", {})} _am_note_request(int(status), float(dur), source="internal", context=(ctx or None)) except Exception: pass try: method = getattr(request, "method", "GET") record_http_request(method, endpoint, status, dur, path=path_label) except Exception: pass # Queue delay instrumentation (best-effort) try: q_ms = int(getattr(g, "_queue_delay_ms", 0) or 0) except Exception: q_ms = 0 try: q_src = getattr(g, "_queue_delay_source", None) except Exception: q_src = None try: record_request_queue_delay(method_label, endpoint, float(q_ms) / 1000.0) except Exception: pass try: # Silence noisy monitoring endpoints when request is "ok". # - For health/metrics: skip only successes (<400) but keep 4xx/5xx. # - For favicon: also skip 404/4xx noise, keep 5xx. # - For root availability probes: skip HEAD / when "ok" (<400), but keep 4xx/5xx. silent_paths = {"/metrics", "/health", "/healthz", "/favicon.ico"} is_silent_path = path_label in silent_paths is_root_check = (path_label == "/" and str(method_label).upper() == "HEAD") should_silence = False if is_silent_path or is_root_check: ok_threshold = 500 if path_label == "/favicon.ico" else 400 should_silence = int(status) < int(ok_threshold) if not should_silence: rid = getattr(request, "_req_id", "") or "" access_fields: Dict[str, Any] = { "request_id": str(rid), "method": method_label, "path": path_label, "handler": handler_label, "status_code": int(status), "duration_ms": int(float(dur) * 1000), "queue_delay": int(q_ms), } if q_src: access_fields["queue_delay_source"] = str(q_src) emit_event("access_logs", severity="info", **access_fields) except Exception: pass try: threshold = _queue_delay_warn_threshold_ms() if threshold > 0 and int(q_ms) >= int(threshold): warn_fields: Dict[str, Any] = { "request_id": str(getattr(request, "_req_id", "") or ""), "queue_delay": int(q_ms), "threshold_ms": int(threshold), "method": method_label, "path": path_label, "handler": handler_label, } if q_src: warn_fields["queue_delay_source"] = str(q_src) emit_event("queue_delay_high", severity="warning", **warn_fields) except Exception: pass # מדידת זמן "בקשה ראשונה" מול זמן אתחול התהליך try: global _FIRST_REQUEST_RECORDED if not _FIRST_REQUEST_RECORDED: with _FIRST_REQUEST_LOCK: if not _FIRST_REQUEST_RECORDED: note_first_request_latency() _FIRST_REQUEST_RECORDED = True except Exception: pass except Exception: pass return resp @app.after_request def _impersonation_action_event(resp): try: method = str(getattr(request, "method", "") or "").upper() if method in ("GET", "HEAD", "OPTIONS"): return resp if not is_impersonating_safe(): return resp endpoint = getattr(request, "endpoint", None) or getattr(request, "path", "") or "unknown" target_id = None try: view_args = getattr(request, "view_args", None) or {} for key in ("file_id", "id", "snippet_id", "collection_id", "share_id"): if key in view_args: target_id = view_args.get(key) break except Exception: target_id = None emit_event( "action_performed_while_impersonating", severity="info", user_id=session.get("user_id"), action=endpoint, target_id=target_id, ) except Exception: pass return resp @app.teardown_request def _metrics_teardown(_exc): try: note_request_finished() except Exception: pass @app.after_request def _otel_record_response(resp): try: setattr(g, "_otel_response_status", int(getattr(resp, "status_code", 0) or 0)) except Exception: setattr(g, "_otel_response_status", None) span = getattr(g, "_otel_span", None) if span is not None: try: span.set_attribute("http.status_code", int(getattr(resp, "status_code", 0) or 0)) # type: ignore[attr-defined] except Exception: pass try: cache_hit_flag = getattr(g, "_otel_cache_hit", None) if cache_hit_flag is not None: span.set_attribute("cache_hit", bool(cache_hit_flag)) # type: ignore[attr-defined] except Exception: pass try: code = int(getattr(resp, "status_code", 0) or 0) span.set_attribute("status", "error" if code >= 500 else "ok") # type: ignore[attr-defined] except Exception: pass return resp @app.teardown_request def _otel_teardown_request(exc): span_cm = getattr(g, "_otel_span_cm", None) if span_cm is None: return span = getattr(g, "_otel_span", None) if span is not None and exc is not None: try: span.set_attribute("status", "error") # type: ignore[attr-defined] span.set_attribute("error_signature", type(exc).__name__) # type: ignore[attr-defined] except Exception: pass status_code = getattr(g, "_otel_response_status", None) if span is not None and status_code is not None: try: span.set_attribute("http.status_code", int(status_code)) # type: ignore[attr-defined] except Exception: pass cache_hit_flag = getattr(g, "_otel_cache_hit", None) if span is not None and cache_hit_flag is not None: try: span.set_attribute("cache_hit", bool(cache_hit_flag)) # type: ignore[attr-defined] except Exception: pass if exc is None: span_cm.__exit__(None, None, None) else: span_cm.__exit__(type(exc), exc, getattr(exc, "__traceback__", None)) setattr(g, "_otel_span_cm", None) setattr(g, "_otel_span", None) setattr(g, "_otel_response_status", None) setattr(g, "_otel_cache_hit", None) # --- Slow request logging (server-side) --- @app.after_request def _log_slow_request(resp): try: start = float(getattr(request, "_metrics_start", 0.0) or 0.0) if not start: return resp dur_ms = ( _time.perf_counter() - start ) * 1000.0 try: slow_ms = float(os.getenv("SLOW_MS", "0") or 0) except Exception: slow_ms = 0.0 if slow_ms and dur_ms > slow_ms: try: logger.warning( "slow_request", extra={ "path": getattr(request, "path", "") or "", "method": getattr(request, "method", "GET"), "status": int(getattr(resp, "status_code", 0) or 0), "ms": round(dur_ms, 1), }, ) except Exception: pass except Exception: pass return resp # --- Default CSP for HTML pages (allows CodeMirror ESM + workers) --- @app.after_request def _add_default_csp(resp): """Set a safe, permissive-enough CSP for HTML pages by default. - Allows dynamic ESM imports from common CDNs used by the webapp - Allows blob: for workers required by some CodeMirror features - Keeps frame-ancestors restricted to self Note: Route-specific responses that already set CSP (e.g. raw HTML preview) remain authoritative; we only add this header if it's missing. """ try: if 'Content-Security-Policy' not in resp.headers: content_type = resp.headers.get('Content-Type', '') if isinstance(content_type, str) and 'text/html' in content_type: resp.headers['Content-Security-Policy'] = ( "default-src 'self'; " "base-uri 'self'; " "frame-ancestors 'self'; " # Scripts: allow our origin, inline (for small in-page helpers), blob workers, and ESM from CDNs "script-src 'self' 'unsafe-inline' blob: https://cdn.jsdelivr.net https://unpkg.com https://esm.sh https://telegram.org; " # Workers used by some CM6 language/tooling integrations "worker-src 'self' blob:; " # Styles: local + inline + Google Fonts CSS + Font Awesome from cdnjs "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdnjs.cloudflare.com https://cdn.jsdelivr.net; " # Fonts: local + Google Fonts + Font Awesome webfonts + data: (icons) "font-src 'self' https://fonts.gstatic.com https://cdnjs.cloudflare.com data:; " # תמונות: מהאתר, ‏data/blob (תמונות ממוזערות ותצוגות מקדימות), ומכל כתובת http/https. תמונה # שהמשתמש כתב במסמך Markdown (``![alt](url)``) היא חלק מהמסמך, ו-markdown-it מרנדר אותה ל-```` # בכל עמוד שמציג Markdown של המשתמש — ``md_preview.html`` ו-``MarkdownLiveRenderer`` ב- # ``webapp/static/js/live-preview.js``, שמשמש כמה עמודים. כשהמדיניות התירה רק את האתר עצמו, תמונה מאתר # אחר נחסמה בדפדפן בלי שום עקבה בשרת, בכל העמודים האלה. זו אותה החלטה כמו בייצוא ובקישור השיתוף # המעוצב (``editor_export_meta_csp`` ו-``styled_share_page_csp`` ב-``services/styled_export_service.py``). # ההיתר כאן ולא לכל עמוד לחוד, כי ההגבלה לא הגנה על שום עמוד: עם ``'unsafe-inline'`` ב-``script-src`` # ובלי ``form-action`` במדיניות הזו, מי שמזריק HTML כבר יכול להריץ קוד ולשלוח מידע החוצה בלי תמונה, # ורשימת עמודים הייתה נשכחת בעמוד ה-Markdown הבא. "img-src 'self' data: blob: http: https:; " # XHR/fetch for ESM modules and assets "connect-src 'self' https://cdn.jsdelivr.net https://unpkg.com https://esm.sh https://oauth.telegram.org https://telegram.org; " # Frames: allow Telegram OAuth widget iframes "frame-src 'self' https://oauth.telegram.org https://telegram.org;" ) except Exception: # Never break responses due to header set failures pass return resp @app.after_request def _disable_html_cache(resp): """Force browsers to revalidate HTML responses unless ETag is present.""" try: content_type = resp.headers.get('Content-Type', '') if isinstance(content_type, str) and 'text/html' in content_type: # Respect explicit cache directives set by endpoints. if 'Cache-Control' in resp.headers: return resp # Allow ETag-based revalidation for pages that set validators. if 'ETag' in resp.headers: resp.headers['Cache-Control'] = 'private, max-age=0, must-revalidate' return resp resp.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' resp.headers['Pragma'] = 'no-cache' resp.headers['Expires'] = '0' except Exception: # Never fail the response if header manipulation crashes pass return resp # --- X-Content-Type-Options: nosniff on every response --- @app.after_request def _add_nosniff(resp): """הדפדפן מאמין לסוג התוכן שהשרת הצהיר עליו, ולא מנחש. בלי הכותרת, Chromium מריץ כסקריפט תשובה של ``text/plain`` שנטענה ב-`` """ return Response(html, mimetype='text/html') @app.route('/redoc') def redoc_docs(): html = """ ReDoc """ return Response(html, mimetype='text/html') # בדיקת קונפיגורציה בהפעלה def check_configuration(): """בדיקת משתני סביבה נדרשים""" required_vars = { 'MONGODB_URL': MONGODB_URL, 'BOT_TOKEN': BOT_TOKEN, 'BOT_USERNAME': BOT_USERNAME } missing = [] for var_name, var_value in required_vars.items(): if not var_value: missing.append(var_name) logger.warning("Environment variable is not configured: %s", var_name, extra={"var_name": var_name}) if missing: logger.warning("Missing required environment variables: %s", ", ".join(missing), extra={"missing": missing}) logger.warning("Please configure them in Render Dashboard or .env file") # בדיקת חיבור ל-MongoDB if MONGODB_URL: try: test_client = MongoClient(MONGODB_URL, serverSelectionTimeoutMS=5000) test_client.server_info() logger.info("MongoDB connection successful") test_client.close() except Exception as e: logger.warning("MongoDB connection failed", exc_info=e) return len(missing) == 0 def run_dev_server() -> None: """שרת הפיתוח של Flask, להרצה ישירה של הקובץ (``python app.py``). בלוק השם שבראש הקובץ קורא לפונקציה הזו מתוך ``webapp.app``, אחרי שהקובץ נטען פעם אחת בשמו. השרת מאזין ל-``127.0.0.1``: עם ``DEBUG=true`` הוא מגיש גם את הדיבאגר של Werkzeug, ולכן פתיחה לרשת דורשת ``WEBAPP_DEV_HOST`` מפורש. בגוניקורן הפונקציה לא נקראת — כתובת ההאזנה שם נקבעת ב-``scripts/start_webapp.sh``. """ logger.info("Starting Code Keeper Web App...") logger.info("BOT_USERNAME: %s", BOT_USERNAME) logger.info("DATABASE_NAME: %s", DATABASE_NAME) log_webapp_url_status(logger, service="webapp") log_legacy_redirect_status(logger) if check_configuration(): logger.info("Configuration check passed") else: logger.warning("Configuration issues detected") host = (os.getenv("WEBAPP_DEV_HOST") or "").strip() or "127.0.0.1" port = int(os.getenv('PORT', 5000)) app.run(host=host, port=port, debug=os.getenv('DEBUG', 'false').lower() == 'true')