▍ humdrum codex / custard v0.3.0
license AGPL-3.0
1.2 KB 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
// Package cli implements custard's subcommands: the long-running forge server
// (serve) and the local client verbs (check/preview/promote/release).
package cli

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"custard/internal/config"
	"custard/internal/server"
)

// Serve runs the forge HTTP server until interrupted, then drains in-flight
// requests. This is what the droplet runs (via systemd).
func Serve(args []string) {
	cfg := config.Load(args)
	srv, err := server.New(cfg)
	if err != nil {
		log.Fatalf("init: %v", err)
	}

	httpSrv := &http.Server{
		Addr:              cfg.ListenAddr,
		Handler:           srv.Handler(),
		ReadHeaderTimeout: 10 * time.Second,
	}

	go func() {
		log.Printf("custard listening on %s (repos: %s)", cfg.ListenAddr, cfg.ReposPath)
		if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("server error: %v", err)
		}
	}()

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
	<-stop

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := httpSrv.Shutdown(ctx); err != nil {
		log.Printf("shutdown error: %v", err)
	}
	log.Println("custard stopped")
}