feat: 支持数据库迁移脏状态自动恢复和Neo4j连接重试机制

This commit is contained in:
wizardchen
2025-12-08 17:40:10 +08:00
parent 8eb737ae28
commit c67a5d3949
9 changed files with 829 additions and 474 deletions
+35 -10
View File
@@ -279,9 +279,13 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
// Run database migrations automatically (optional, can be disabled via env var)
// To disable auto-migration, set AUTO_MIGRATE=false
// To enable auto-recovery from dirty state, set AUTO_RECOVER_DIRTY=true
if os.Getenv("AUTO_MIGRATE") != "false" {
logger.Infof(context.Background(), "Running database migrations...")
if err := database.RunMigrations(migrateDSN); err != nil {
autoRecover := os.Getenv("AUTO_RECOVER_DIRTY") == "true"
if err := database.RunMigrationsWithOptions(migrateDSN, database.MigrationOptions{
AutoRecoverDirty: autoRecover,
}); err != nil {
// Log warning but don't fail startup - migrations might be handled externally
logger.Warnf(context.Background(), "Database migration failed: %v", err)
logger.Warnf(
@@ -539,21 +543,42 @@ func initOllamaService() (*ollama.OllamaService, error) {
}
func initNeo4jClient() (neo4j.Driver, error) {
ctx := context.Background()
if strings.ToLower(os.Getenv("NEO4J_ENABLE")) != "true" {
logger.Debugf(context.Background(), "NOT SUPPORT RETRIEVE GRAPH")
logger.Debugf(ctx, "NOT SUPPORT RETRIEVE GRAPH")
return nil, nil
}
uri := os.Getenv("NEO4J_URI")
username := os.Getenv("NEO4J_USERNAME")
password := os.Getenv("NEO4J_PASSWORD")
driver, err := neo4j.NewDriver(uri, neo4j.BasicAuth(username, password, ""))
if err != nil {
return nil, err
// Retry configuration
maxRetries := 30 // Max retry attempts
retryInterval := 2 * time.Second // Wait between retries
var driver neo4j.Driver
var err error
for attempt := 1; attempt <= maxRetries; attempt++ {
driver, err = neo4j.NewDriver(uri, neo4j.BasicAuth(username, password, ""))
if err != nil {
logger.Warnf(ctx, "Failed to create Neo4j driver (attempt %d/%d): %v", attempt, maxRetries, err)
time.Sleep(retryInterval)
continue
}
err = driver.VerifyAuthentication(ctx, nil)
if err == nil {
if attempt > 1 {
logger.Infof(ctx, "Successfully connected to Neo4j after %d attempts", attempt)
}
return driver, nil
}
logger.Warnf(ctx, "Failed to verify Neo4j authentication (attempt %d/%d): %v", attempt, maxRetries, err)
driver.Close(ctx)
time.Sleep(retryInterval)
}
err = driver.VerifyAuthentication(context.Background(), nil)
if err != nil {
return nil, err
}
return driver, nil
return nil, fmt.Errorf("failed to connect to Neo4j after %d attempts: %w", maxRetries, err)
}
+129 -35
View File
@@ -14,11 +14,28 @@ import (
// RunMigrations executes all pending database migrations
// This should be called during application startup
func RunMigrations(dsn string) error {
return RunMigrationsWithOptions(dsn, MigrationOptions{AutoRecoverDirty: false})
}
// MigrationOptions configures migration behavior
type MigrationOptions struct {
// AutoRecoverDirty when true, automatically attempts to recover from dirty state
// by forcing to the previous version and retrying the migration
AutoRecoverDirty bool
}
// RunMigrationsWithOptions executes all pending database migrations with custom options
func RunMigrationsWithOptions(dsn string, opts MigrationOptions) error {
ctx := context.Background()
logger.Infof(ctx, "Starting database migration...")
// Use versioned migrations directory
migrationsPath := "file://migrations/versioned"
m, err := migrate.New(migrationsPath, dsn)
if err != nil {
logger.Errorf(ctx, "Failed to create migrate instance: %v", err)
return fmt.Errorf("failed to create migrate instance: %w", err)
}
defer m.Close()
@@ -26,57 +43,93 @@ func RunMigrations(dsn string) error {
// Check current version and dirty state before migration
oldVersion, oldDirty, versionErr := m.Version()
if versionErr != nil && versionErr != migrate.ErrNilVersion {
// If we can't get version and it's not because database is empty, return error
logger.Errorf(ctx, "Failed to get migration version: %v", versionErr)
return fmt.Errorf("failed to get migration version: %w", versionErr)
}
// If database is in dirty state, return detailed error with fix instructions
if oldDirty {
// Calculate the version to force to (usually the previous version)
forceVersion := int(oldVersion) - 1
if oldVersion == 0 || forceVersion < 0 {
forceVersion = 0
}
return fmt.Errorf(
"database is in dirty state at version %d. This usually means a migration failed partway through. "+
"To fix this:\n"+
"1. Check if the migration partially applied changes and manually fix if needed\n"+
"2. Use the force command to set the version to the last successful migration (usually %d):\n"+
" ./scripts/migrate.sh force %d\n"+
" Or if using make: make migrate-force version=%d\n"+
"3. After fixing, restart the application to retry the migration",
oldVersion,
forceVersion,
forceVersion,
forceVersion,
)
if versionErr == migrate.ErrNilVersion {
logger.Infof(ctx, "Database has no migration history, will start from version 0")
} else {
logger.Infof(ctx, "Current migration version: %d, dirty: %v", oldVersion, oldDirty)
}
// Run all pending migrations
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
// Check if error is due to dirty state (in case it became dirty during migration)
currentVersion, currentDirty, versionCheckErr := m.Version()
if versionCheckErr == nil && currentDirty {
// If database is in dirty state, try to recover or return error
if oldDirty {
logger.Warnf(ctx, "Database is in dirty state at version %d", oldVersion)
if opts.AutoRecoverDirty {
logger.Infof(ctx, "AutoRecoverDirty is enabled, attempting recovery...")
if err := recoverFromDirtyState(ctx, m, oldVersion); err != nil {
return err
}
// Update oldVersion after recovery
oldVersion, _, _ = m.Version()
} else {
// Calculate the version to force to (usually the previous version)
forceVersion := currentVersion - 1
if currentVersion == 0 {
forceVersion := int(oldVersion) - 1
if oldVersion == 0 || forceVersion < 0 {
forceVersion = 0
}
return fmt.Errorf(
"migration failed and database is now in dirty state at version %d. "+
"database is in dirty state at version %d. This usually means a migration failed partway through. "+
"To fix this:\n"+
"1. Check if the migration partially applied changes and manually fix if needed\n"+
"2. Use the force command to set the version to the last successful migration (usually %d):\n"+
" ./scripts/migrate.sh force %d\n"+
" Or if using make: make migrate-force version=%d\n"+
"3. After fixing, restart the application to retry the migration",
currentVersion,
"3. After fixing, restart the application to retry the migration\n"+
"Or enable AutoRecoverDirty option to automatically retry",
oldVersion,
forceVersion,
forceVersion,
forceVersion,
)
}
return fmt.Errorf("failed to run migrations: %w", err)
}
// Run all pending migrations
logger.Infof(ctx, "Running pending migrations...")
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
logger.Errorf(ctx, "Migration failed: %v", err)
// Check if error is due to dirty state (in case it became dirty during migration)
currentVersion, currentDirty, versionCheckErr := m.Version()
if versionCheckErr == nil && currentDirty {
logger.Warnf(ctx, "Migration caused dirty state at version %d", currentVersion)
if opts.AutoRecoverDirty {
logger.Infof(ctx, "Attempting to recover from dirty state...")
// Try to recover and retry
if recoverErr := recoverFromDirtyState(ctx, m, currentVersion); recoverErr != nil {
return recoverErr
}
// Retry migration after recovery
logger.Infof(ctx, "Retrying migration after recovery...")
if retryErr := m.Up(); retryErr != nil && retryErr != migrate.ErrNoChange {
logger.Errorf(ctx, "Migration failed after recovery attempt: %v", retryErr)
return fmt.Errorf("migration failed after recovery attempt: %w", retryErr)
}
} else {
// Calculate the version to force to (usually the previous version)
forceVersion := currentVersion - 1
if currentVersion == 0 {
forceVersion = 0
}
return fmt.Errorf(
"migration failed and database is now in dirty state at version %d. "+
"To fix this:\n"+
"1. Check if the migration partially applied changes and manually fix if needed\n"+
"2. Use the force command to set the version to the last successful migration (usually %d):\n"+
" ./scripts/migrate.sh force %d\n"+
" Or if using make: make migrate-force version=%d\n"+
"3. After fixing, restart the application to retry the migration\n"+
"Or enable AutoRecoverDirty option to automatically retry",
currentVersion,
forceVersion,
forceVersion,
forceVersion,
)
}
} else {
return fmt.Errorf("failed to run migrations: %w", err)
}
}
// Get current version after migration
@@ -86,18 +139,59 @@ func RunMigrations(dsn string) error {
}
if oldVersion != version {
logger.Infof(context.Background(), "Database migrated from version %d to %d", oldVersion, version)
logger.Infof(ctx, "Database migrated from version %d to %d", oldVersion, version)
} else {
logger.Infof(context.Background(), "Database is up to date (version: %d)", version)
logger.Infof(ctx, "Database is up to date (version: %d)", version)
}
if dirty {
logger.Warnf(context.Background(), "Database is in dirty state! Manual intervention may be required.")
logger.Warnf(ctx, "Database is in dirty state! Manual intervention may be required.")
}
return nil
}
// recoverFromDirtyState attempts to recover from a dirty migration state
// by forcing to the previous version and allowing the migration to be retried
func recoverFromDirtyState(ctx context.Context, m *migrate.Migrate, dirtyVersion uint) error {
// Special case: if dirty at version 0 (init migration), we cannot go back further
// The only option is to force to version 0 and retry, but this requires the migration to be idempotent
if dirtyVersion == 0 {
logger.Warnf(ctx, "Database is in dirty state at version 0 (init migration). "+
"This is the initial migration, cannot rollback further. "+
"Will attempt to clear dirty flag and retry. "+
"Note: This only works if the init migration uses IF NOT EXISTS clauses.")
// Force to version -1 (no version) to allow re-running version 0
// This effectively tells migrate that no migrations have been applied
if err := m.Force(-1); err != nil {
return fmt.Errorf(
"failed to recover from dirty state at version 0. "+
"Manual intervention required:\n"+
"1. Check what was partially created in the database\n"+
"2. Either drop all created objects and retry, or\n"+
"3. Manually complete the migration and run: ./scripts/migrate.sh force 0\n"+
"Error: %w", err)
}
logger.Infof(ctx, "Cleared migration state, will retry from version 0")
return nil
}
forceVersion := int(dirtyVersion) - 1
logger.Warnf(ctx, "Database is in dirty state at version %d, attempting auto-recovery by forcing to version %d",
dirtyVersion, forceVersion)
// Force to previous version to clear dirty state
if err := m.Force(forceVersion); err != nil {
return fmt.Errorf("failed to force migration version during recovery: %w", err)
}
logger.Infof(ctx, "Successfully forced migration to version %d, migration will be retried", forceVersion)
return nil
}
// GetMigrationVersion returns the current migration version
func GetMigrationVersion() (uint, bool, error) {
dbURL := fmt.Sprintf(