// Package appboot starts an app Base installs. Every such app boots the same // way: read the BASE_APP_* settings, open and migrate its database, build its // router, and serve it with rastrillo. Only the inputs in App differ. package appboot import ( "context" "errors" "log/slog" "net/http" "os" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/db" _ "amadan.net/rastrillo/rastrillo/locales/en" "amadan.net/rastrillo/rastrillo/migrate" "amadan.net/oficina/base/internal/consumer" ) // App is what one installed app brings to the boot. type App struct { Name string // for log lines, such as "scratchpad" DBFile string // the database file name when the platform passes no -db Schema *migrate.Set // everything the app's database needs // Build returns the app's router. d has Schema applied, and cfg.Logger // is set. Build func(d *db.DB, cfg consumer.Config, logger *slog.Logger) (http.Handler, error) } // Main runs app with the process's environment and exits 1 if it cannot // start. func Main(app App) { logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) if err := Run(app, os.Getenv, logger); err != nil { logger.Error(app.Name+" failed to start", "err", err) os.Exit(1) } } // Run reads the settings with getenv, opens and migrates the database, // builds the app and serves it until rastrillo stops. The database is // closed whenever Run returns. func Run(app App, getenv func(string) string, logger *slog.Logger) error { if app.Name == "" || app.DBFile == "" || app.Schema == nil || app.Build == nil { return errors.New("appboot: an App needs a Name, DBFile, Schema and Build") } cfg, err := consumer.Load(getenv) if err != nil { return err } opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: app.DBFile, Logger: logger}) if err != nil { return err } handler, closeDB, err := open(app, cfg, opts.DBPath, logger) if err != nil { return err } defer closeDB() // rastrillo.Serve wants a *http.ServeMux; the app's router takes every path. mux := http.NewServeMux() mux.Handle("/", handler) opts.Mux = mux opts.DBPath = "" // the database is already open return rastrillo.Serve(opts) } // open opens and migrates the database at path and builds the app on it. On // any error the database is already closed. func open(app App, cfg consumer.Config, path string, logger *slog.Logger) (http.Handler, func() error, error) { d, err := db.Open(path, logger) if err != nil { return nil, nil, err } if _, err := migrate.Apply(context.Background(), d, app.Schema); err != nil { d.Close() return nil, nil, err } cfg.Logger = logger handler, err := app.Build(d, cfg, logger) if err != nil { d.Close() return nil, nil, err } return handler, d.Close, nil }