Skip to content
Open
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
40 changes: 18 additions & 22 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,23 +202,23 @@ 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)
if err != nil {
Log.Fatal().Err(err).Msg("failed to create connection with postgres")
logger.FatalError("failed to create connection with postgres", err)
}

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

mp := cfg.MailProvider
Expand All @@ -246,14 +244,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 @@ -263,7 +261,6 @@ func Setup(cfg config.AppConfig) {
Volatile: Cache,
Search: Search,
Email: Emailer,
Log: Log,
}

return exe, nil
Expand All @@ -274,7 +271,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 @@ -300,12 +297,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
31 changes: 15 additions & 16 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"

"github.com/staticbackendhq/core/config"
Expand All @@ -26,18 +27,17 @@ const (
type Cache struct {
Rdb *redis.Client
Ctx context.Context
log *logger.Logger
}

// NewCache returns an initiated Redis client
func NewCache(log *logger.Logger) *Cache {
func NewCache() *Cache {
var err error
var opt *redis.Options

if uri := config.Current.RedisURL; len(uri) > 0 {
opt, err = redis.ParseURL(uri)
if err != nil {
log.Fatal().Err(err).Msg("invalid REDIS_URL value")
logger.FatalError("invalid REDIS_URL value", err)
}
} else {
opt = &redis.Options{
Expand All @@ -51,7 +51,6 @@ func NewCache(log *logger.Logger) *Cache {
return &Cache{
Rdb: rdb,
Ctx: context.Background(),
log: log,
}
}

Expand Down Expand Up @@ -113,12 +112,12 @@ func (c *Cache) Subscribe(send chan model.Command, token, channel string, close
pubsub := c.Rdb.Subscribe(c.Ctx, channel)

if _, err := pubsub.Receive(c.Ctx); err != nil {
c.log.Error().Err(err).Msg("error establishing PubSub subscription")
slog.Error("error establishing PubSub subscription", "error", err)
return
}
defer func() {
if err := pubsub.Close(); err != nil && !errors.Is(err, redis.ErrClosed) {
c.log.Warn().Err(err).Msg("error closing PubSub subscription")
slog.Warn("error closing PubSub subscription", "error", err)
}
}()

Expand All @@ -132,13 +131,13 @@ func (c *Cache) Subscribe(send chan model.Command, token, channel string, close
select {
case m, ok := <-ch:
if !ok {
c.log.Warn().Msgf("PubSub channel closed: %s", channel)
slog.Warn("PubSub channel closed", "channel", channel)
return
}

var msg model.Command
if err := json.Unmarshal([]byte(m.Payload), &msg); err != nil {
c.log.Error().Err(err).Msg("error parsing JSON message")
slog.Error("error parsing JSON message", "error", err)
return
}

Expand Down Expand Up @@ -169,7 +168,7 @@ func (c *Cache) sendMessage(send chan model.Command, close chan bool, msg model.
case <-close:
return false
case <-timer.C:
c.log.Warn().Msgf("dropping PubSub message after blocked receiver timeout: %s", msg.Channel)
slog.Warn("dropping PubSub message after blocked receiver timeout", "channel", msg.Channel)
return true
}
}
Expand All @@ -192,27 +191,27 @@ func (c *Cache) Publish(msg model.Command) error {
sysmsg.IsSystemEvent = true
b, err := json.Marshal(sysmsg)
if err != nil {
c.log.Error().Err(err).Msg("error marshaling the system msg")
slog.Error("error marshaling the system msg", "error", err)
return
}

sysctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
if err := c.Rdb.Publish(sysctx, "sbsys", string(b)).Err(); err != nil {
c.log.Error().Err(err).Msg("error publishing to system channel")
slog.Error("error publishing to system channel", "error", err)
}
}(msg)
}

subs, err := c.Rdb.PubSubNumSub(c.Ctx, msg.Channel).Result()
if err != nil {
c.log.Error().Err(err).Msgf("error getting db subscribers for %s", msg.Channel)
slog.Error("error getting db subscribers for", "channel", msg.Channel, "error", err)
return err
}

count, ok := subs[msg.Channel]
if !ok {
c.log.Warn().Msgf("cannot find channel in subs: %s", msg.Channel)
slog.Warn("cannot find channel in subs", "channel", msg.Channel)
return nil
} else if count == 0 {
return nil
Expand All @@ -226,7 +225,7 @@ func (c *Cache) Publish(msg model.Command) error {
func (c *Cache) PublishDocument(auth model.Auth, dbName, channel, typ string, v interface{}) {
b, err := json.Marshal(v)
if err != nil {
c.log.Error().Err(err).Msg("error publishing db doc")
slog.Error("error publishing db doc", "error", err)
return
}

Expand All @@ -239,7 +238,7 @@ func (c *Cache) PublishDocument(auth model.Auth, dbName, channel, typ string, v
}

if err := c.Publish(msg); err != nil {
c.log.Error().Err(err).Msg("unable to publish db doc events")
slog.Error("unable to publish db doc events", "error", err)
}
}

Expand All @@ -258,7 +257,7 @@ func (c *Cache) HasPermission(token, repo, payload string) bool {

docs := make(map[string]interface{})
if err := json.Unmarshal([]byte(payload), &docs); err != nil {
c.log.Error().Err(err).Msg("error decoding docs for permissions check")
slog.Error("error decoding docs for permissions check", "error", err)

return false
}
Expand Down
Loading
Loading