Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions account.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package staticbackend

import (
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
Expand All @@ -11,7 +12,6 @@ import (
"github.com/staticbackendhq/core/config"
emailFuncs "github.com/staticbackendhq/core/email"
"github.com/staticbackendhq/core/internal"
"github.com/staticbackendhq/core/logger"
"github.com/staticbackendhq/core/middleware"
"github.com/staticbackendhq/core/model"

Expand All @@ -23,7 +23,6 @@ import (
)

type accounts struct {
log *logger.Logger
}

func (a *accounts) create(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -192,7 +191,7 @@ func (a *accounts) create(w http.ResponseWriter, r *http.Request) {
// "safe-to-use-in-dev-root-token" as root token instead of
// the changing one across CLI start/stop
if err := backend.Cache.Set("dev-root-token", rootToken); err != nil {
backend.Log.Error().Err(err)
slog.Error(err.Error())
}
}

Expand Down Expand Up @@ -221,7 +220,7 @@ Refer to the documentation at https://staticbackend.dev/docs
} else if !bypassStripe {
err = backend.Emailer.Send(ed)
if err != nil {
a.log.Error().Err(err).Msg("error sending email")
slog.Error("error sending email", "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -250,7 +249,7 @@ Refer to the documentation at https://staticbackend.dev/docs
return
}

render(w, r, "login.html", nil, &Flash{Type: "sucess", Message: "We've emailed you all the information you need to get started."}, a.log)
render(w, r, "login.html", nil, &Flash{Type: "sucess", Message: "We've emailed you all the information you need to get started."})
}

func (a *accounts) addDatabase(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -280,7 +279,12 @@ func (a *accounts) addDatabase(w http.ResponseWriter, r *http.Request) {
if len(config.Current.StripeKey) > 0 && len(cust.SubscriptionID) > 0 {
curSub, err := subscription.Get(cust.SubscriptionID, nil)
if err != nil {
a.log.Err(err).Msgf("trying to get stripe cust %s sub %s", cust.StripeID, cust.SubscriptionID)
slog.Error(
"trying to get stripe customer subscription",
"stripe_customer_id", cust.StripeID,
"subscription_id", cust.SubscriptionID,
"error", err,
)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
Expand All @@ -302,7 +306,12 @@ func (a *accounts) addDatabase(w http.ResponseWriter, r *http.Request) {
}

if _, err := subscription.Update(cust.SubscriptionID, params); err != nil {
a.log.Err(err).Msgf("unable to update stripe cust %s sub %s quantity", cust.ID, cust.SubscriptionID)
slog.Error(
"unable to update stripe customer subscription quantity",
"tenant_id", cust.ID,
"subscription_id", cust.SubscriptionID,
"error", err,
)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down
53 changes: 24 additions & 29 deletions backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
// - [Filestore]: raw blob storage
// - [Emailer]: to send emails
// - [Config]: the config that was passed to [Setup]
// - [Log]: logger
//
// You may see those services as raw building blocks that give you the most
// flexibility to build on top.
Expand Down Expand Up @@ -118,6 +117,7 @@ import (
"database/sql"
"errors"
"fmt"
"log/slog"
"os"
"strings"
"sync"
Expand Down Expand Up @@ -158,8 +158,6 @@ var (
// Cache initialized Volatilizer for cache and pub/sub
Cache cache.Volatilizer
Search *search.Search
// Log initialized Logger for all logging
Log *logger.Logger

// Membership exposes Account and User functionalities like register, login, etc
// account and user functionalities.
Expand All @@ -181,21 +179,21 @@ var (

// Setup initializes the core services based on the configuration received.
func Setup(cfg config.AppConfig) {
logger.Setup(cfg)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if err := Close(ctx); err != nil && Log != nil {
Log.Error().Err(err).Msg("error closing existing backend services")
defer cancel()

if err := Close(ctx); err != nil {
slog.Error("error closing existing backend services", "error", err)
}
cancel()

Config = cfg
resetLifecycle()

Log = logger.Get(cfg)

if strings.EqualFold(cfg.DatabaseURL, "mem") || strings.EqualFold(cfg.RedisHost, "mem") {
Cache = cache.NewDevCache(Log)
Cache = cache.NewDevCache()
} else {
Cache = cache.NewCache(Log)
Cache = cache.NewCache()
}

persister := config.Current.DataStore
Expand All @@ -204,30 +202,29 @@ func Setup(cfg config.AppConfig) {
} else if strings.EqualFold(persister, "mongo") {
cl, err := openMongoDatabase(cfg.DatabaseURL)
if err != nil {
Log.Fatal().Err(err).Msg("failed to create connection with mongodb")
logger.FatalError("failed to create connection with mongodb", err)
}
DB = mongo.New(cl, Cache.PublishDocument, Log)
DB = mongo.New(cl, Cache.PublishDocument)
} else if strings.EqualFold(persister, "sqlite") {
cl, err := openSQLite(cfg.DatabaseURL)
if err != nil {
Log.Fatal().Err(err).Msg("failed to create connection with SQLite")
logger.FatalError("failed to create connection with SQLite", err)
}

DB = sqlite.New(cl, Cache.PublishDocument, Log)
DB = sqlite.New(cl, Cache.PublishDocument)
} else {
cl, err := openPGDatabase(cfg.DatabaseURL, cfg)
if err != nil {
Log.Fatal().Err(err).Msg("failed to create connection with postgres")
logger.FatalError("failed to create connection with postgres", err)
}
pool := normalizedPostgresPoolConfig(cfg)
Log.Info().
Int("max_open_connections", pool.maxOpenConns).
Int("max_idle_connections", pool.maxIdleConns).
Int("max_lifetime_seconds", pool.maxLifetimeSeconds).
Int("max_idle_time_seconds", pool.maxIdleTimeSeconds).
Msg("postgres connection pool configured")

DB = postgresql.New(cl, Cache.PublishDocument, Log)
slog.Info("postgres connection pool configured",
"max_open_connections", pool.maxOpenConns,
"max_idle_connections", pool.maxIdleConns,
"max_lifetime_seconds", pool.maxLifetimeSeconds,
"max_idle_time_seconds", pool.maxIdleTimeSeconds)

DB = postgresql.New(cl, Cache.PublishDocument)
}

mp := cfg.MailProvider
Expand All @@ -253,14 +250,14 @@ func Setup(cfg config.AppConfig) {
}
src, err := search.New(ftsFilename, Cache)
if err != nil {
Log.Fatal().Err(err).Msg("unable to start full-text search")
logger.FatalError("unable to start full-text search", err)
return
}

Search = src
}

sub := &function.Subscriber{Log: Log}
sub := &function.Subscriber{}
sub.PubSub = Cache
sub.GetExecEnv = func(msg model.Command) (*function.ExecutionEnvironment, error) {
exe := &function.ExecutionEnvironment{
Expand All @@ -270,7 +267,6 @@ func Setup(cfg config.AppConfig) {
Volatile: Cache,
Search: Search,
Email: Emailer,
Log: Log,
}

return exe, nil
Expand All @@ -281,7 +277,7 @@ func Setup(cfg config.AppConfig) {
// if no value is provided, like on GH action for tests, we assume primary
isPrimary = true
} else if hostname, err := os.Hostname(); err != nil {
Log.Warn().Err(err).Msg("cannot determine if it's primary instance")
slog.Warn("cannot determine if it's primary instance", "error", err)
} else if strings.EqualFold(hostname, cfg.PrimaryInstanceHostname) {
isPrimary = true
}
Expand All @@ -307,12 +303,11 @@ func Setup(cfg config.AppConfig) {
DataStore: DB,
Search: Search,
Email: Emailer,
Log: Log,
}

Scheduler = runner
go runner.Start()
Log.Info().Msg("job scheduler / runner started on primary instance")
slog.Info("job scheduler / runner started on primary instance")
}

Membership = newUser
Expand Down
11 changes: 7 additions & 4 deletions backend/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,22 @@ func TestMain(t *testing.M) {
// initializes all core services basesd on config
backend.Setup(config.Current)

setup()
if err := setup(); err != nil {
panic(err)
}

os.Exit(t.Run())
}

func setup() {
func setup() error {
if err := createTenantAndDatabase(); err != nil {
backend.Log.Fatal().Err(err)
return err
}

if err := createUser(); err != nil {
backend.Log.Fatal().Err(err)
return err
}
return nil
}

func createTenantAndDatabase() error {
Expand Down
5 changes: 3 additions & 2 deletions backend/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"math/rand"
"strings"
"time"
Expand Down Expand Up @@ -249,7 +250,7 @@ func (u User) publishAccountCreated(accountID, email string, tok model.User) {
}
b, err := json.Marshal(data)
if err != nil {
Log.Error().Err(err).Msg("error marshaling system account event")
slog.Error("error marshaling system account event", "error", err)
return
}

Expand All @@ -260,7 +261,7 @@ func (u User) publishAccountCreated(accountID, email string, tok model.User) {
Auth: auth,
Base: u.conf.Name,
}); err != nil {
Log.Error().Err(err).Msg("error publishing system account event")
slog.Error("error publishing system account event", "error", err)
}
}

Expand Down
Loading
Loading