package database import ( "eden-server/internal/runtime" "path/filepath" "time" "gorm.io/driver/sqlite" "gorm.io/gorm" ) //var watchdogStop = make(chan struct{}) func KickoffDatabase(workDir string) (*gorm.DB, error) { dbLoc := filepath.Join(workDir, "data", "garden.db") db, err := gorm.Open(sqlite.Open(dbLoc), &gorm.Config{}) if err != nil { return nil, err } if err := db.AutoMigrate(&State{}); err != nil { return nil, err } if err := db.AutoMigrate(&Device{}); err != nil { return nil, err } if err := db.AutoMigrate(&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 runtime.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.DataDirectory, db) // then defer to a decoupled/disowned golang goroutine for range ticker.C { watchdog(env.DataDirectory, db) } }() }