micw/server/setup.go

101 lines
2.5 KiB
Go
Raw Permalink Normal View History

2024-11-13 21:10:13 +00:00
package server
import (
"context"
"database/sql"
"fmt"
commonUtils "git.mic.pp.ua/anderson/nettools/common"
dbUtils "git.mic.pp.ua/anderson/nettools/db"
"github.com/golang-migrate/migrate/v4/database/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/matchsystems/werr"
"log"
"mic-wallet/server/repository"
"net"
"net/http"
"time"
)
func (s *Server) Setup(ctx context.Context) error {
2024-11-17 21:24:19 +00:00
// ================================
// Set up the transactions pipeline
2024-11-13 21:10:13 +00:00
// ===================
// Setting up database
var db *sql.DB
var err error
success, errs := commonUtils.Retry(ctx, 5, time.Second*1, func(_ context.Context) error {
db, err = sql.Open("pgx", s.Cfg.DbConnUrl)
if err != nil {
return err
}
return db.Ping()
})
if !success {
return werr.Wrapf(errs[0], "failed to connect to database")
}
log.Println("Applying database migrations")
ver, dirty, err := dbUtils.DoMigrate(dbUtils.MigrationConfig[*pgx.Config]{
MigrationsPath: "./migrations",
DB: db,
VersionLimit: -1,
Drop: false,
DriverCfg: &pgx.Config{
MigrationsTable: "migrations",
SchemaName: "public",
},
}, dbUtils.NewMigratePgxInstance)
if err != nil {
return werr.Wrapf(err, "failed to apply database migrations")
}
log.Println("Database migrations applied")
log.Println("\tVersion: ", ver)
log.Println("\tDirty: ", dirty)
if err = db.Close(); err != nil {
return werr.Wrapf(err, "failed to close database connection")
}
s.DB, err = pgxpool.New(ctx, s.Cfg.DbConnUrl)
if err != nil {
return werr.Wrapf(err, "failed to create new pgxpool")
}
// ========================
// Internals initialization
s.Repo = repository.NewRepository(s.DB)
// TODO:
// ======================
// Creating net listeners
if s.Cfg.HttpPort > 0 || s.Cfg.HttpsPort > 0 {
s.Mux = http.NewServeMux()
}
if s.Cfg.HttpPort > 0 {
addr := fmt.Sprintf("%s:%d", s.Cfg.Addr, s.Cfg.HttpPort)
s.HttpListener, err = net.Listen("tcp", addr)
if err != nil {
2024-11-17 21:24:19 +00:00
return werr.Wrapf(err, "failed to listen http_api_entities on address %s", addr)
2024-11-13 21:10:13 +00:00
}
}
if s.Cfg.HttpsPort > 0 {
addr := fmt.Sprintf("%s:%d", s.Cfg.Addr, s.Cfg.HttpsPort)
s.HttpListener, err = net.Listen("tcp", addr)
if err != nil {
return werr.Wrapf(err, "failed to listen https on address %s", addr)
}
}
if s.Cfg.GrpcPort > 0 {
addr := fmt.Sprintf("%s:%d", s.Cfg.Addr, s.Cfg.GrpcPort)
s.GrpcListener, err = net.Listen("tcp", addr)
if err != nil {
return werr.Wrapf(err, "failed to listen grpc on address %s", addr)
}
}
return nil
}