library/cmd/serve/main.go

156 lines
3.8 KiB
Go

package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"time"
"git.yetaga.in/alazyreader/library/config"
"git.yetaga.in/alazyreader/library/database"
"git.yetaga.in/alazyreader/library/frontend"
"git.yetaga.in/alazyreader/library/media"
"github.com/kelseyhightower/envconfig"
"golang.org/x/sync/errgroup"
"tailscale.com/tsnet"
"tailscale.com/util/must"
)
func obscureStr(in string, l int) string {
return in[0:max(l, len(in))] + strings.Repeat("*", max(0, len(in)-l))
}
type Library interface {
GetAllBooks(context.Context) ([]media.Book, error)
}
type RecordCollection interface {
GetAllRecords(context.Context) ([]media.Record, error)
}
func main() {
var c config.Config
must.Do(envconfig.Process("library", &c))
var lib Library
var err error
if c.DBType == "memory" {
lib = &database.Memory{}
} else if c.DBType == "sql" {
var latest, run int
lib, latest, run, err = setupSQL(c)
if err != nil {
log.Fatalf("err starting sql connection: %v", err)
}
log.Printf("latest migration: %d; migrations run: %d", latest, run)
}
discogsCache := must.Get(database.NewDiscogsCache(
c.DiscogsToken, time.Hour*24, c.DiscogsUser, c.DiscogsPersist, c.DiscogsCacheFile,
))
frontendRoot := must.Get(frontend.Root())
adminRoot := must.Get(frontend.AdminRoot())
servers := make(chan (*http.Server), 2)
errGroup := errgroup.Group{}
errGroup.Go(start(servers)(
publicServer(8080, &Router{
static: frontendRoot,
lib: lib,
rcol: discogsCache,
})))
errGroup.Go(start(servers)(
tailscaleListener("library-admin", &AdminRouter{
static: adminRoot,
lib: lib,
})))
errGroup.Go(shutdown(servers))
log.Println(errGroup.Wait())
}
func setupSQL(c config.Config) (Library, int, int, error) {
if c.DBUser == "" || c.DBPass == "" || c.DBHost == "" || c.DBPort == "" || c.DBName == "" {
if c.DBPass != "" {
c.DBPass = obscureStr(c.DBPass, 3)
}
if c.DiscogsToken != "" {
c.DiscogsToken = obscureStr(c.DiscogsToken, 3)
}
return nil, 0, 0, fmt.Errorf("invalid config; vars provided: %+v", c)
}
sql, err := database.NewMySQLConnection(c.DBUser, c.DBPass, c.DBHost, c.DBPort, c.DBName)
if err != nil {
return nil, 0, 0, err
}
err = sql.PrepareDatabase(context.Background())
if err != nil {
return nil, 0, 0, err
}
latest, run, err := sql.RunMigrations(context.Background())
if err != nil {
return nil, 0, 0, err
}
return sql, latest, run, nil
}
func errFunc(err error) func() error {
return func() error { return err }
}
func start(servers chan (*http.Server)) func(*http.Server, net.Listener, error) func() error {
return func(s *http.Server, l net.Listener, err error) func() error {
if err != nil {
return errFunc(err)
}
servers <- s
return errFunc(s.Serve(l))
}
}
func shutdown(servers chan (*http.Server)) func() error {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
<-sigint
close(servers)
for server := range servers {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
if err := server.Shutdown(ctx); err != nil {
log.Panicf("error during shutdown: %v", err)
}
cancel()
}
return errFunc(nil)
}
func publicServer(port int, handler http.Handler) (*http.Server, net.Listener, error) {
server := &http.Server{Handler: handler}
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", 8080))
if err != nil {
return nil, nil, err
}
return server, ln, nil
}
func tailscaleListener(hostname string, handler *AdminRouter) (*http.Server, net.Listener, error) {
s := &tsnet.Server{
Dir: ".config/" + hostname,
Hostname: hostname,
}
ln, err := s.Listen("tcp", ":80")
if err != nil {
return nil, nil, err
}
handler.ts, err = s.LocalClient()
if err != nil {
return nil, nil, err
}
server := &http.Server{Handler: handler}
return server, ln, nil
}