exec.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. """Everything regarding execution of the built app."""
  2. from __future__ import annotations
  3. import hashlib
  4. import json
  5. import os
  6. import platform
  7. import re
  8. import subprocess
  9. import sys
  10. from pathlib import Path
  11. from typing import Sequence
  12. from urllib.parse import urljoin
  13. import psutil
  14. from reflex import constants
  15. from reflex.config import environment, get_config
  16. from reflex.constants.base import LogLevel
  17. from reflex.utils import console, path_ops
  18. from reflex.utils.prerequisites import get_web_dir
  19. # For uvicorn windows bug fix (#2335)
  20. frontend_process = None
  21. def detect_package_change(json_file_path: Path) -> str:
  22. """Calculates the SHA-256 hash of a JSON file and returns it as a hexadecimal string.
  23. Args:
  24. json_file_path: The path to the JSON file to be hashed.
  25. Returns:
  26. str: The SHA-256 hash of the JSON file as a hexadecimal string.
  27. Example:
  28. >>> detect_package_change("package.json")
  29. 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2'
  30. """
  31. with json_file_path.open("r") as file:
  32. json_data = json.load(file)
  33. # Calculate the hash
  34. json_string = json.dumps(json_data, sort_keys=True)
  35. hash_object = hashlib.sha256(json_string.encode())
  36. return hash_object.hexdigest()
  37. def kill(proc_pid: int):
  38. """Kills a process and all its child processes.
  39. Args:
  40. proc_pid (int): The process ID of the process to be killed.
  41. Example:
  42. >>> kill(1234)
  43. """
  44. process = psutil.Process(proc_pid)
  45. for proc in process.children(recursive=True):
  46. proc.kill()
  47. process.kill()
  48. def notify_backend():
  49. """Output a string notifying where the backend is running."""
  50. console.print(
  51. f"Backend running at: [bold green]http://0.0.0.0:{get_config().backend_port}[/bold green]"
  52. )
  53. # run_process_and_launch_url is assumed to be used
  54. # only to launch the frontend
  55. # If this is not the case, might have to change the logic
  56. def run_process_and_launch_url(
  57. run_command: list[str | None], backend_present: bool = True
  58. ):
  59. """Run the process and launch the URL.
  60. Args:
  61. run_command: The command to run.
  62. backend_present: Whether the backend is present.
  63. """
  64. from reflex.utils import processes
  65. json_file_path = get_web_dir() / constants.PackageJson.PATH
  66. last_hash = detect_package_change(json_file_path)
  67. process = None
  68. first_run = True
  69. while True:
  70. if process is None:
  71. kwargs = {}
  72. if constants.IS_WINDOWS and backend_present:
  73. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue]
  74. process = processes.new_process(
  75. run_command,
  76. cwd=get_web_dir(),
  77. shell=constants.IS_WINDOWS,
  78. **kwargs,
  79. )
  80. global frontend_process
  81. frontend_process = process
  82. if process.stdout:
  83. for line in processes.stream_logs("Starting frontend", process):
  84. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  85. if match:
  86. if first_run:
  87. url = match.group(1)
  88. if get_config().frontend_path != "":
  89. url = urljoin(url, get_config().frontend_path)
  90. console.print(
  91. f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
  92. )
  93. if backend_present:
  94. notify_backend()
  95. first_run = False
  96. else:
  97. console.print("New packages detected: Updating app...")
  98. else:
  99. if any(
  100. x in line for x in ("bin executable does not exist on disk",)
  101. ):
  102. console.error(
  103. "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
  104. "`REFLEX_USE_NPM=1 reflex init`\n"
  105. "`REFLEX_USE_NPM=1 reflex run`"
  106. )
  107. new_hash = detect_package_change(json_file_path)
  108. if new_hash != last_hash:
  109. last_hash = new_hash
  110. kill(process.pid)
  111. process = None
  112. break # for line in process.stdout
  113. if process is not None:
  114. break # while True
  115. def run_frontend(root: Path, port: str, backend_present: bool = True):
  116. """Run the frontend.
  117. Args:
  118. root: The root path of the project.
  119. port: The port to run the frontend on.
  120. backend_present: Whether the backend is present.
  121. """
  122. from reflex.utils import prerequisites
  123. # validate dependencies before run
  124. prerequisites.validate_frontend_dependencies(init=False)
  125. # Run the frontend in development mode.
  126. console.rule("[bold green]App Running")
  127. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  128. run_process_and_launch_url(
  129. [
  130. *prerequisites.get_js_package_executor(raise_on_none=True)[0],
  131. "run",
  132. "dev",
  133. ],
  134. backend_present,
  135. )
  136. def run_frontend_prod(root: Path, port: str, backend_present: bool = True):
  137. """Run the frontend.
  138. Args:
  139. root: The root path of the project (to keep same API as run_frontend).
  140. port: The port to run the frontend on.
  141. backend_present: Whether the backend is present.
  142. """
  143. from reflex.utils import prerequisites
  144. # Set the port.
  145. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  146. # validate dependencies before run
  147. prerequisites.validate_frontend_dependencies(init=False)
  148. # Run the frontend in production mode.
  149. console.rule("[bold green]App Running")
  150. run_process_and_launch_url(
  151. [*prerequisites.get_js_package_executor(raise_on_none=True)[0], "run", "prod"],
  152. backend_present,
  153. )
  154. def should_use_granian():
  155. """Whether to use Granian for backend.
  156. Returns:
  157. True if Granian should be used.
  158. """
  159. return environment.REFLEX_USE_GRANIAN.get()
  160. def get_app_module():
  161. """Get the app module for the backend.
  162. Returns:
  163. The app module for the backend.
  164. """
  165. config = get_config()
  166. return f"{config.module}:{constants.CompileVars.APP}"
  167. def run_backend(
  168. host: str,
  169. port: int,
  170. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  171. frontend_present: bool = False,
  172. ):
  173. """Run the backend.
  174. Args:
  175. host: The app host
  176. port: The app port
  177. loglevel: The log level.
  178. frontend_present: Whether the frontend is present.
  179. """
  180. web_dir = get_web_dir()
  181. # Create a .nocompile file to skip compile for backend.
  182. if web_dir.exists():
  183. (web_dir / constants.NOCOMPILE_FILE).touch()
  184. if not frontend_present:
  185. notify_backend()
  186. # Run the backend in development mode.
  187. if should_use_granian():
  188. run_granian_backend(host, port, loglevel)
  189. else:
  190. run_uvicorn_backend(host, port, loglevel)
  191. def get_reload_paths() -> Sequence[Path]:
  192. """Get the reload paths for the backend.
  193. Returns:
  194. The reload paths for the backend.
  195. """
  196. config = get_config()
  197. reload_paths = [Path(config.app_name).parent]
  198. if config.app_module is not None and config.app_module.__file__:
  199. module_path = Path(config.app_module.__file__).resolve().parent
  200. while module_path.parent.name and any(
  201. sibling_file.name == "__init__.py"
  202. for sibling_file in module_path.parent.iterdir()
  203. ):
  204. # go up a level to find dir without `__init__.py`
  205. module_path = module_path.parent
  206. reload_paths = [module_path]
  207. include_dirs = tuple(
  208. map(Path.absolute, environment.REFLEX_HOT_RELOAD_INCLUDE_PATHS.get())
  209. )
  210. exclude_dirs = tuple(
  211. map(Path.absolute, environment.REFLEX_HOT_RELOAD_EXCLUDE_PATHS.get())
  212. )
  213. def is_excluded_by_default(path: Path) -> bool:
  214. if path.is_dir():
  215. if path.name.startswith("."):
  216. # exclude hidden directories
  217. return True
  218. if path.name.startswith("__"):
  219. # ignore things like __pycache__
  220. return True
  221. return path.name in (".gitignore", "uploaded_files")
  222. reload_paths = (
  223. tuple(
  224. path.absolute()
  225. for dir in reload_paths
  226. for path in dir.iterdir()
  227. if not is_excluded_by_default(path)
  228. )
  229. + include_dirs
  230. )
  231. if exclude_dirs:
  232. reload_paths = tuple(
  233. path
  234. for path in reload_paths
  235. if all(not path.samefile(exclude) for exclude in exclude_dirs)
  236. )
  237. console.debug(f"Reload paths: {list(map(str, reload_paths))}")
  238. return reload_paths
  239. def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel):
  240. """Run the backend in development mode using Uvicorn.
  241. Args:
  242. host: The app host
  243. port: The app port
  244. loglevel: The log level.
  245. """
  246. import uvicorn
  247. uvicorn.run(
  248. app=f"{get_app_module()}",
  249. factory=True,
  250. host=host,
  251. port=port,
  252. log_level=loglevel.value,
  253. reload=True,
  254. reload_dirs=list(map(str, get_reload_paths())),
  255. )
  256. def run_granian_backend(host: str, port: int, loglevel: LogLevel):
  257. """Run the backend in development mode using Granian.
  258. Args:
  259. host: The app host
  260. port: The app port
  261. loglevel: The log level.
  262. """
  263. console.debug("Using Granian for backend")
  264. try:
  265. from granian.constants import Interfaces
  266. from granian.log import LogLevels
  267. from granian.server import Server as Granian
  268. Granian(
  269. target=get_app_module(),
  270. factory=True,
  271. address=host,
  272. port=port,
  273. interface=Interfaces.ASGI,
  274. log_level=LogLevels(loglevel.value),
  275. reload=True,
  276. reload_paths=get_reload_paths(),
  277. ).serve()
  278. except ImportError:
  279. console.error(
  280. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  281. )
  282. os._exit(1)
  283. def _get_backend_workers():
  284. from reflex.utils import processes
  285. config = get_config()
  286. return (
  287. processes.get_num_workers()
  288. if not config.gunicorn_workers
  289. else config.gunicorn_workers
  290. )
  291. def run_backend_prod(
  292. host: str,
  293. port: int,
  294. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  295. frontend_present: bool = False,
  296. ):
  297. """Run the backend.
  298. Args:
  299. host: The app host
  300. port: The app port
  301. loglevel: The log level.
  302. frontend_present: Whether the frontend is present.
  303. """
  304. if not frontend_present:
  305. notify_backend()
  306. if should_use_granian():
  307. run_granian_backend_prod(host, port, loglevel)
  308. else:
  309. run_uvicorn_backend_prod(host, port, loglevel)
  310. def run_uvicorn_backend_prod(host: str, port: int, loglevel: LogLevel):
  311. """Run the backend in production mode using Uvicorn.
  312. Args:
  313. host: The app host
  314. port: The app port
  315. loglevel: The log level.
  316. """
  317. from reflex.utils import processes
  318. config = get_config()
  319. app_module = get_app_module()
  320. command = (
  321. [
  322. "uvicorn",
  323. *(
  324. [
  325. "--limit-max-requests",
  326. str(config.gunicorn_max_requests),
  327. ]
  328. if config.gunicorn_max_requests > 0
  329. else []
  330. ),
  331. *("--timeout-keep-alive", str(config.timeout)),
  332. *("--host", host),
  333. *("--port", str(port)),
  334. *("--workers", str(_get_backend_workers())),
  335. "--factory",
  336. app_module,
  337. ]
  338. if constants.IS_WINDOWS
  339. else [
  340. "gunicorn",
  341. *("--worker-class", config.gunicorn_worker_class),
  342. *(
  343. [
  344. "--max-requests",
  345. str(config.gunicorn_max_requests),
  346. "--max-requests-jitter",
  347. str(config.gunicorn_max_requests_jitter),
  348. ]
  349. if config.gunicorn_max_requests > 0
  350. else []
  351. ),
  352. "--preload",
  353. *("--timeout", str(config.timeout)),
  354. *("--bind", f"{host}:{port}"),
  355. *("--threads", str(_get_backend_workers())),
  356. f"{app_module}()",
  357. ]
  358. )
  359. command += [
  360. *("--log-level", loglevel.value),
  361. ]
  362. processes.new_process(
  363. command,
  364. run=True,
  365. show_logs=True,
  366. env={
  367. environment.REFLEX_SKIP_COMPILE.name: "true"
  368. }, # skip compile for prod backend
  369. )
  370. def run_granian_backend_prod(host: str, port: int, loglevel: LogLevel):
  371. """Run the backend in production mode using Granian.
  372. Args:
  373. host: The app host
  374. port: The app port
  375. loglevel: The log level.
  376. """
  377. from reflex.utils import processes
  378. try:
  379. from granian.constants import Interfaces
  380. command = [
  381. "granian",
  382. "--workers",
  383. str(_get_backend_workers()),
  384. "--log-level",
  385. "critical",
  386. "--host",
  387. host,
  388. "--port",
  389. str(port),
  390. "--interface",
  391. str(Interfaces.ASGI),
  392. "--factory",
  393. get_app_module(),
  394. ]
  395. processes.new_process(
  396. command,
  397. run=True,
  398. show_logs=True,
  399. env={
  400. environment.REFLEX_SKIP_COMPILE.name: "true"
  401. }, # skip compile for prod backend
  402. )
  403. except ImportError:
  404. console.error(
  405. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  406. )
  407. def output_system_info():
  408. """Show system information if the loglevel is in DEBUG."""
  409. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  410. return
  411. from reflex.utils import prerequisites
  412. config = get_config()
  413. try:
  414. config_file = sys.modules[config.__module__].__file__
  415. except Exception:
  416. config_file = None
  417. console.rule("System Info")
  418. console.debug(f"Config file: {config_file!r}")
  419. console.debug(f"Config: {config}")
  420. dependencies = [
  421. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  422. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  423. ]
  424. system = platform.system()
  425. dependencies.append(
  426. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {path_ops.get_bun_path()})]"
  427. )
  428. if system == "Linux":
  429. import distro # pyright: ignore[reportMissingImports]
  430. os_version = distro.name(pretty=True)
  431. else:
  432. os_version = platform.version()
  433. dependencies.append(f"[OS {platform.system()} {os_version}]")
  434. for dep in dependencies:
  435. console.debug(f"{dep}")
  436. console.debug(
  437. f"Using package installer at: {prerequisites.get_nodejs_compatible_package_managers(raise_on_none=False)}"
  438. )
  439. console.debug(
  440. f"Using package executer at: {prerequisites.get_js_package_executor(raise_on_none=False)}"
  441. )
  442. if system != "Windows":
  443. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  444. def is_testing_env() -> bool:
  445. """Whether the app is running in a testing environment.
  446. Returns:
  447. True if the app is running in under pytest.
  448. """
  449. return constants.PYTEST_CURRENT_TEST in os.environ
  450. def is_in_app_harness() -> bool:
  451. """Whether the app is running in the app harness.
  452. Returns:
  453. True if the app is running in the app harness.
  454. """
  455. return constants.APP_HARNESS_FLAG in os.environ
  456. def is_prod_mode() -> bool:
  457. """Check if the app is running in production mode.
  458. Returns:
  459. True if the app is running in production mode or False if running in dev mode.
  460. """
  461. current_mode = environment.REFLEX_ENV_MODE.get()
  462. return current_mode == constants.Env.PROD
  463. def get_compile_context() -> constants.CompileContext:
  464. """Check if the app is compiled for deploy.
  465. Returns:
  466. Whether the app is being compiled for deploy.
  467. """
  468. return environment.REFLEX_COMPILE_CONTEXT.get()