exec.py 16 KB

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