feat: add ConnectionManager for lazy database connections
Introduced ConnectionManager to support offline-first architecture: - New internal/db/connection.go with thread-safe connection management - Lazy connection establishment (5s timeout, 10s cooldown) - Automatic ping caching (30s interval) to avoid excessive checks - Updated middleware/offline.go to use ConnectionManager.IsOnline() - Updated sync/worker.go to use ConnectionManager instead of direct DB This enables the application to start without MariaDB and gracefully handle offline/online transitions. Part of Phase 2.5: Full Offline Mode Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,17 +4,17 @@ import (
|
||||
"log/slog"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/db"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OfflineDetector creates middleware that detects offline mode
|
||||
// Sets context values:
|
||||
// - "is_offline" (bool) - true if MariaDB is unavailable
|
||||
// - "localdb" (*localdb.LocalDB) - local database instance for fallback
|
||||
func OfflineDetector(mariaDB *gorm.DB, local *localdb.LocalDB) gin.HandlerFunc {
|
||||
func OfflineDetector(connMgr *db.ConnectionManager, local *localdb.LocalDB) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
isOffline := !checkMariaDBOnline(mariaDB)
|
||||
isOffline := !connMgr.IsOnline()
|
||||
|
||||
// Set context values for handlers
|
||||
c.Set("is_offline", isOffline)
|
||||
@@ -27,17 +27,3 @@ func OfflineDetector(mariaDB *gorm.DB, local *localdb.LocalDB) gin.HandlerFunc {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// checkMariaDBOnline checks if MariaDB is accessible
|
||||
func checkMariaDBOnline(mariaDB *gorm.DB) bool {
|
||||
sqlDB, err := mariaDB.DB()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if err := sqlDB.Ping(); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user