chore(tfstated): refactor database environment handling

This commit is contained in:
Julien Dessaux 2024-12-17 23:18:34 +01:00
parent 6cf2ca82de
commit c1ddc47c95
Signed by: adyxax
GPG key ID: F92E51B86E07177E
3 changed files with 32 additions and 43 deletions

View file

@ -10,7 +10,6 @@ import (
"net/http"
"os"
"os/signal"
"strconv"
"sync"
"time"
@ -36,22 +35,6 @@ func run(
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
defer cancel()
dataEncryptionKey := getenv("DATA_ENCRYPTION_KEY")
if dataEncryptionKey == "" {
return fmt.Errorf("the DATA_ENCRYPTION_KEY environment variable is not set")
}
if err := db.SetDataEncryptionKey(dataEncryptionKey); err != nil {
return err
}
versionsHistoryLimit := getenv("VERSIONS_HISTORY_LIMIT")
if versionsHistoryLimit != "" {
n, err := strconv.Atoi(versionsHistoryLimit)
if err != nil {
return fmt.Errorf("failed to parse the VERSIONS_HISTORY_LIMIT environment variable: %w", err)
}
db.SetVersionsHistoryLimit(n)
}
if err := db.InitAdminAccount(); err != nil {
return err
}
@ -107,7 +90,7 @@ func main() {
Port: "8080",
}
db, err := database.NewDB(ctx, "./tfstate.db?_txlock=immediate")
db, err := database.NewDB(ctx, "./tfstate.db?_txlock=immediate", os.Getenv)
if err != nil {
fmt.Fprintf(os.Stderr, "database init error: %+v\n", err)
os.Exit(1)

View file

@ -24,19 +24,10 @@ var adminPassword string
var adminPasswordMutex sync.Mutex
func TestMain(m *testing.M) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
config := Config{
Host: "127.0.0.1",
Port: "8081",
}
_ = os.Remove("./test.db")
var err error
db, err = database.NewDB(ctx, "./test.db")
if err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
getenv := func(key string) string {
switch key {
case "DATA_ENCRYPTION_KEY":
@ -48,6 +39,15 @@ func TestMain(m *testing.M) {
}
}
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
_ = os.Remove("./test.db")
var err error
db, err = database.NewDB(ctx, "./test.db", getenv)
if err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
database.AdvertiseAdminPassword = func(password string) {
adminPasswordMutex.Lock()
defer adminPasswordMutex.Unlock()
@ -125,14 +125,13 @@ func waitForReady(
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Error making request: %s\n", err.Error())
continue
} else {
_ = resp.Body.Close()
if resp.StatusCode == http.StatusOK {
fmt.Println("Endpoint is ready!")
return nil
}
}
if resp.StatusCode == http.StatusOK {
fmt.Println("Endpoint is ready!")
resp.Body.Close()
return nil
}
resp.Body.Close()
select {
case <-ctx.Done():