103 lines
2.4 KiB
Go
103 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"brunel/buildqueue"
|
|
"brunel/config"
|
|
handlers_auth "brunel/handlers/auth"
|
|
handlers_build "brunel/handlers/build"
|
|
handlers_packages "brunel/handlers/packages"
|
|
"brunel/helpers"
|
|
"brunel/middleware"
|
|
"brunel/packages"
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/goccy/go-json"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/fiber/v2/middleware/compress"
|
|
"github.com/gofiber/fiber/v2/middleware/recover"
|
|
"github.com/maypok86/otter"
|
|
slogfiber "github.com/samber/slog-fiber"
|
|
)
|
|
|
|
// runServer runs a new HTTP server with the loaded environment variables.
|
|
func runServer(ctx context.Context) error {
|
|
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
|
|
var err error
|
|
|
|
ott := otter.MustBuilder[string, any](10000)
|
|
ott.WithTTL(time.Hour * 24)
|
|
helpers.Cache, err = ott.Build()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
err = config.Init()
|
|
if err != nil {
|
|
slog.Error("unable to load configuration: " + err.Error())
|
|
return err
|
|
}
|
|
|
|
go func() {
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
default:
|
|
err := helpers.DBInst.DeleteExpiredSessions()
|
|
if err != nil {
|
|
slog.Error("unable to delete expired sessions: " + err.Error())
|
|
}
|
|
time.Sleep(time.Minute)
|
|
}
|
|
}
|
|
}()
|
|
|
|
start := time.Now()
|
|
err = packages.LoadFromDb()
|
|
if err != nil {
|
|
slog.Error("unable to load packages from db: " + err.Error())
|
|
return err
|
|
}
|
|
slog.Info("packages loaded in " + time.Since(start).String())
|
|
|
|
buildqueue.StartPackageQueueWorker(ctx)
|
|
buildqueue.StartQueueAndStatusWorker(ctx)
|
|
|
|
cfg := fiber.Config{
|
|
JSONEncoder: json.Marshal,
|
|
JSONDecoder: json.Unmarshal,
|
|
ReadTimeout: 5 * time.Second,
|
|
WriteTimeout: 10 * time.Second,
|
|
AppName: "brunel",
|
|
Prefork: false,
|
|
}
|
|
|
|
server := fiber.New(cfg)
|
|
|
|
server.Use(slogfiber.NewWithConfig(logger, slogfiber.Config{
|
|
WithSpanID: true,
|
|
WithTraceID: true,
|
|
}))
|
|
server.Use(recover.New())
|
|
server.Use(compress.New(compress.Config{
|
|
Level: compress.LevelBestSpeed,
|
|
}))
|
|
|
|
adminRoutes := server.Group("api/admin")
|
|
adminRoutes.Use(middleware.NewAuth())
|
|
|
|
server.Get("/api/counts", handlers_packages.Counts)
|
|
server.Get("/api/packages", handlers_packages.Packages)
|
|
server.Get("/api/queue", handlers_build.Queue)
|
|
|
|
server.Post("/api/login", handlers_auth.Login)
|
|
adminRoutes.Post("/register", handlers_auth.Register)
|
|
adminRoutes.Post("/updatePassword", handlers_auth.UpdatePassword)
|
|
|
|
return server.Listen(fmt.Sprintf("localhost:%d", config.Configs.Port))
|
|
}
|