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:
@@ -5,23 +5,23 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/db"
|
||||
)
|
||||
|
||||
// Worker performs background synchronization at regular intervals
|
||||
type Worker struct {
|
||||
service *Service
|
||||
db *gorm.DB
|
||||
connMgr *db.ConnectionManager
|
||||
interval time.Duration
|
||||
logger *slog.Logger
|
||||
stopCh chan struct{}
|
||||
}
|
||||
|
||||
// NewWorker creates a new background sync worker
|
||||
func NewWorker(service *Service, db *gorm.DB, interval time.Duration) *Worker {
|
||||
func NewWorker(service *Service, connMgr *db.ConnectionManager, interval time.Duration) *Worker {
|
||||
return &Worker{
|
||||
service: service,
|
||||
db: db,
|
||||
connMgr: connMgr,
|
||||
interval: interval,
|
||||
logger: slog.Default(),
|
||||
stopCh: make(chan struct{}),
|
||||
@@ -30,11 +30,7 @@ func NewWorker(service *Service, db *gorm.DB, interval time.Duration) *Worker {
|
||||
|
||||
// isOnline checks if the database connection is available
|
||||
func (w *Worker) isOnline() bool {
|
||||
sqlDB, err := w.db.DB()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return sqlDB.Ping() == nil
|
||||
return w.connMgr.IsOnline()
|
||||
}
|
||||
|
||||
// Start begins the background sync loop in a goroutine
|
||||
|
||||
Reference in New Issue
Block a user