package database import ( "eden-server/internal/utility" "log/slog" "path/filepath" "time" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" ) //var watchdogStop = make(chan struct{}) func KickoffDatabase(workDir string) (*gorm.DB, error) { dbLoc := filepath.Join(workDir, "garden.db") db, err := gorm.Open(sqlite.Open(dbLoc), &gorm.Config{ Logger: logger.Discard, // disable gorm logging since its not slog (yet) TranslateError: true, }) if err != nil { return nil, err } // try to use GORM automigrate if the schema changes slog.Info("performing migration") if err := db.AutoMigrate( &State{}, &Device{}, &File{}, ); err != nil { return nil, err } // create the first row if it does not exist yet if err := db.FirstOrCreate(&State{}, State{ ID: 0, MediaType: "unspecified", }).Error; err != nil { return nil, err } return db, nil } func KickoffDatabaseWatchdog(env utility.Environment, db *gorm.DB) { timeInterval := time.Second * time.Duration(env.WatchInterval) ticker := time.NewTicker(timeInterval) go func() { defer ticker.Stop() /* // Possible future mechanism to stop the watchdog // must be inside a non-conditional for loop select { case <-ticker.C: // ticker event watchdog(env.DataDirectory, db) case <-watchdogStop: return } */ // run the watchdog function once to see if all is well. watchdog(env, db) // then defer to a decoupled/disowned golang goroutine for range ticker.C { watchdog(env, db) } }() }