|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +from datetime import datetime, timedelta |
| 5 | +from typing import TYPE_CHECKING, Literal |
| 6 | + |
| 7 | +from django.contrib.auth import get_user_model |
| 8 | +from django.utils import timezone |
| 9 | + |
| 10 | +_logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from reactpy_django.models import Config |
| 14 | + |
| 15 | +CLEAN_NEEDED_BY: datetime = datetime( |
| 16 | + year=1, month=1, day=1, tzinfo=timezone.now().tzinfo |
| 17 | +) |
| 18 | + |
| 19 | + |
| 20 | +def clean( |
| 21 | + *args: Literal["all", "sessions", "user_data"], |
| 22 | + immediate: bool = False, |
| 23 | + verbosity: int = 1, |
| 24 | +): |
| 25 | + from reactpy_django.config import ( |
| 26 | + REACTPY_CLEAN_SESSIONS, |
| 27 | + REACTPY_CLEAN_USER_DATA, |
| 28 | + ) |
| 29 | + from reactpy_django.models import Config |
| 30 | + |
| 31 | + config = Config.load() |
| 32 | + if immediate or is_clean_needed(config): |
| 33 | + config.cleaned_at = timezone.now() |
| 34 | + config.save() |
| 35 | + sessions = REACTPY_CLEAN_SESSIONS |
| 36 | + user_data = REACTPY_CLEAN_USER_DATA |
| 37 | + |
| 38 | + if args: |
| 39 | + sessions = any(value in args for value in {"sessions", "all"}) |
| 40 | + user_data = any(value in args for value in {"user_data", "all"}) |
| 41 | + |
| 42 | + if sessions: |
| 43 | + clean_sessions(verbosity) |
| 44 | + if user_data: |
| 45 | + clean_user_data(verbosity) |
| 46 | + |
| 47 | + |
| 48 | +def clean_sessions(verbosity: int = 1): |
| 49 | + """Deletes expired component sessions from the database. |
| 50 | + As a performance optimization, this is only run once every REACTPY_SESSION_MAX_AGE seconds. |
| 51 | + """ |
| 52 | + from reactpy_django.config import REACTPY_DEBUG_MODE, REACTPY_SESSION_MAX_AGE |
| 53 | + from reactpy_django.models import ComponentSession |
| 54 | + |
| 55 | + if verbosity >= 2: |
| 56 | + print("Cleaning ReactPy component sessions...") |
| 57 | + |
| 58 | + start_time = timezone.now() |
| 59 | + expiration_date = timezone.now() - timedelta(seconds=REACTPY_SESSION_MAX_AGE) |
| 60 | + session_objects = ComponentSession.objects.filter( |
| 61 | + last_accessed__lte=expiration_date |
| 62 | + ) |
| 63 | + |
| 64 | + if verbosity >= 2: |
| 65 | + print(f"Deleting {session_objects.count()} expired component sessions...") |
| 66 | + |
| 67 | + session_objects.delete() |
| 68 | + |
| 69 | + if REACTPY_DEBUG_MODE or verbosity >= 2: |
| 70 | + inspect_clean_duration(start_time, "component sessions", verbosity) |
| 71 | + |
| 72 | + |
| 73 | +def clean_user_data(verbosity: int = 1): |
| 74 | + """Delete any user data that is not associated with an existing `User`. |
| 75 | + This is a safety measure to ensure that we don't have any orphaned data in the database. |
| 76 | +
|
| 77 | + Our `UserDataModel` is supposed to automatically get deleted on every `User` delete signal. |
| 78 | + However, we can't use Django to enforce this relationship since ReactPy can be configured to |
| 79 | + use any database. |
| 80 | + """ |
| 81 | + from reactpy_django.config import REACTPY_DEBUG_MODE |
| 82 | + from reactpy_django.models import UserDataModel |
| 83 | + |
| 84 | + if verbosity >= 2: |
| 85 | + print("Cleaning ReactPy user data...") |
| 86 | + |
| 87 | + start_time = timezone.now() |
| 88 | + user_model = get_user_model() |
| 89 | + all_users = user_model.objects.all() |
| 90 | + all_user_pks = all_users.values_list(user_model._meta.pk.name, flat=True) # type: ignore |
| 91 | + |
| 92 | + # Django doesn't support using QuerySets as an argument with cross-database relations. |
| 93 | + if user_model.objects.db != UserDataModel.objects.db: |
| 94 | + all_user_pks = list(all_user_pks) # type: ignore |
| 95 | + |
| 96 | + user_data_objects = UserDataModel.objects.exclude(user_pk__in=all_user_pks) |
| 97 | + |
| 98 | + if verbosity >= 2: |
| 99 | + print( |
| 100 | + f"Deleting {user_data_objects.count()} user data objects not associated with an existing user..." |
| 101 | + ) |
| 102 | + |
| 103 | + user_data_objects.delete() |
| 104 | + |
| 105 | + if REACTPY_DEBUG_MODE or verbosity >= 2: |
| 106 | + inspect_clean_duration(start_time, "user data", verbosity) |
| 107 | + |
| 108 | + |
| 109 | +def is_clean_needed(config: Config | None = None) -> bool: |
| 110 | + """Check if a clean is needed. This function avoids unnecessary database reads by caching the |
| 111 | + CLEAN_NEEDED_BY date.""" |
| 112 | + from reactpy_django.config import REACTPY_CLEAN_INTERVAL |
| 113 | + from reactpy_django.models import Config |
| 114 | + |
| 115 | + global CLEAN_NEEDED_BY |
| 116 | + |
| 117 | + if REACTPY_CLEAN_INTERVAL is None: |
| 118 | + return False |
| 119 | + |
| 120 | + if timezone.now() >= CLEAN_NEEDED_BY: |
| 121 | + config = config or Config.load() |
| 122 | + CLEAN_NEEDED_BY = config.cleaned_at + timedelta(seconds=REACTPY_CLEAN_INTERVAL) |
| 123 | + |
| 124 | + return timezone.now() >= CLEAN_NEEDED_BY |
| 125 | + |
| 126 | + |
| 127 | +def inspect_clean_duration(start_time: datetime, task_name: str, verbosity: int): |
| 128 | + clean_duration = timezone.now() - start_time |
| 129 | + |
| 130 | + if verbosity >= 3: |
| 131 | + print( |
| 132 | + f"Cleaned ReactPy {task_name} in {clean_duration.total_seconds()} seconds." |
| 133 | + ) |
| 134 | + |
| 135 | + if clean_duration.total_seconds() > 1: |
| 136 | + _logger.warning( |
| 137 | + "ReactPy has taken %s seconds to clean %s. " |
| 138 | + "This may indicate a performance issue with your system, cache, or database.", |
| 139 | + clean_duration.total_seconds(), |
| 140 | + task_name, |
| 141 | + ) |
0 commit comments