-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
191 lines (164 loc) · 4.52 KB
/
Copy pathmain.go
File metadata and controls
191 lines (164 loc) · 4.52 KB
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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
// version is injected at build time via -ldflags "-X main.version=...".
var version = "dev"
func main() {
healthcheck := flag.Bool("healthcheck", false, "run a quick health probe and exit")
schema := flag.Bool("schema", false, "generate a openapi.json file and exit")
flag.Parse()
if *schema {
if err := writeSchemaFile("openapi.json"); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
os.Exit(0)
}
cfg, err := LoadConfig()
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
logger := newLogger(cfg.LogLevel)
if *healthcheck {
url, err := healthcheckURL(cfg.ListenAddr)
if err == nil {
err = doHealthcheck(url)
}
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
os.Exit(0)
}
db, err := OpenDB(cfg.SQLitePath)
if err != nil {
logger.Error("db open failed", slog.String("err", err.Error()))
os.Exit(1)
}
defer func() { _ = db.Close() }()
client := NewTranslationClient(cfg)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Ready = can serve: data from a previous run counts, even if the
// upstream is currently unreachable. A pull success also sets it.
ready := &ReadyState{}
hasData, err := db.HasStrings(ctx)
if err != nil {
logger.Error("readiness check failed", slog.String("err", err.Error()))
os.Exit(1)
}
ready.SetReady(hasData)
srv := &Server{db: db, ready: ready, logger: logger}
logger.Info("cacheppuccino starting",
slog.String("version", version),
slog.String("addr", cfg.ListenAddr),
slog.Bool("has_data", hasData),
slog.String("pull_interval", cfg.PullInterval.String()),
slog.String("http_timeout", cfg.HTTPTimeout.String()),
slog.String("initial_pull_deadline", cfg.InitialPullDeadline.String()),
)
// No BaseContext: request contexts must outlive the shutdown signal
// so Shutdown can drain in-flight requests instead of aborting them.
httpServer := &http.Server{
Addr: cfg.ListenAddr,
Handler: srv.routes(),
ReadTimeout: 10 * time.Second,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
go func() {
logger.Info("http server starting", slog.String("addr", cfg.ListenAddr))
err := httpServer.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
logger.Error("http server failed", slog.String("err", err.Error()))
stop()
}
}()
StartPeriodicPuller(
ctx,
db,
client,
cfg.PullInterval,
cfg.InitialPullDeadline,
cfg.TranslationApplicationID,
ready,
logger,
)
<-ctx.Done()
logger.Info("shutdown signal received")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
logger.Error("http shutdown failed", slog.String("err", err.Error()))
} else {
logger.Info("http server stopped")
}
}
func writeSchemaFile(path string) error {
spec, err := buildOpenAPISpec("/")
if err != nil {
return err
}
data, err := json.MarshalIndent(spec, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}
func newLogger(level string) *slog.Logger {
var lvl slog.Level
switch level {
case "debug":
lvl = slog.LevelDebug
case "warn":
lvl = slog.LevelWarn
case "error":
lvl = slog.LevelError
default:
lvl = slog.LevelInfo
}
h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: lvl})
return slog.New(h)
}
// healthcheckURL derives the probe URL from LISTEN_ADDR. The probe runs
// inside the same container as the server (the distroless image has no
// curl, so the binary probes itself): wildcard binds (":8080",
// "0.0.0.0:8080", "[::]:8080") are reachable via loopback, while an
// explicit bind host must be probed directly.
func healthcheckURL(listenAddr string) (string, error) {
host, port, err := net.SplitHostPort(listenAddr)
if err != nil {
return "", fmt.Errorf("invalid LISTEN_ADDR %q: %w", listenAddr, err)
}
switch host {
case "", "0.0.0.0", "::":
host = "127.0.0.1"
}
return "http://" + net.JoinHostPort(host, port) + "/healthz", nil
}
func doHealthcheck(url string) error {
c := &http.Client{Timeout: 2 * time.Second}
resp, err := c.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
return fmt.Errorf("healthcheck failed: %s", resp.Status)
}
return nil
}