Dev.vala 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. using GLib;
  2. namespace Spry.Cli {
  3. /**
  4. * `spry dev` — build, run and watch the application.
  5. *
  6. * Sets up the builddir when absent, builds with ninja, spawns the app
  7. * binary with the stack's library environment, then watches `src/`,
  8. * `meson.build` and `web-config.json`. On change it rebuilds
  9. * incrementally — meson's dependency graph re-runs the statum-mkpstm /
  10. * statum-mkres code generation automatically — and restarts the binary
  11. * when the build succeeds. On failure the compiler errors are shown and
  12. * the previous process keeps running, so the loop is never left dead.
  13. *
  14. * Restarts are cheap by design: Statum state is client-carried, the
  15. * browser transparently recovers via the transmit(retry) protocol, and
  16. * session identity survives via the static keys in web-config.json —
  17. * just refresh the page.
  18. */
  19. public class Dev : Object {
  20. /** Delay bundling rapid consecutive saves into one rebuild. */
  21. private const uint DEBOUNCE_MS = 200;
  22. /** Grace period after SIGTERM before escalating to SIGKILL. */
  23. private const uint KILL_GRACE_SECONDS = 3;
  24. private string app_dir;
  25. private string app_name;
  26. private string build_dir;
  27. private string binary_path;
  28. private string? libdir;
  29. private int port;
  30. private MainLoop loop;
  31. private SubprocessLauncher launcher;
  32. private Subprocess? app_process = null;
  33. private FileMonitor[] monitors = {};
  34. private uint debounce_source = 0;
  35. private bool expect_exit = false;
  36. private bool shutting_down = false;
  37. /**
  38. * Runs the dev loop in `app_dir`. Does not return until the user
  39. * interrupts it (Ctrl-C) or the initial build fails.
  40. */
  41. public static int run(string app_dir, string app_name, int port, bool fresh,
  42. bool no_run, string? libdir) throws Error {
  43. var dev = new Dev();
  44. dev.app_dir = app_dir;
  45. dev.app_name = app_name;
  46. dev.build_dir = Path.build_filename(app_dir, "builddir");
  47. dev.binary_path = Path.build_filename(dev.build_dir, app_name);
  48. dev.libdir = libdir;
  49. dev.port = port;
  50. if (fresh) {
  51. dev.reset_database();
  52. }
  53. dev.launcher = new SubprocessLauncher(SubprocessFlags.NONE);
  54. Tools.apply_env(dev.launcher, libdir);
  55. if (!FileUtils.test(Path.build_filename(dev.build_dir, "build.ninja"), FileTest.EXISTS)) {
  56. dev.step("Configuring builddir");
  57. if (!dev.spawn_sync({ "meson", "setup", ".", "builddir" })) {
  58. stderr.printf("[spry] meson setup failed — fix the errors above and re-run spry dev\n");
  59. return 1;
  60. }
  61. }
  62. dev.step("Building");
  63. if (!dev.build()) {
  64. return 1;
  65. }
  66. CompileCommands.copy_from_builddir(dev.app_dir);
  67. if (no_run) {
  68. return 0;
  69. }
  70. dev.loop = new MainLoop();
  71. dev.watch_sources();
  72. dev.install_signal_handlers();
  73. dev.spawn_child();
  74. dev.loop.run();
  75. return 0;
  76. }
  77. // ------------------------------------------------------------------
  78. // Build / run / restart
  79. // ------------------------------------------------------------------
  80. /** Deletes the application's SQLite store (honouring SPRY_DB_PATH). */
  81. private void reset_database() {
  82. var configured = Environment.get_variable("SPRY_DB_PATH");
  83. var path = configured != null && configured.length > 0
  84. ? configured
  85. : app_name + ".sqlite";
  86. if (FileUtils.test(path, FileTest.EXISTS)) {
  87. FileUtils.remove(path);
  88. stdout.printf("[spry] Deleted %s\n", path);
  89. }
  90. }
  91. /** Incrementally builds; returns true on success. */
  92. private bool build() throws Error {
  93. return spawn_sync({ "ninja", "-C", "builddir" });
  94. }
  95. /**
  96. * Runs a short-lived child that inherits this process's stdio,
  97. * with the stack's library environment applied.
  98. */
  99. private bool spawn_sync(string[] argv) throws Error {
  100. var process = launcher.spawnv(argv);
  101. try {
  102. process.wait_check();
  103. return true;
  104. } catch (Error e) {
  105. return false;
  106. }
  107. }
  108. private void spawn_child() {
  109. try {
  110. expect_exit = false;
  111. app_process = launcher.spawnv({ binary_path, port.to_string() });
  112. stdout.printf("[spry] Running %s on port %d (Ctrl-C to stop)\n", app_name, port);
  113. watch_child.begin();
  114. } catch (Error e) {
  115. stderr.printf("[spry] Could not run %s: %s\n", binary_path, e.message);
  116. }
  117. }
  118. /**
  119. * The single lifecycle waiter for the running child: on an expected
  120. * exit (restart) it spawns the replacement; on an unexpected exit it
  121. * reports and leaves the loop watching for the next successful
  122. * rebuild.
  123. */
  124. private async void watch_child() {
  125. var process = app_process;
  126. if (process == null) {
  127. return;
  128. }
  129. try {
  130. yield ((!)process).wait_async(null);
  131. } catch (Error e) {
  132. }
  133. if (shutting_down) {
  134. return;
  135. }
  136. if (expect_exit) {
  137. spawn_child();
  138. } else {
  139. app_process = null;
  140. stdout.printf("[spry] %s exited — save a file to rebuild, or Ctrl-C to quit\n", app_name);
  141. }
  142. }
  143. /** Rebuilds and, on success, replaces the running child. */
  144. private void rebuild() {
  145. if (shutting_down) {
  146. return;
  147. }
  148. step("Rebuilding");
  149. try {
  150. if (!build()) {
  151. stdout.printf("[spry] Build failed — %s is still running\n", app_name);
  152. return;
  153. }
  154. } catch (Error e) {
  155. stderr.printf("[spry] Build could not run: %s\n", e.message);
  156. return;
  157. }
  158. CompileCommands.copy_from_builddir(app_dir);
  159. restart_child();
  160. }
  161. /**
  162. * Stops the running child (SIGTERM, escalating to SIGKILL after the
  163. * grace period); the lifecycle waiter spawns the replacement once it
  164. * observes the exit. When no child is running the replacement starts
  165. * immediately.
  166. */
  167. private void restart_child() {
  168. var process = app_process;
  169. if (process == null) {
  170. spawn_child();
  171. return;
  172. }
  173. expect_exit = true;
  174. ((!)process).send_signal(ProcessSignal.TERM);
  175. Timeout.add_seconds(KILL_GRACE_SECONDS, () => {
  176. if (!shutting_down && app_process == process && !((!)process).get_if_exited()) {
  177. stdout.printf("[spry] %s did not exit — killing it\n", app_name);
  178. ((!)process).send_signal(ProcessSignal.KILL);
  179. }
  180. return false;
  181. });
  182. }
  183. // ------------------------------------------------------------------
  184. // Watching
  185. // ------------------------------------------------------------------
  186. /** Watches the application's sources for changes. */
  187. private void watch_sources() throws Error {
  188. watch_tree(File.new_for_path(Path.build_filename(app_dir, "src")));
  189. watch_file(Path.build_filename(app_dir, "meson.build"));
  190. watch_file(Path.build_filename(app_dir, "web-config.json"));
  191. }
  192. private void watch_tree(File directory) {
  193. watch_directory(directory);
  194. try {
  195. var enumerator = directory.enumerate_children("standard::name,standard::type",
  196. FileQueryInfoFlags.NONE);
  197. FileInfo info;
  198. while ((info = enumerator.next_file()) != null) {
  199. if (info.get_file_type() == FileType.DIRECTORY) {
  200. watch_tree(File.new_for_path(
  201. Path.build_filename((!) directory.get_path(), info.get_name())));
  202. }
  203. }
  204. } catch (Error e) {
  205. stderr.printf("[spry] Could not enumerate %s: %s\n", directory.get_path(), e.message);
  206. }
  207. }
  208. /**
  209. * Attaches a directory monitor; newly created subdirectories are
  210. * picked up as well, so `spry add` output is watched without a
  211. * restart.
  212. */
  213. private void watch_directory(File directory) {
  214. try {
  215. var monitor = directory.monitor_directory(FileMonitorFlags.NONE);
  216. monitor.changed.connect((file, other, event) => {
  217. if (event == FileMonitorEvent.CREATED && file.query_file_type(FileQueryInfoFlags.NONE) == FileType.DIRECTORY) {
  218. watch_tree(file);
  219. }
  220. if (event != FileMonitorEvent.CHANGES_DONE_HINT) {
  221. schedule_rebuild();
  222. }
  223. });
  224. monitors += monitor;
  225. } catch (Error e) {
  226. stderr.printf("[spry] Could not watch %s: %s\n", directory.get_path(), e.message);
  227. }
  228. }
  229. private void watch_file(string path) {
  230. try {
  231. var monitor = File.new_for_path(path).monitor_file(FileMonitorFlags.NONE);
  232. monitor.changed.connect(() => schedule_rebuild());
  233. monitors += monitor;
  234. } catch (Error e) {
  235. stderr.printf("[spry] Could not watch %s: %s\n", path, e.message);
  236. }
  237. }
  238. /** Bundles rapid saves into a single rebuild. */
  239. private void schedule_rebuild() {
  240. if (debounce_source != 0) {
  241. Source.remove(debounce_source);
  242. }
  243. debounce_source = Timeout.add(DEBOUNCE_MS, () => {
  244. debounce_source = 0;
  245. rebuild();
  246. return false;
  247. });
  248. }
  249. // ------------------------------------------------------------------
  250. // Lifecycle
  251. // ------------------------------------------------------------------
  252. private void install_signal_handlers() {
  253. Unix.signal_add(ProcessSignal.INT, () => {
  254. shutdown();
  255. return false;
  256. });
  257. Unix.signal_add(ProcessSignal.TERM, () => {
  258. shutdown();
  259. return false;
  260. });
  261. }
  262. private void shutdown() {
  263. if (shutting_down) {
  264. return;
  265. }
  266. shutting_down = true;
  267. stdout.printf("\n[spry] Stopping %s\n", app_name);
  268. if (app_process != null) {
  269. ((!)app_process).send_signal(ProcessSignal.TERM);
  270. Timeout.add_seconds(KILL_GRACE_SECONDS, () => {
  271. if (app_process != null && !((!)app_process).get_if_exited()) {
  272. ((!)app_process).send_signal(ProcessSignal.KILL);
  273. }
  274. return false;
  275. });
  276. }
  277. Timeout.add(KILL_GRACE_SECONDS * 1000, () => {
  278. loop.quit();
  279. return false;
  280. });
  281. }
  282. private void step(string label) {
  283. stdout.printf("[spry] %s…\n", label);
  284. }
  285. }
  286. }