storage.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import asyncio
  2. import contextvars
  3. import os
  4. import time
  5. import uuid
  6. from collections.abc import MutableMapping
  7. from datetime import timedelta
  8. from pathlib import Path
  9. from typing import Any, Dict, Iterator, Optional, Union
  10. import aiofiles
  11. from starlette.middleware import Middleware
  12. from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
  13. from starlette.middleware.sessions import SessionMiddleware
  14. from starlette.requests import Request
  15. from starlette.responses import Response
  16. from . import background_tasks, core, json, observables
  17. from .context import context
  18. from .logging import log
  19. from .observables import ObservableDict
  20. request_contextvar: contextvars.ContextVar[Optional[Request]] = contextvars.ContextVar('request_var', default=None)
  21. PURGE_INTERVAL = timedelta(minutes=5).total_seconds()
  22. class ReadOnlyDict(MutableMapping):
  23. def __init__(self, data: Dict[Any, Any], write_error_message: str = 'Read-only dict') -> None:
  24. self._data: Dict[Any, Any] = data
  25. self._write_error_message: str = write_error_message
  26. def __getitem__(self, item: Any) -> Any:
  27. return self._data[item]
  28. def __setitem__(self, key: Any, value: Any) -> None:
  29. raise TypeError(self._write_error_message)
  30. def __delitem__(self, key: Any) -> None:
  31. raise TypeError(self._write_error_message)
  32. def __iter__(self) -> Iterator:
  33. return iter(self._data)
  34. def __len__(self) -> int:
  35. return len(self._data)
  36. class PersistentDict(observables.ObservableDict):
  37. def __init__(self, filepath: Path, encoding: Optional[str] = None, *, indent: bool = False) -> None:
  38. self.filepath = filepath
  39. self.encoding = encoding
  40. self.indent = indent
  41. try:
  42. data = json.loads(filepath.read_text(encoding)) if filepath.exists() else {}
  43. except Exception:
  44. log.warning(f'Could not load storage file {filepath}')
  45. data = {}
  46. super().__init__(data, on_change=self.backup)
  47. def backup(self) -> None:
  48. """Back up the data to the given file path."""
  49. if not self.filepath.exists():
  50. if not self:
  51. return
  52. self.filepath.parent.mkdir(exist_ok=True)
  53. async def backup() -> None:
  54. async with aiofiles.open(self.filepath, 'w', encoding=self.encoding) as f:
  55. await f.write(json.dumps(self, indent=self.indent))
  56. if core.loop:
  57. background_tasks.create_lazy(backup(), name=self.filepath.stem)
  58. else:
  59. core.app.on_startup(backup())
  60. class RequestTrackingMiddleware(BaseHTTPMiddleware):
  61. async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
  62. request_contextvar.set(request)
  63. if 'id' not in request.session:
  64. request.session['id'] = str(uuid.uuid4())
  65. request.state.responded = False
  66. response = await call_next(request)
  67. request.state.responded = True
  68. return response
  69. def set_storage_secret(storage_secret: Optional[str] = None) -> None:
  70. """Set storage_secret and add request tracking middleware."""
  71. if any(m.cls == SessionMiddleware for m in core.app.user_middleware):
  72. # NOTE not using "add_middleware" because it would be the wrong order
  73. core.app.user_middleware.append(Middleware(RequestTrackingMiddleware))
  74. elif storage_secret is not None:
  75. core.app.add_middleware(RequestTrackingMiddleware)
  76. core.app.add_middleware(SessionMiddleware, secret_key=storage_secret)
  77. Storage.secret = storage_secret
  78. class Storage:
  79. secret: Optional[str] = None
  80. def __init__(self) -> None:
  81. self.path = Path(os.environ.get('NICEGUI_STORAGE_PATH', '.nicegui')).resolve()
  82. self.max_tab_storage_age = timedelta(days=30).total_seconds()
  83. self._general = PersistentDict(self.path / 'storage-general.json', encoding='utf-8')
  84. self._users: Dict[str, PersistentDict] = {}
  85. self._tabs: Dict[str, observables.ObservableDict] = {}
  86. @property
  87. def browser(self) -> Union[ReadOnlyDict, Dict]:
  88. """Small storage that is saved directly within the user's browser (encrypted cookie).
  89. The data is shared between all browser tabs and can only be modified before the initial request has been submitted.
  90. Therefore it is normally better to use `app.storage.user` instead,
  91. which can be modified anytime, reduces overall payload, improves security and has larger storage capacity.
  92. """
  93. request: Optional[Request] = request_contextvar.get()
  94. if request is None:
  95. if self._is_in_auto_index_context():
  96. raise RuntimeError('app.storage.browser can only be used with page builder functions '
  97. '(https://nicegui.io/documentation/page)')
  98. if Storage.secret is None:
  99. raise RuntimeError('app.storage.browser needs a storage_secret passed in ui.run()')
  100. raise RuntimeError('app.storage.browser can only be used within a UI context')
  101. if request.state.responded:
  102. return ReadOnlyDict(
  103. request.session,
  104. 'the response to the browser has already been built, so modifications cannot be sent back anymore'
  105. )
  106. return request.session
  107. @property
  108. def user(self) -> PersistentDict:
  109. """Individual user storage that is persisted on the server (where NiceGUI is executed).
  110. The data is stored in a file on the server.
  111. It is shared between all browser tabs by identifying the user via session cookie ID.
  112. """
  113. request: Optional[Request] = request_contextvar.get()
  114. if request is None:
  115. if self._is_in_auto_index_context():
  116. raise RuntimeError('app.storage.user can only be used with page builder functions '
  117. '(https://nicegui.io/documentation/page)')
  118. if Storage.secret is None:
  119. raise RuntimeError('app.storage.user needs a storage_secret passed in ui.run()')
  120. raise RuntimeError('app.storage.user can only be used within a UI context')
  121. session_id = request.session['id']
  122. if session_id not in self._users:
  123. self._users[session_id] = PersistentDict(self.path / f'storage-user-{session_id}.json', encoding='utf-8')
  124. return self._users[session_id]
  125. @staticmethod
  126. def _is_in_auto_index_context() -> bool:
  127. try:
  128. return context.client.is_auto_index_client
  129. except RuntimeError:
  130. return False # no client
  131. @property
  132. def general(self) -> PersistentDict:
  133. """General storage shared between all users that is persisted on the server (where NiceGUI is executed)."""
  134. return self._general
  135. @property
  136. def client(self) -> ObservableDict:
  137. """A volatile storage that is only kept during the current connection to the client.
  138. Like `app.storage.tab` data is unique per browser tab but is even more volatile as it is already discarded
  139. when the connection to the client is lost through a page reload or a navigation.
  140. """
  141. if self._is_in_auto_index_context():
  142. raise RuntimeError('app.storage.client can only be used with page builder functions '
  143. '(https://nicegui.io/documentation/page)')
  144. return context.client.storage
  145. @property
  146. def tab(self) -> observables.ObservableDict:
  147. """A volatile storage that is only kept during the current tab session."""
  148. if self._is_in_auto_index_context():
  149. raise RuntimeError('app.storage.tab can only be used with page builder functions '
  150. '(https://nicegui.io/documentation/page)')
  151. client = context.client
  152. if not client.has_socket_connection:
  153. raise RuntimeError('app.storage.tab can only be used with a client connection; '
  154. 'see https://nicegui.io/documentation/page#wait_for_client_connection to await it')
  155. assert client.tab_id is not None
  156. if client.tab_id not in self._tabs:
  157. self._tabs[client.tab_id] = observables.ObservableDict()
  158. return self._tabs[client.tab_id]
  159. async def prune_tab_storage(self) -> None:
  160. """Regularly prune tab storage that is older than the configured `max_tab_storage_age`."""
  161. while True:
  162. for tab_id, tab in list(self._tabs.items()):
  163. if time.time() > tab.last_modified + self.max_tab_storage_age:
  164. del self._tabs[tab_id]
  165. await asyncio.sleep(PURGE_INTERVAL)
  166. def clear(self) -> None:
  167. """Clears all storage."""
  168. self._general.clear()
  169. self._users.clear()
  170. try:
  171. client = context.client
  172. except RuntimeError:
  173. pass # no client, could be a pytest
  174. else:
  175. client.storage.clear()
  176. self._tabs.clear()
  177. for filepath in self.path.glob('storage-*.json'):
  178. filepath.unlink()
  179. if self.path.exists():
  180. self.path.rmdir()