-
Notifications
You must be signed in to change notification settings - Fork 86
/
service.go
191 lines (164 loc) · 4.64 KB
/
service.go
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"
"embed"
"errors"
"io/fs"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/bluesky-social/indigo/atproto/identity"
"github.com/bluesky-social/indigo/atproto/syntax"
"github.com/bluesky-social/indigo/util"
"github.com/bluesky-social/indigo/xrpc"
"github.com/flosch/pongo2/v6"
"github.com/labstack/echo-contrib/echoprometheus"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
slogecho "github.com/samber/slog-echo"
"github.com/urfave/cli/v2"
)
//go:embed static/*
var StaticFS embed.FS
type Server struct {
echo *echo.Echo
httpd *http.Server
dir identity.Directory // TODO: unused?
xrpcc *xrpc.Client
defaultHandle syntax.Handle
}
func serve(cctx *cli.Context) error {
debug := cctx.Bool("debug")
httpAddress := cctx.String("bind")
appviewHost := cctx.String("appview-host")
dh, err := syntax.ParseHandle("atproto.com")
if err != nil {
return err
}
xrpcc := &xrpc.Client{
Client: util.RobustHTTPClient(),
Host: appviewHost,
// Headers: version
}
e := echo.New()
// httpd
var (
httpTimeout = 1 * time.Minute
httpMaxHeaderBytes = 1 * (1024 * 1024)
)
srv := &Server{
echo: e,
xrpcc: xrpcc,
dir: identity.DefaultDirectory(),
defaultHandle: dh,
}
srv.httpd = &http.Server{
Handler: srv,
Addr: httpAddress,
WriteTimeout: httpTimeout,
ReadTimeout: httpTimeout,
MaxHeaderBytes: httpMaxHeaderBytes,
}
e.HideBanner = true
e.Use(slogecho.New(slog))
e.Use(middleware.Recover())
e.Use(echoprometheus.NewMiddleware("athome"))
e.Use(middleware.BodyLimit("64M"))
e.HTTPErrorHandler = srv.errorHandler
e.Renderer = NewRenderer("templates/", &TemplateFS, debug)
e.Use(middleware.SecureWithConfig(middleware.SecureConfig{
ContentTypeNosniff: "nosniff",
XFrameOptions: "SAMEORIGIN",
HSTSMaxAge: 31536000, // 365 days
// TODO:
// ContentSecurityPolicy
// XSSProtection
}))
// redirect trailing slash to non-trailing slash.
// all of our current endpoints have no trailing slash.
e.Use(middleware.RemoveTrailingSlashWithConfig(middleware.TrailingSlashConfig{
RedirectCode: http.StatusFound,
}))
staticHandler := http.FileServer(func() http.FileSystem {
if debug {
return http.FS(os.DirFS("static"))
}
fsys, err := fs.Sub(StaticFS, "static")
if err != nil {
slog.Error("static template error", "err", err)
os.Exit(-1)
}
return http.FS(fsys)
}())
e.GET("/static/*", echo.WrapHandler(http.StripPrefix("/static/", staticHandler)))
e.GET("/_health", srv.HandleHealthCheck)
e.GET("/metrics", echoprometheus.NewHandler())
// basic static routes
e.GET("/robots.txt", echo.WrapHandler(staticHandler))
e.GET("/favicon.ico", echo.WrapHandler(staticHandler))
// actual content
e.GET("/", srv.WebHome)
e.GET("/bsky", srv.WebProfile)
e.GET("/bsky/post/:rkey", srv.WebPost)
e.GET("/bsky/repo.car", srv.WebRepoCar)
e.GET("/bsky/rss.xml", srv.WebRepoRSS)
// Start the server
slog.Info("starting server", "bind", httpAddress)
go func() {
if err := srv.httpd.ListenAndServe(); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
slog.Error("HTTP server shutting down unexpectedly", "err", err)
}
}
}()
// Wait for a signal to exit.
slog.Info("registering OS exit signal handler")
quit := make(chan struct{})
exitSignals := make(chan os.Signal, 1)
signal.Notify(exitSignals, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-exitSignals
slog.Info("received OS exit signal", "signal", sig)
// Shut down the HTTP server
if err := srv.Shutdown(); err != nil {
slog.Error("HTTP server shutdown error", "err", err)
}
// Trigger the return that causes an exit.
close(quit)
}()
<-quit
slog.Info("graceful shutdown complete")
return nil
}
type GenericStatus struct {
Daemon string `json:"daemon"`
Status string `json:"status"`
Message string `json:"msg,omitempty"`
}
func (srv *Server) errorHandler(err error, c echo.Context) {
code := http.StatusInternalServerError
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
}
if code >= 500 {
slog.Warn("athome-http-internal-error", "err", err)
}
data := pongo2.Context{
"statusCode": code,
}
c.Render(code, "error.html", data)
}
func (srv *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
srv.echo.ServeHTTP(rw, req)
}
func (srv *Server) Shutdown() error {
slog.Info("shutting down")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return srv.httpd.Shutdown(ctx)
}
func (s *Server) HandleHealthCheck(c echo.Context) error {
return c.JSON(200, GenericStatus{Status: "ok", Daemon: "athome"})
}