cmd/dev/main.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | package main import ( "context" "fmt" "io" "io/fs" "log" "log/slog" "net/http" "net/http/httputil" "os" "os/exec" "os/signal" "path" "path/filepath" "strings" "sync" "syscall" "time" "website/internal/config" "github.com/antage/eventsource" "github.com/ardanlabs/conf/v3" "github.com/gohugoio/hugo/watcher" "github.com/pkg/errors" ) type DevConfig struct { Source string `conf:"default:.,short:s"` TempDir string `conf:"required,short:t"` BaseURL config.URL `conf:"default:http://localhost:3000"` ServerURL config.URL `conf:"default:http://localhost:3001"` } func RunCommandPiped( ctx context.Context, command string, args ...string, ) (cmd *exec.Cmd, err error) { slog.Debug(fmt.Sprintf("running command %s %s", command, strings.Join(args, " "))) cmd = exec.CommandContext(ctx, command, args...) cmd.Env = append(os.Environ(), "DEBUG=") cmd.Cancel = func() error { slog.Debug("signalling child") err := cmd.Process.Signal(os.Interrupt) if err != nil { slog.Error(fmt.Sprintf("signal error: %v", err)) } return err } stdout, err := cmd.StdoutPipe() if err != nil { return } stderr, err := cmd.StderrPipe() if err != nil { return } go io.Copy(os.Stdout, stdout) go io.Copy(os.Stderr, stderr) return } type FileWatcher struct { *watcher.Batcher } func NewFileWatcher(pollTime time.Duration) (*FileWatcher, error) { batcher, err := watcher.New(pollTime/5, pollTime, true) if err != nil { return nil, err } return &FileWatcher{batcher}, nil } func (watcher FileWatcher) WatchAllFiles(from string) error { slog.Debug(fmt.Sprintf("watching files under %s", from)) err := filepath.Walk(from, func(path string, info fs.FileInfo, err error) error { if err != nil { return err } // slog.Debug(fmt.Sprintf("adding file %s to watcher", path)) if err = watcher.Add(path); err != nil { return err } return nil }) return err } func build(ctx context.Context, config DevConfig) error { buildExe := filepath.Join(config.TempDir, "build") cmd, err := RunCommandPiped(ctx, buildExe, "--dest", path.Join(config.TempDir, "output"), "--dev", ) // cmd, err := RunCommandPiped(ctx, "./devfakebuild") if err != nil { return errors.WithMessage(err, "error running build command") } err = cmd.Run() slog.Debug(fmt.Sprintf("build command exited with code %d", cmd.ProcessState.ExitCode())) if err != nil { return errors.WithMessage(err, "error running build command") } return nil } func server(ctx context.Context, devConfig DevConfig) error { serverExe := path.Join(devConfig.TempDir, "server") cmd, err := RunCommandPiped(ctx, serverExe, "--port", devConfig.ServerURL.Port(), "--root", path.Join(devConfig.TempDir, "output"), "--in-dev-server", ) if err != nil { return errors.WithMessage(err, "error running server command") } // cmd.Env = append(cmd.Env, "DEBUG=1") cmdErr := make(chan error, 1) done := make(chan struct{}) err = cmd.Start() if err != nil { return errors.WithMessage(err, "error starting server binary") } go func() { err := cmd.Wait() if err == nil && cmd.ProcessState.Exited() { err = errors.Errorf("server exited unexpectedly") } cmdErr <- err close(done) }() for { select { case <-ctx.Done(): slog.Debug("server context done") err := cmd.Process.Signal(os.Interrupt) if err != nil { return err } <-done case err := <-cmdErr: return err } } } func main() { if os.Getenv("DEBUG") != "" { slog.SetLogLoggerLevel(slog.LevelDebug) } var wg sync.WaitGroup devConfig := DevConfig{} help, err := conf.Parse("", &devConfig) if err != nil { if errors.Is(err, conf.ErrHelpWanted) { fmt.Println(help) os.Exit(1) } log.Panicf("parsing dev configuration: %v", err) } slog.Debug(fmt.Sprintf("using folder %s for build output", devConfig.TempDir)) ctx, cancel := context.WithCancel(context.Background()) defer cancel() slog.Debug("setting interrupt handler") c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { sig := <-c slog.Info(fmt.Sprintf("shutting down on signal %d", sig)) cancel() sig = <-c slog.Info(fmt.Sprintf("got second signal, dying %d", sig)) os.Exit(1) }() serverChan := make(chan bool, 1) eventsource := eventsource.New(nil, nil) defer eventsource.Close() srv := http.Server{ Addr: devConfig.BaseURL.Host, } devCtx, devCancel := context.WithTimeout(ctx, 1*time.Second) wg.Add(1) go func() { defer wg.Done() defer devCancel() slog.Debug("waiting for first server launch") <-serverChan slog.Debug("got first server launch event") http.Handle("/", &httputil.ReverseProxy{ Rewrite: func(req *httputil.ProxyRequest) { req.SetURL(devConfig.ServerURL.URL) req.Out.Host = req.In.Host }, }) http.Handle("/_/reload", eventsource) done := make(chan bool) go func() { err := srv.ListenAndServe() if err != nil && err != http.ErrServerClosed { slog.Error(err.Error()) cancel() } done <- true }() go func() { for ready := range serverChan { if ready { slog.Debug("sending reload message") eventsource.SendEventMessage("reload", "", "") } else { slog.Debug("server not ready") } } }() slog.Info(fmt.Sprintf("dev server listening on %s", devConfig.BaseURL.Host)) <-done slog.Debug("dev server closed") }() fw, err := NewFileWatcher(500 * time.Millisecond) if err != nil { log.Fatalf("error creating file watcher: %v", err) } err = fw.WatchAllFiles("content") if err != nil { log.Fatalf("could not watch files in content directory: %v", err) } err = fw.WatchAllFiles("templates") if err != nil { log.Fatalf("could not watch files in templates directory: %v", err) } var exitCode int serverErr := make(chan error, 1) loop: for { serverCtx, stopServer := context.WithCancel(ctx) slog.Debug("starting build") err := build(ctx, devConfig) if err != nil { slog.Error(fmt.Sprintf("build error: %v", err)) // don't set up the server until there's a FS change event } else { slog.Debug("setting up server") wg.Add(1) go func() { defer wg.Done() serverChan <- true serverErr <- server(serverCtx, devConfig) }() } select { case <-ctx.Done(): slog.Debug("main context cancelled") slog.Debug("calling server shutdown") err := srv.Shutdown(devCtx) if err != nil { slog.Debug("shutdown error", "error", err) } exitCode = 1 break loop case event := <-fw.Events: slog.Debug(fmt.Sprintf("event received: %v", event)) stopServer() serverChan <- false slog.Debug("waiting for server shutdown") <-serverErr slog.Debug("server shutdown completed") continue case err = <-serverErr: if err != nil && err != context.Canceled { var exerr *exec.ExitError slog.Error(fmt.Sprintf("server reported error: %v", err)) if errors.As(err, &exerr) { slog.Debug("server exit error") } else { slog.Debug("server other error") } break } slog.Debug("no error or server context cancelled") continue } slog.Debug("waiting on server") exitCode = 0 break } slog.Debug("waiting for wg before shutting down") wg.Wait() os.Exit(exitCode) } |