Dev.vala 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. if (no_run) {
  67. return 0;
  68. }
  69. dev.loop = new MainLoop();
  70. dev.watch_sources();
  71. dev.install_signal_handlers();
  72. dev.spawn_child();
  73. dev.loop.run();
  74. return 0;
  75. }
  76. // ------------------------------------------------------------------
  77. // Build / run / restart
  78. // ------------------------------------------------------------------
  79. /** Deletes the application's SQLite store (honouring SPRY_DB_PATH). */
  80. private void reset_database() {
  81. var configured = Environment.get_variable("SPRY_DB_PATH");
  82. var path = configured != null && configured.length > 0
  83. ? configured
  84. : app_name + ".sqlite";
  85. if (FileUtils.test(path, FileTest.EXISTS)) {
  86. FileUtils.remove(path);
  87. stdout.printf("[spry] Deleted %s\n", path);
  88. }
  89. }
  90. /** Incrementally builds; returns true on success. */
  91. private bool build() throws Error {
  92. return spawn_sync({ "ninja", "-C", "builddir" });
  93. }
  94. /**
  95. * Runs a short-lived child that inherits this process's stdio,
  96. * with the stack's library environment applied.
  97. */
  98. private bool spawn_sync(string[] argv) throws Error {
  99. var process = launcher.spawnv(argv);
  100. try {
  101. process.wait_check();
  102. return true;
  103. } catch (Error e) {
  104. return false;
  105. }
  106. }
  107. private void spawn_child() {
  108. try {
  109. expect_exit = false;
  110. app_process = launcher.spawnv({ binary_path, port.to_string() });
  111. stdout.printf("[spry] Running %s on port %d (Ctrl-C to stop)\n", app_name, port);
  112. watch_child.begin();
  113. } catch (Error e) {
  114. stderr.printf("[spry] Could not run %s: %s\n", binary_path, e.message);
  115. }
  116. }
  117. /**
  118. * The single lifecycle waiter for the running child: on an expected
  119. * exit (restart) it spawns the replacement; on an unexpected exit it
  120. * reports and leaves the loop watching for the next successful
  121. * rebuild.
  122. */
  123. private async void watch_child() {
  124. var process = app_process;
  125. if (process == null) {
  126. return;
  127. }
  128. try {
  129. yield ((!)process).wait_async(null);
  130. } catch (Error e) {
  131. }
  132. if (shutting_down) {
  133. return;
  134. }
  135. if (expect_exit) {
  136. spawn_child();
  137. } else {
  138. app_process = null;
  139. stdout.printf("[spry] %s exited — save a file to rebuild, or Ctrl-C to quit\n", app_name);
  140. }
  141. }
  142. /** Rebuilds and, on success, replaces the running child. */
  143. private void rebuild() {
  144. if (shutting_down) {
  145. return;
  146. }
  147. step("Rebuilding");
  148. try {
  149. if (!build()) {
  150. stdout.printf("[spry] Build failed — %s is still running\n", app_name);
  151. return;
  152. }
  153. } catch (Error e) {
  154. stderr.printf("[spry] Build could not run: %s\n", e.message);
  155. return;
  156. }
  157. restart_child();
  158. }
  159. /**
  160. * Stops the running child (SIGTERM, escalating to SIGKILL after the
  161. * grace period); the lifecycle waiter spawns the replacement once it
  162. * observes the exit. When no child is running the replacement starts
  163. * immediately.
  164. */
  165. private void restart_child() {
  166. var process = app_process;
  167. if (process == null) {
  168. spawn_child();
  169. return;
  170. }
  171. expect_exit = true;
  172. ((!)process).send_signal(ProcessSignal.TERM);
  173. Timeout.add_seconds(KILL_GRACE_SECONDS, () => {
  174. if (!shutting_down && app_process == process && !((!)process).get_if_exited()) {
  175. stdout.printf("[spry] %s did not exit — killing it\n", app_name);
  176. ((!)process).send_signal(ProcessSignal.KILL);
  177. }
  178. return false;
  179. });
  180. }
  181. // ------------------------------------------------------------------
  182. // Watching
  183. // ------------------------------------------------------------------
  184. /** Watches the application's sources for changes. */
  185. private void watch_sources() throws Error {
  186. watch_tree(File.new_for_path(Path.build_filename(app_dir, "src")));
  187. watch_file(Path.build_filename(app_dir, "meson.build"));
  188. watch_file(Path.build_filename(app_dir, "web-config.json"));
  189. }
  190. private void watch_tree(File directory) {
  191. watch_directory(directory);
  192. try {
  193. var enumerator = directory.enumerate_children("standard::name,standard::type",
  194. FileQueryInfoFlags.NONE);
  195. FileInfo info;
  196. while ((info = enumerator.next_file()) != null) {
  197. if (info.get_file_type() == FileType.DIRECTORY) {
  198. watch_tree(File.new_for_path(
  199. Path.build_filename((!) directory.get_path(), info.get_name())));
  200. }
  201. }
  202. } catch (Error e) {
  203. stderr.printf("[spry] Could not enumerate %s: %s\n", directory.get_path(), e.message);
  204. }
  205. }
  206. /**
  207. * Attaches a directory monitor; newly created subdirectories are
  208. * picked up as well, so `spry add` output is watched without a
  209. * restart.
  210. */
  211. private void watch_directory(File directory) {
  212. try {
  213. var monitor = directory.monitor_directory(FileMonitorFlags.NONE);
  214. monitor.changed.connect((file, other, event) => {
  215. if (event == FileMonitorEvent.CREATED && file.query_file_type(FileQueryInfoFlags.NONE) == FileType.DIRECTORY) {
  216. watch_tree(file);
  217. }
  218. if (event != FileMonitorEvent.CHANGES_DONE_HINT) {
  219. schedule_rebuild();
  220. }
  221. });
  222. monitors += monitor;
  223. } catch (Error e) {
  224. stderr.printf("[spry] Could not watch %s: %s\n", directory.get_path(), e.message);
  225. }
  226. }
  227. private void watch_file(string path) {
  228. try {
  229. var monitor = File.new_for_path(path).monitor_file(FileMonitorFlags.NONE);
  230. monitor.changed.connect(() => schedule_rebuild());
  231. monitors += monitor;
  232. } catch (Error e) {
  233. stderr.printf("[spry] Could not watch %s: %s\n", path, e.message);
  234. }
  235. }
  236. /** Bundles rapid saves into a single rebuild. */
  237. private void schedule_rebuild() {
  238. if (debounce_source != 0) {
  239. Source.remove(debounce_source);
  240. }
  241. debounce_source = Timeout.add(DEBOUNCE_MS, () => {
  242. debounce_source = 0;
  243. rebuild();
  244. return false;
  245. });
  246. }
  247. // ------------------------------------------------------------------
  248. // Lifecycle
  249. // ------------------------------------------------------------------
  250. private void install_signal_handlers() {
  251. Unix.signal_add(ProcessSignal.INT, () => {
  252. shutdown();
  253. return false;
  254. });
  255. Unix.signal_add(ProcessSignal.TERM, () => {
  256. shutdown();
  257. return false;
  258. });
  259. }
  260. private void shutdown() {
  261. if (shutting_down) {
  262. return;
  263. }
  264. shutting_down = true;
  265. stdout.printf("\n[spry] Stopping %s\n", app_name);
  266. if (app_process != null) {
  267. ((!)app_process).send_signal(ProcessSignal.TERM);
  268. Timeout.add_seconds(KILL_GRACE_SECONDS, () => {
  269. if (app_process != null && !((!)app_process).get_if_exited()) {
  270. ((!)app_process).send_signal(ProcessSignal.KILL);
  271. }
  272. return false;
  273. });
  274. }
  275. Timeout.add(KILL_GRACE_SECONDS * 1000, () => {
  276. loop.quit();
  277. return false;
  278. });
  279. }
  280. private void step(string label) {
  281. stdout.printf("[spry] %s…\n", label);
  282. }
  283. }
  284. }