service.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. # -*- coding: utf-8 -*-
  2. """
  3. Online-Service — Konnektivitaets-Ueberwachung.
  4. Prueft periodisch ob das System online ist:
  5. - Online: alle 5 Minuten pruefen
  6. - Offline: jede Minute pruefen
  7. Stellt einen HttpClient mit integriertem Offline-Cache bereit.
  8. Events:
  9. - online_status_changed: {"online": bool, "since": datetime}
  10. """
  11. from __future__ import annotations
  12. import asyncio
  13. import socket
  14. import time
  15. from dataclasses import dataclass
  16. from datetime import datetime
  17. from typing import TYPE_CHECKING
  18. from trixy_core.online.cache import ResponseCache
  19. from trixy_core.online.client import HttpClient
  20. from trixy_core.service import IService, ServicePriority, ServiceGroup
  21. from trixy_core.utils.debug import pinfo, pdebug, perror
  22. if TYPE_CHECKING:
  23. from trixy_core.application import BaseApplication
  24. @dataclass
  25. class OnlineServiceConfig:
  26. """Konfiguration fuer den Online-Service."""
  27. # Pruef-Intervalle (Sekunden)
  28. check_interval_online: float = 300.0 # 5 Minuten
  29. check_interval_offline: float = 60.0 # 1 Minute
  30. # Pruef-Methode: DNS-Lookup auf bekannte Hosts
  31. check_hosts: list[str] | None = None # Default: Google DNS + Cloudflare
  32. # Timeout fuer einzelne Pruefung
  33. check_timeout: float = 5.0
  34. # HTTP-Client Defaults
  35. http_timeout: float = 30.0
  36. # Cache-Verzeichnis (relativ zum Source-Dir)
  37. cache_dir: str = "cache"
  38. class OnlineService(IService):
  39. """
  40. Konnektivitaets-Service.
  41. Ueberwacht die Internet-Verbindung und stellt einen
  42. HTTP-Client mit Offline-Cache bereit.
  43. Beispiel:
  44. ```python
  45. online = app.services.get("online")
  46. # Status pruefen
  47. if online.is_online:
  48. resp = await online.http.get("https://api.example.com")
  49. # Request mit Cache (funktioniert auch offline)
  50. resp = await online.http.get(
  51. "https://api.weather.com/forecast",
  52. cache_ttl=3600,
  53. )
  54. if resp.from_cache:
  55. print("Offline — verwende gecachte Daten")
  56. ```
  57. """
  58. PRIORITY = ServicePriority.CORE
  59. GROUP = ServiceGroup.NETWORK
  60. DEPENDENCIES = []
  61. def __init__(
  62. self,
  63. application: "BaseApplication",
  64. config: OnlineServiceConfig | None = None,
  65. ) -> None:
  66. super().__init__(application)
  67. self._config = config or OnlineServiceConfig()
  68. # Status
  69. self._online = False
  70. self._online_since: datetime | None = None
  71. self._offline_since: datetime | None = datetime.now()
  72. self._last_check: float = 0.0
  73. self._check_count = 0
  74. # Check-Hosts
  75. self._check_hosts = self._config.check_hosts or [
  76. "8.8.8.8", # Google DNS
  77. "1.1.1.1", # Cloudflare DNS
  78. "9.9.9.9", # Quad9 DNS
  79. ]
  80. # Cache + HTTP-Client
  81. source_path = ""
  82. if hasattr(application, "config_manager"):
  83. source_path = getattr(application.config_manager, "base_path", "")
  84. if not source_path:
  85. source_path = "."
  86. cache_path = f"{source_path}/{self._config.cache_dir}"
  87. self._cache = ResponseCache(cache_path)
  88. self._http = HttpClient(
  89. cache=self._cache,
  90. is_online_fn=lambda: self._online,
  91. timeout=self._config.http_timeout,
  92. )
  93. # Task
  94. self._check_task: asyncio.Task | None = None
  95. # === Properties ===
  96. @property
  97. def is_online(self) -> bool:
  98. """True wenn Internet-Verbindung besteht."""
  99. return self._online
  100. @property
  101. def is_offline(self) -> bool:
  102. """True wenn keine Internet-Verbindung besteht."""
  103. return not self._online
  104. @property
  105. def online_since(self) -> datetime | None:
  106. """Zeitpunkt seit dem online. None wenn offline."""
  107. return self._online_since
  108. @property
  109. def offline_since(self) -> datetime | None:
  110. """Zeitpunkt seit dem offline. None wenn online."""
  111. return self._offline_since
  112. @property
  113. def online_duration_seconds(self) -> float:
  114. """Wie lange online in Sekunden. 0 wenn offline."""
  115. if self._online and self._online_since:
  116. return (datetime.now() - self._online_since).total_seconds()
  117. return 0.0
  118. @property
  119. def offline_duration_seconds(self) -> float:
  120. """Wie lange offline in Sekunden. 0 wenn online."""
  121. if not self._online and self._offline_since:
  122. return (datetime.now() - self._offline_since).total_seconds()
  123. return 0.0
  124. @property
  125. def http(self) -> HttpClient:
  126. """HTTP/HTTPS-Client mit Offline-Cache."""
  127. return self._http
  128. def ftp(self, config: "FTPConfig") -> "FTPClient":
  129. """
  130. Erstellt einen FTP/SFTP-Client.
  131. Nutzung als Context-Manager:
  132. ```python
  133. async with online.ftp(FTPConfig(host="...")) as ftp:
  134. await ftp.download("/remote/file", "/local/file")
  135. ```
  136. """
  137. from trixy_core.online.ftp import FTPClient
  138. return FTPClient(config)
  139. @property
  140. def cache(self) -> ResponseCache:
  141. """Zugriff auf den Response-Cache."""
  142. return self._cache
  143. # === Service Lifecycle ===
  144. async def start(self) -> None:
  145. """Startet den Online-Service."""
  146. # Initialen Check durchfuehren
  147. online = await self._check_connectivity()
  148. self._set_status(online, emit_event=False)
  149. status = "online" if self._online else "offline"
  150. pinfo(f"Online-Service gestartet (Status: {status})")
  151. # Periodischen Check starten
  152. self._check_task = asyncio.create_task(self._check_loop())
  153. async def stop(self) -> None:
  154. """Stoppt den Online-Service."""
  155. if self._check_task:
  156. self._check_task.cancel()
  157. try:
  158. await self._check_task
  159. except asyncio.CancelledError:
  160. pass
  161. self._check_task = None
  162. await self._http.close()
  163. pinfo("Online-Service gestoppt")
  164. # === Konnektivitaets-Pruefung ===
  165. async def _check_loop(self) -> None:
  166. """Periodischer Konnektivitaets-Check."""
  167. try:
  168. while True:
  169. # Intervall: 5 Min online, 1 Min offline
  170. if self._online:
  171. interval = self._config.check_interval_online
  172. else:
  173. interval = self._config.check_interval_offline
  174. await asyncio.sleep(interval)
  175. online = await self._check_connectivity()
  176. self._set_status(online)
  177. except asyncio.CancelledError:
  178. pass
  179. async def _check_connectivity(self) -> bool:
  180. """
  181. Prueft die Internet-Verbindung.
  182. Versucht einen TCP-Connect zu bekannten DNS-Servern (Port 53).
  183. Schneller und zuverlaessiger als HTTP oder ICMP.
  184. """
  185. self._last_check = time.time()
  186. self._check_count += 1
  187. for host in self._check_hosts:
  188. try:
  189. # TCP-Connect zu DNS-Port (schnell, kein Payload)
  190. _, writer = await asyncio.wait_for(
  191. asyncio.open_connection(host, 53),
  192. timeout=self._config.check_timeout,
  193. )
  194. writer.close()
  195. await writer.wait_closed()
  196. return True
  197. except (OSError, asyncio.TimeoutError):
  198. continue
  199. return False
  200. def _set_status(self, online: bool, emit_event: bool = True) -> None:
  201. """
  202. Setzt den Online-Status und loest Events aus.
  203. Events:
  204. - online_status_changed: Immer bei Statuswechsel (online/offline)
  205. - connection_online: Wenn Verbindung wiederhergestellt (war offline)
  206. - connection_offline: Wenn Verbindung verloren (war online)
  207. """
  208. if online == self._online:
  209. return # Keine Aenderung
  210. was_online = self._online
  211. self._online = online
  212. now = datetime.now()
  213. # Offline-Dauer berechnen (fuer Event-Daten)
  214. offline_duration = 0.0
  215. online_duration = 0.0
  216. if online:
  217. # Wechsel: offline → online
  218. if self._offline_since:
  219. offline_duration = (now - self._offline_since).total_seconds()
  220. self._online_since = now
  221. self._offline_since = None
  222. pinfo(f"Verbindung hergestellt — ONLINE (war {offline_duration:.0f}s offline)")
  223. else:
  224. # Wechsel: online → offline
  225. if self._online_since:
  226. online_duration = (now - self._online_since).total_seconds()
  227. self._online_since = None
  228. self._offline_since = now
  229. pinfo(f"Verbindung verloren — OFFLINE (war {online_duration:.0f}s online)")
  230. if not emit_event:
  231. return
  232. events = getattr(self._application, "events", None)
  233. if not events:
  234. return
  235. event_data = {
  236. "online": online,
  237. "since": now.isoformat(),
  238. "previous": "online" if was_online else "offline",
  239. }
  240. # 1. Allgemeines Status-Change Event (immer)
  241. asyncio.create_task(events.emit("online_status_changed", event_data))
  242. # 2. Spezifisches Event (zusaetzlich)
  243. if online:
  244. asyncio.create_task(events.emit("connection_online", {
  245. **event_data,
  246. "offline_duration_seconds": offline_duration,
  247. }))
  248. else:
  249. asyncio.create_task(events.emit("connection_offline", {
  250. **event_data,
  251. "online_duration_seconds": online_duration,
  252. }))
  253. # === Manuelle Pruefung ===
  254. async def check_now(self) -> bool:
  255. """Fuehrt sofort einen Konnektivitaets-Check durch."""
  256. online = await self._check_connectivity()
  257. self._set_status(online)
  258. return online
  259. def get_status(self) -> dict:
  260. """Gibt den aktuellen Status als Dictionary zurueck."""
  261. return {
  262. "online": self._online,
  263. "online_since": self._online_since.isoformat() if self._online_since else None,
  264. "offline_since": self._offline_since.isoformat() if self._offline_since else None,
  265. "online_duration_seconds": self.online_duration_seconds,
  266. "offline_duration_seconds": self.offline_duration_seconds,
  267. "last_check": self._last_check,
  268. "check_count": self._check_count,
  269. "cache_entries": self._cache.size,
  270. }