exec.py 19 KB

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