exec.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. console.print(
  65. f"DETECT_PACKAGE_CHANGE init {last_hash}, {json.dumps(json.loads(json_file_path.read_text()))}"
  66. )
  67. last_packages = (
  68. processes.new_process(
  69. ["bun", "pm", "ls"],
  70. cwd=get_web_dir(),
  71. )
  72. .stdout.read()
  73. .strip()
  74. )
  75. console.print(
  76. f"DETECT_PACKAGE_CHANGE init {last_packages}",
  77. )
  78. process = None
  79. first_run = True
  80. while True:
  81. if process is None:
  82. kwargs = {}
  83. if constants.IS_WINDOWS and backend_present:
  84. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
  85. process = processes.new_process(
  86. run_command,
  87. cwd=get_web_dir(),
  88. shell=constants.IS_WINDOWS,
  89. **kwargs,
  90. )
  91. global frontend_process
  92. frontend_process = process
  93. if process.stdout:
  94. for line in processes.stream_logs("Starting frontend", process):
  95. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  96. if match:
  97. if first_run:
  98. url = match.group(1)
  99. if get_config().frontend_path != "":
  100. url = urljoin(url, get_config().frontend_path)
  101. console.print(
  102. f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
  103. )
  104. if backend_present:
  105. notify_backend()
  106. first_run = False
  107. else:
  108. console.print(f"New packages detected: Updating app... {line}")
  109. else:
  110. if any(
  111. x in line for x in ("bin executable does not exist on disk",)
  112. ):
  113. console.error(
  114. "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
  115. "`REFLEX_USE_NPM=1 reflex init`\n"
  116. "`REFLEX_USE_NPM=1 reflex run`"
  117. )
  118. new_hash = detect_package_change(json_file_path)
  119. if new_hash != last_hash:
  120. new_content = json.dumps(json.loads(json_file_path.read_text()))
  121. console.print(
  122. f"DETECT_PACKAGE_CHANGE hit {last_hash} != {new_hash} (new), {new_content}"
  123. )
  124. last_hash = new_hash
  125. new_packages = (
  126. processes.new_process(
  127. ["bun", "pm", "ls"],
  128. cwd=get_web_dir(),
  129. )
  130. .stdout.read()
  131. .strip()
  132. )
  133. console.print(
  134. f"DETECT_PACKAGE_CHANGE init {new_packages}",
  135. )
  136. if new_packages != last_packages:
  137. last_packages = new_packages
  138. console.print("Reloading app due to new content...")
  139. kill(process.pid)
  140. process = None
  141. break # for line in process.stdout
  142. if process is not None:
  143. break # while True
  144. def run_frontend(root: Path, port: str, backend_present=True):
  145. """Run the frontend.
  146. Args:
  147. root: The root path of the project.
  148. port: The port to run the frontend on.
  149. backend_present: Whether the backend is present.
  150. """
  151. from reflex.utils import prerequisites
  152. # validate dependencies before run
  153. prerequisites.validate_frontend_dependencies(init=False)
  154. # Run the frontend in development mode.
  155. console.rule("[bold green]App Running")
  156. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  157. run_process_and_launch_url(
  158. [prerequisites.get_package_manager(), "run", "dev"], # type: ignore
  159. backend_present,
  160. )
  161. def run_frontend_prod(root: Path, port: str, backend_present=True):
  162. """Run the frontend.
  163. Args:
  164. root: The root path of the project (to keep same API as run_frontend).
  165. port: The port to run the frontend on.
  166. backend_present: Whether the backend is present.
  167. """
  168. from reflex.utils import prerequisites
  169. # Set the port.
  170. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  171. # validate dependencies before run
  172. prerequisites.validate_frontend_dependencies(init=False)
  173. # Run the frontend in production mode.
  174. console.rule("[bold green]App Running")
  175. run_process_and_launch_url(
  176. [prerequisites.get_package_manager(), "run", "prod"], # type: ignore
  177. backend_present,
  178. )
  179. def should_use_granian():
  180. """Whether to use Granian for backend.
  181. Returns:
  182. True if Granian should be used.
  183. """
  184. return environment.REFLEX_USE_GRANIAN.get()
  185. def get_app_module():
  186. """Get the app module for the backend.
  187. Returns:
  188. The app module for the backend.
  189. """
  190. return f"reflex.app_module_for_backend:{constants.CompileVars.APP}"
  191. def get_granian_target():
  192. """Get the Granian target for the backend.
  193. Returns:
  194. The Granian target for the backend.
  195. """
  196. import reflex
  197. app_module_path = Path(reflex.__file__).parent / "app_module_for_backend.py"
  198. return (
  199. f"{app_module_path!s}:{constants.CompileVars.APP}.{constants.CompileVars.API}"
  200. )
  201. def run_backend(
  202. host: str,
  203. port: int,
  204. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  205. frontend_present: bool = False,
  206. ):
  207. """Run the backend.
  208. Args:
  209. host: The app host
  210. port: The app port
  211. loglevel: The log level.
  212. frontend_present: Whether the frontend is present.
  213. """
  214. web_dir = get_web_dir()
  215. # Create a .nocompile file to skip compile for backend.
  216. if web_dir.exists():
  217. (web_dir / constants.NOCOMPILE_FILE).touch()
  218. if not frontend_present:
  219. notify_backend()
  220. # Run the backend in development mode.
  221. if should_use_granian():
  222. run_granian_backend(host, port, loglevel)
  223. else:
  224. run_uvicorn_backend(host, port, loglevel)
  225. def run_uvicorn_backend(host, port, loglevel: LogLevel):
  226. """Run the backend in development mode using Uvicorn.
  227. Args:
  228. host: The app host
  229. port: The app port
  230. loglevel: The log level.
  231. """
  232. import uvicorn
  233. uvicorn.run(
  234. app=f"{get_app_module()}.{constants.CompileVars.API}",
  235. host=host,
  236. port=port,
  237. log_level=loglevel.value,
  238. reload=True,
  239. reload_dirs=[get_config().app_name],
  240. )
  241. def run_granian_backend(host, port, loglevel: LogLevel):
  242. """Run the backend in development mode using Granian.
  243. Args:
  244. host: The app host
  245. port: The app port
  246. loglevel: The log level.
  247. """
  248. console.debug("Using Granian for backend")
  249. try:
  250. from granian import Granian # type: ignore
  251. from granian.constants import Interfaces # type: ignore
  252. from granian.log import LogLevels # type: ignore
  253. Granian(
  254. target=get_granian_target(),
  255. address=host,
  256. port=port,
  257. interface=Interfaces.ASGI,
  258. log_level=LogLevels(loglevel.value),
  259. reload=True,
  260. reload_paths=[Path(get_config().app_name)],
  261. reload_ignore_dirs=[".web"],
  262. ).serve()
  263. except ImportError:
  264. console.error(
  265. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  266. )
  267. os._exit(1)
  268. def _get_backend_workers():
  269. from reflex.utils import processes
  270. config = get_config()
  271. return (
  272. processes.get_num_workers()
  273. if not config.gunicorn_workers
  274. else config.gunicorn_workers
  275. )
  276. def run_backend_prod(
  277. host: str,
  278. port: int,
  279. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  280. frontend_present: bool = False,
  281. ):
  282. """Run the backend.
  283. Args:
  284. host: The app host
  285. port: The app port
  286. loglevel: The log level.
  287. frontend_present: Whether the frontend is present.
  288. """
  289. if not frontend_present:
  290. notify_backend()
  291. if should_use_granian():
  292. run_granian_backend_prod(host, port, loglevel)
  293. else:
  294. run_uvicorn_backend_prod(host, port, loglevel)
  295. def run_uvicorn_backend_prod(host, port, loglevel):
  296. """Run the backend in production mode using Uvicorn.
  297. Args:
  298. host: The app host
  299. port: The app port
  300. loglevel: The log level.
  301. """
  302. from reflex.utils import processes
  303. config = get_config()
  304. app_module = get_app_module()
  305. 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()
  306. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --limit-max-requests {config.gunicorn_max_requests} --timeout-keep-alive {config.timeout}".split()
  307. command = (
  308. [
  309. *RUN_BACKEND_PROD_WINDOWS,
  310. "--host",
  311. host,
  312. "--port",
  313. str(port),
  314. app_module,
  315. ]
  316. if constants.IS_WINDOWS
  317. else [
  318. *RUN_BACKEND_PROD,
  319. "--bind",
  320. f"{host}:{port}",
  321. "--threads",
  322. str(_get_backend_workers()),
  323. f"{app_module}()",
  324. ]
  325. )
  326. command += [
  327. "--log-level",
  328. loglevel.value,
  329. "--workers",
  330. str(_get_backend_workers()),
  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. def run_granian_backend_prod(host, port, loglevel):
  341. """Run the backend in production mode using Granian.
  342. Args:
  343. host: The app host
  344. port: The app port
  345. loglevel: The log level.
  346. """
  347. from reflex.utils import processes
  348. try:
  349. from granian.constants import Interfaces # type: ignore
  350. command = [
  351. "granian",
  352. "--workers",
  353. str(_get_backend_workers()),
  354. "--log-level",
  355. "critical",
  356. "--host",
  357. host,
  358. "--port",
  359. str(port),
  360. "--interface",
  361. str(Interfaces.ASGI),
  362. get_granian_target(),
  363. ]
  364. processes.new_process(
  365. command,
  366. run=True,
  367. show_logs=True,
  368. env={
  369. environment.REFLEX_SKIP_COMPILE.name: "true"
  370. }, # skip compile for prod backend
  371. )
  372. except ImportError:
  373. console.error(
  374. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  375. )
  376. def output_system_info():
  377. """Show system information if the loglevel is in DEBUG."""
  378. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  379. return
  380. from reflex.utils import prerequisites
  381. config = get_config()
  382. try:
  383. config_file = sys.modules[config.__module__].__file__
  384. except Exception:
  385. config_file = None
  386. console.rule("System Info")
  387. console.debug(f"Config file: {config_file!r}")
  388. console.debug(f"Config: {config}")
  389. dependencies = [
  390. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  391. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  392. ]
  393. system = platform.system()
  394. if system != "Windows" or (
  395. system == "Windows" and prerequisites.is_windows_bun_supported()
  396. ):
  397. dependencies.extend(
  398. [
  399. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  400. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {config.bun_path})]",
  401. ],
  402. )
  403. else:
  404. dependencies.append(
  405. f"[FNM {prerequisites.get_fnm_version()} (Expected: {constants.Fnm.VERSION}) (PATH: {constants.Fnm.EXE})]",
  406. )
  407. if system == "Linux":
  408. import distro # type: ignore
  409. os_version = distro.name(pretty=True)
  410. else:
  411. os_version = platform.version()
  412. dependencies.append(f"[OS {platform.system()} {os_version}]")
  413. for dep in dependencies:
  414. console.debug(f"{dep}")
  415. console.debug(
  416. f"Using package installer at: {prerequisites.get_install_package_manager(on_failure_return_none=True)}" # type: ignore
  417. )
  418. console.debug(
  419. f"Using package executer at: {prerequisites.get_package_manager(on_failure_return_none=True)}"
  420. ) # type: ignore
  421. if system != "Windows":
  422. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  423. def is_testing_env() -> bool:
  424. """Whether the app is running in a testing environment.
  425. Returns:
  426. True if the app is running in under pytest.
  427. """
  428. return constants.PYTEST_CURRENT_TEST in os.environ
  429. def is_prod_mode() -> bool:
  430. """Check if the app is running in production mode.
  431. Returns:
  432. True if the app is running in production mode or False if running in dev mode.
  433. """
  434. current_mode = environment.REFLEX_ENV_MODE.get()
  435. return current_mode == constants.Env.PROD
  436. def is_frontend_only() -> bool:
  437. """Check if the app is running in frontend-only mode.
  438. Returns:
  439. True if the app is running in frontend-only mode.
  440. """
  441. console.deprecate(
  442. "is_frontend_only() is deprecated and will be removed in a future release.",
  443. reason="Use `environment.REFLEX_FRONTEND_ONLY.get()` instead.",
  444. deprecation_version="0.6.5",
  445. removal_version="0.7.0",
  446. )
  447. return environment.REFLEX_FRONTEND_ONLY.get()
  448. def is_backend_only() -> bool:
  449. """Check if the app is running in backend-only mode.
  450. Returns:
  451. True if the app is running in backend-only mode.
  452. """
  453. console.deprecate(
  454. "is_backend_only() is deprecated and will be removed in a future release.",
  455. reason="Use `environment.REFLEX_BACKEND_ONLY.get()` instead.",
  456. deprecation_version="0.6.5",
  457. removal_version="0.7.0",
  458. )
  459. return environment.REFLEX_BACKEND_ONLY.get()
  460. def should_skip_compile() -> bool:
  461. """Whether the app should skip compile.
  462. Returns:
  463. True if the app should skip compile.
  464. """
  465. console.deprecate(
  466. "should_skip_compile() is deprecated and will be removed in a future release.",
  467. reason="Use `environment.REFLEX_SKIP_COMPILE.get()` instead.",
  468. deprecation_version="0.6.5",
  469. removal_version="0.7.0",
  470. )
  471. return environment.REFLEX_SKIP_COMPILE.get()