Skip to content

Commit

Permalink
feat(config): yeet thread safety, just hope for the best
Browse files Browse the repository at this point in the history
  • Loading branch information
Topvennie committed Dec 10, 2024
1 parent 0696f11 commit 071975a
Show file tree
Hide file tree
Showing 13 changed files with 45 additions and 73 deletions.
6 changes: 3 additions & 3 deletions internal/cmd/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import (
func Event(db *db.DB) (*event.Event, chan bool) {
ev := event.New(db)
done := make(chan bool)
interval := config.GetDefaultInt("backend.event.interval_s", 3600)

go eventPeriodicUpdate(ev, done)
go eventPeriodicUpdate(ev, done, interval)

return ev, done
}

func eventPeriodicUpdate(ev *event.Event, done chan bool) {
interval := config.GetDefaultInt("backend.event.interval_s", 3600)
func eventPeriodicUpdate(ev *event.Event, done chan bool, interval int) {
zap.S().Info("Event: Starting periodic leaderboard update with an interval of ", interval, " seconds")

ticker := time.NewTimer(time.Duration(interval) * time.Second)
Expand Down
6 changes: 3 additions & 3 deletions internal/cmd/gamification.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import (
func Gamification(db *db.DB) (*gamification.Gamification, chan bool) {
gam := gamification.New(db)
done := make(chan bool)
interval := config.GetDefaultInt("backend.gamification.interval_s", 3600)

go gamificationPeriodicUpdate(gam, done)
go gamificationPeriodicUpdate(gam, done, interval)

return gam, done
}

func gamificationPeriodicUpdate(gam *gamification.Gamification, done chan bool) {
interval := config.GetDefaultInt("backend.gamification.interval_s", 3600)
func gamificationPeriodicUpdate(gam *gamification.Gamification, done chan bool, interval int) {
zap.S().Info("Gamification: Starting periodic leaderboard update with an interval of ", interval, " seconds")

ticker := time.NewTicker(time.Duration(interval) * time.Second)
Expand Down
6 changes: 3 additions & 3 deletions internal/cmd/tap.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import (
func Tap(db *db.DB) (*tap.Tap, chan bool) {
tap := tap.New(db)
done := make(chan bool)
interval := config.GetDefaultInt("backend.tap.interval_s", 60)

go tapPeriodicUpdate(tap, done)
go tapPeriodicUpdate(tap, done, interval)

return tap, done
}

func tapPeriodicUpdate(tap *tap.Tap, done chan bool) {
interval := config.GetDefaultInt("backend.tap.interval_s", 60)
func tapPeriodicUpdate(tap *tap.Tap, done chan bool, interval int) {
zap.S().Info("Tap: Starting periodic update with an interval of ", interval, " seconds")

ticker := time.NewTicker(time.Duration(interval) * time.Second)
Expand Down
14 changes: 8 additions & 6 deletions internal/cmd/zess.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,20 @@ import (
// Zess starts the zess instance
func Zess(db *db.DB) (*zess.Zess, chan bool, chan bool) {
zess := zess.New(db)

doneSeason := make(chan bool)
intervalSeason := config.GetDefaultInt("backend.zess.interval_season_s", 300)

doneScan := make(chan bool)
intervalScan := config.GetDefaultInt("backend.zess.interval_scan_s", 60)

go zessPeriodicSeasonUpdate(zess, doneSeason)
go zessPeriodicScanUpdate(zess, doneScan)
go zessPeriodicSeasonUpdate(zess, doneSeason, intervalSeason)
go zessPeriodicScanUpdate(zess, doneScan, intervalScan)

return zess, doneSeason, doneScan
}

func zessPeriodicSeasonUpdate(zess *zess.Zess, done chan bool) {
interval := config.GetDefaultInt("backend.zess.interval_season_s", 300)
func zessPeriodicSeasonUpdate(zess *zess.Zess, done chan bool, interval int) {
zap.S().Info("Zess: Starting periodic season update with an interval of ", interval, " seconds")

ticker := time.NewTicker(time.Duration(interval) * time.Second)
Expand All @@ -49,8 +52,7 @@ func zessPeriodicSeasonUpdate(zess *zess.Zess, done chan bool) {
}
}

func zessPeriodicScanUpdate(zess *zess.Zess, done chan bool) {
interval := config.GetDefaultInt("backend.zess.interval_scan_s", 60)
func zessPeriodicScanUpdate(zess *zess.Zess, done chan bool, interval int) {
zap.S().Info("Zess: Starting periodic scan update with an interval of ", interval, " seconds")

ticker := time.NewTicker(time.Duration(interval) * time.Second)
Expand Down
10 changes: 6 additions & 4 deletions internal/pkg/event/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ import (

var layout = "Monday 02 January, 15:04 2006"

var (
website = config.GetDefaultString("backend.event.website", "https://zeus.gent/events")
websitePoster = config.GetDefaultString("backend.event.website_poster", "https://git.zeus.gent/ZeusWPI/visueel/raw/branch/master")
)

func (e *Event) getEvents() ([]dto.Event, error) {
zap.S().Info("Events: Getting all events")

website := config.GetDefaultString("backend.event.website", "https://zeus.gent/events")

var events []dto.Event
var errs []error
c := colly.NewCollector()
Expand Down Expand Up @@ -83,7 +86,6 @@ func (e *Event) getEvents() ([]dto.Event, error) {
func (e *Event) getPoster(event *dto.Event) error {
zap.S().Info("Events: Getting poster for ", event.Name)

website := config.GetDefaultString("backend.event.website_poster", "https://git.zeus.gent/ZeusWPI/visueel/raw/branch/master")
yearParts := strings.Split(event.AcademicYear, "-")
if len(yearParts) != 2 {
return fmt.Errorf("Event: Academic year not properly formatted %s", event.AcademicYear)
Expand All @@ -100,7 +102,7 @@ func (e *Event) getPoster(event *dto.Event) error {

year := fmt.Sprintf("20%d-20%d", yearStart, yearEnd)

url := fmt.Sprintf("%s/%s/%s/scc.png", website, year, event.Name)
url := fmt.Sprintf("%s/%s/%s/scc.png", websitePoster, year, event.Name)

req := fiber.Get(url)
status, body, errs := req.Bytes()
Expand Down
3 changes: 2 additions & 1 deletion internal/pkg/gamification/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"go.uber.org/zap"
)

var api = config.GetDefaultString("backend.gamification.api", "https://gamification.zeus.gent")

type gamificationItem struct {
ID int32 `json:"id"`
Name string `json:"github_name"`
Expand All @@ -20,7 +22,6 @@ type gamificationItem struct {
func (g *Gamification) getLeaderboard() ([]dto.Gamification, error) {
zap.S().Info("Gamification: Getting leaderboard")

api := config.GetDefaultString("backend.gamification.api", "https://gamification.zeus.gent")
req := fiber.Get(api+"/top4").Set("Accept", "application/json")

res := new([]gamificationItem)
Expand Down
5 changes: 3 additions & 2 deletions internal/pkg/song/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"go.uber.org/zap"
)

var apiAccount = config.GetDefaultString("backend.song.spotify_api_account", "https://accounts.spotify.com/api/token")

type accountResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Expand All @@ -21,8 +23,7 @@ func (s *Song) refreshToken() error {
form := &fiber.Args{}
form.Add("grant_type", "client_credentials")

api := config.GetDefaultString("backend.song.spotify_api_account", "https://accounts.spotify.com/api/token")
req := fiber.Post(api).Form(form).BasicAuth(s.ClientID, s.ClientSecret)
req := fiber.Post(apiAccount).Form(form).BasicAuth(s.ClientID, s.ClientSecret)

res := new(accountResponse)
status, _, errs := req.Struct(res)
Expand Down
7 changes: 5 additions & 2 deletions internal/pkg/song/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ import (
"go.uber.org/zap"
)

var api = config.GetDefaultString("backend.song.spotify_api", "https://api.spotify.com/v1")
var (
api = config.GetDefaultString("backend.song.spotify_api", "https://api.spotify.com/v1")
apiLrclib = config.GetDefaultString("backend.song.lrclib_api", "https://lrclib.net/api")
)

type trackArtist struct {
ID string `json:"id"`
Expand Down Expand Up @@ -121,7 +124,7 @@ func (s *Song) getLyrics(track *dto.Song) error {
params.Set("album_name", track.Album)
params.Set("duration", fmt.Sprintf("%d", track.DurationMS/1000))

req := fiber.Get(fmt.Sprintf("%s/get?%s", config.GetDefaultString("backend.song.lrclib_api", "https://lrclib.net/api"), params.Encode()))
req := fiber.Get(fmt.Sprintf("%s/get?%s", apiLrclib, params.Encode()))

res := new(lyricsResponse)
status, _, errs := req.Struct(res)
Expand Down
3 changes: 2 additions & 1 deletion internal/pkg/tap/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"go.uber.org/zap"
)

var api = config.GetDefaultString("backend.tap.api", "https://tap.zeus.gent")

type orderResponseItem struct {
OrderID int32 `json:"order_id"`
OrderCreatedAt time.Time `json:"order_created_at"`
Expand All @@ -23,7 +25,6 @@ type orderResponse struct {
func (t *Tap) getOrders() ([]orderResponseItem, error) {
zap.S().Info("Tap: Getting orders")

api := config.GetDefaultString("backend.tap.api", "https://tap.zeus.gent")
req := fiber.Get(api + "/recent")

res := new(orderResponse)
Expand Down
6 changes: 4 additions & 2 deletions internal/pkg/zess/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ import (
"go.uber.org/zap"
)

var (
api = config.GetDefaultString("backend.zess.api", "https://zess.zeus.gent")
)

func (z *Zess) getSeasons() (*[]*dto.Season, error) {
zap.S().Info("Zess: Getting seasons")

api := config.GetDefaultString("backend.zess.api", "https://zess.zeus.gent")
req := fiber.Get(api + "/seasons")

res := new([]*dto.Season)
Expand All @@ -38,7 +41,6 @@ func (z *Zess) getSeasons() (*[]*dto.Season, error) {
func (z *Zess) getScans() (*[]*dto.Scan, error) {
zap.S().Info("Zess: Getting scans")

api := config.GetDefaultString("backend.zess.api", "https://zess.zeus.gent")
req := fiber.Get(api + "/recent_scans")

res := new([]*dto.Scan)
Expand Down
44 changes: 0 additions & 44 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,14 @@ package config
import (
"fmt"
"strings"
"sync"

"github.com/joho/godotenv"
"github.com/spf13/viper"
)

var mu sync.Mutex

func bindEnv(key string) {
envName := strings.ToUpper(strings.ReplaceAll(key, ".", "_"))

mu.Lock()
defer mu.Unlock()

_ = viper.BindEnv(key, envName)
}

Expand All @@ -27,9 +21,6 @@ func Init() error {
return err
}

mu.Lock()
defer mu.Unlock()

viper.AutomaticEnv()
env := GetDefaultString("app.env", "development")

Expand All @@ -43,94 +34,59 @@ func Init() error {
// GetString returns the value of the key in string
func GetString(key string) string {
bindEnv(key)

mu.Lock()
defer mu.Unlock()

return viper.GetString(key)
}

// GetDefaultString returns the value of the key in string or a default value
func GetDefaultString(key, defaultValue string) string {
mu.Lock()
defer mu.Unlock()

viper.SetDefault(key, defaultValue)
return GetString(key)
}

// GetStringSlice returns the value of the key in string slice
func GetStringSlice(key string) []string {
bindEnv(key)

mu.Lock()
defer mu.Unlock()

return viper.GetStringSlice(key)
}

// GetDefaultStringSlice returns the value of the key in string slice or a default value
func GetDefaultStringSlice(key string, defaultValue []string) []string {
mu.Lock()
defer mu.Unlock()

viper.SetDefault(key, defaultValue)
return GetStringSlice(key)
}

// GetInt returns the value of the key in int
func GetInt(key string) int {
bindEnv(key)

mu.Lock()
defer mu.Unlock()

return viper.GetInt(key)
}

// GetDefaultInt returns the value of the key in int or a default value
func GetDefaultInt(key string, defaultVal int) int {
mu.Lock()
defer mu.Unlock()

viper.SetDefault(key, defaultVal)
return GetInt(key)
}

// GetUint16 returns the value of the key in uint16
func GetUint16(key string) uint16 {
bindEnv(key)

mu.Lock()
defer mu.Unlock()

return viper.GetUint16(key)
}

// GetDefaultUint16 returns the value of the key in uint16 or a default value
func GetDefaultUint16(key string, defaultVal uint16) uint16 {
mu.Lock()
defer mu.Unlock()

viper.SetDefault(key, defaultVal)
return GetUint16(key)
}

// GetBool returns the value of the key in bool
func GetBool(key string) bool {
bindEnv(key)

mu.Lock()
defer mu.Unlock()

return viper.GetBool(key)
}

// GetDefaultBool returns the value of the key in bool or a default value
func GetDefaultBool(key string, defaultVal bool) bool {
mu.Lock()
defer mu.Unlock()

viper.SetDefault(key, defaultVal)
return GetBool(key)
}
4 changes: 3 additions & 1 deletion tui/screen/cammie/cammie.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"github.com/zeusWPI/scc/tui/view/zess"
)

var bottomTimeout = config.GetDefaultInt("tui.screen.cammie.interval_s", 300)

// Cammie represents the cammie screen
type Cammie struct {
db *db.DB
Expand Down Expand Up @@ -162,7 +164,7 @@ func (c *Cammie) GetSizeMsg() tea.Msg {
}

func updateBottomIndex(cammie Cammie) tea.Cmd {
timeout := time.Duration(config.GetDefaultInt("tui.screen.cammie.interval_s", 300) * int(time.Second))
timeout := time.Duration(bottomTimeout * int(time.Second))
return tea.Tick(timeout, func(_ time.Time) tea.Msg {
newIndex := (cammie.indexTop + 1) % len(cammie.top)

Expand Down
4 changes: 3 additions & 1 deletion tui/view/zess/zess.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"go.uber.org/zap"
)

var maxWeeks = config.GetDefaultInt("tui.view.zess.weeks", 10)

// yearWeek represents a yearWeek object by keeping the year and week number
type yearWeek struct {
year int
Expand Down Expand Up @@ -120,7 +122,7 @@ func (m *Model) Update(msg tea.Msg) (view.View, tea.Cmd) {
m.maxWeekScans = newScan.amount
}
// Make sure the array doesn't get too big
if len(m.scans) > config.GetDefaultInt("tui.view.zess.weeks", 10) {
if len(m.scans) > maxWeeks {
m.scans = m.scans[:1]
}
}
Expand Down

0 comments on commit 071975a

Please sign in to comment.