Safe Restarts

Safe Restarts with BGR (Bun Guard Restart)

Learn how to use BGR to automatically monitor and restart your Bun processes safely. This guide covers installation and usage of a simple guard script for seamless process management.

1#!/usr/bin/env bun
2/**
3 * Process Guard for BGR
4 * Monitors a process and automatically restarts it if it stops
5 * 
6 * Usage: bun guard.ts <process-name> [check-interval-seconds]
7 */
8
9import { $, sleep } from "bun";
10
11async function main() {
12  const processName = process.argv[2];
13  const checkInterval = parseInt(process.argv[3] || "30") * 1000;
14  
15  if (!processName) {
16    console.error("Error: Process name required");
17    console.error("Usage: bun guard.ts <process-name> [check-interval-seconds]");
18    process.exit(1);
19  }
20  
21  console.log(`Monitoring process "${processName}"`);
22  console.log(`Check interval: ${checkInterval/1000} seconds`);
23  
24  while (true) {
25    try {
26      const result = await $\`bgr ${processName}\`.quiet().nothrow();
27      
28      if (result.stdout.includes("○ Stopped") || result.exitCode !== 0) {
29        console.log(`Process "${processName}" is not running. Restarting...`);
30        
31        const restartResult = await $\`bgr ${processName} --restart --force\`.nothrow();
32        
33        if (restartResult.exitCode === 0) {
34          console.log(`Restarted "${processName}"`);
35        } else {
36          console.error(`Failed to restart "${processName}"`);
37          console.error(restartResult.stderr);
38        }
39      } else {
40        console.log(`Process "${processName}" is running (${new Date().toLocaleTimeString()})`);
41      }
42    } catch (error) {
43      console.error(`Error checking process: ${error.message}`);
44    }
45    
46    await sleep(checkInterval);
47  }
48}
49
50main().catch(err => {
51  console.error("Fatal error:", err);
52  process.exit(1);
53});
54