using System.Diagnostics; using System.Threading.Channels; using HaDbMigration.Configuration; using HaDbMigration.Models; using HaDbMigration.Services.Interfaces; using Microsoft.Extensions.Logging; namespace HaDbMigration.Services; public sealed class MigrationOrchestrator : IMigrationOrchestrator { private readonly MigrationOptions _options; private readonly ISqliteReaderService _readerService; private readonly IPostgresWriterService _writerService; private readonly ISchemaService _schemaService; private readonly IValidationService _validationService; private readonly ILogger _logger; private static readonly IReadOnlyList> MigrationGroups = [ // Group 1: independent leaf tables (no FKs referencing other data tables) [ TableDescriptors.EventTypes, TableDescriptors.EventData, TableDescriptors.StatesMeta, TableDescriptors.StateAttributes, TableDescriptors.StatisticsMeta, TableDescriptors.StatisticsRuns, TableDescriptors.SchemaChanges, TableDescriptors.MigrationChanges, ], // Group 2: tables with FKs to group 1 [ TableDescriptors.Events, TableDescriptors.States, TableDescriptors.Statistics, TableDescriptors.StatisticsShortTerm, TableDescriptors.RecorderRuns, ], ]; public MigrationOrchestrator( MigrationOptions options, ISqliteReaderService readerService, IPostgresWriterService writerService, ISchemaService schemaService, IValidationService validationService, ILogger logger) { _options = options; _readerService = readerService; _writerService = writerService; _schemaService = schemaService; _validationService = validationService; _logger = logger; } public async Task RunAsync(CancellationToken cancellationToken) { var stopwatch = Stopwatch.StartNew(); _logger.LogInformation("=== Home Assistant SQLite to PostgreSQL Migration ==="); _logger.LogInformation("Source: {SqlitePath}", _options.SqlitePath); _logger.LogInformation("Batch size: {BatchSize}", _options.BatchSize); if (_options.DryRun) { _logger.LogInformation("Mode: DRY RUN (no data will be written)"); } var allTables = TableDescriptors.GetMigrationOrder(); _logger.LogInformation("Validating PostgreSQL schema..."); var tablesExist = await _schemaService.ValidateTablesExistAsync(allTables, cancellationToken); if (!tablesExist) { _logger.LogError( "One or more required tables are missing. " + "Start Home Assistant pointing to the PostgreSQL database first to create the schema."); return; } _logger.LogInformation("All required tables exist in PostgreSQL"); if (_options.Truncate && !_options.DryRun) { _logger.LogInformation("Truncating target tables..."); await _schemaService.TruncateTablesAsync(allTables, cancellationToken); } foreach (var group in MigrationGroups) { await MigrateGroupInParallelAsync(group, cancellationToken); } if (!_options.DryRun) { _logger.LogInformation("Resetting PostgreSQL sequences..."); await _schemaService.ResetSequencesAsync(allTables, cancellationToken); } _logger.LogInformation("Validating migration results..."); var results = await _validationService.ValidateRowCountsAsync(allTables, cancellationToken); LogValidationResults(results); stopwatch.Stop(); _logger.LogInformation( "Migration completed in {Elapsed:F1} seconds", stopwatch.Elapsed.TotalSeconds); } private async Task MigrateGroupInParallelAsync( IReadOnlyList group, CancellationToken cancellationToken) { _logger.LogInformation( "Migrating table group: {Tables}", string.Join(", ", group.Select(t => t.TableName))); var tasks = group.Select(table => MigrateTableAsync(table, cancellationToken)).ToArray(); await Task.WhenAll(tasks); } private async Task MigrateTableAsync(TableDescriptor table, CancellationToken cancellationToken) { var tableStopwatch = Stopwatch.StartNew(); var channel = Channel.CreateBounded>( new BoundedChannelOptions(capacity: 4) { FullMode = BoundedChannelFullMode.Wait, SingleWriter = true, SingleReader = true, }); var readerTask = Task.Run( () => _readerService.ReadTableAsync(table, channel.Writer, cancellationToken), cancellationToken); var writerTask = Task.Run( () => _writerService.WriteTableAsync(table, channel.Reader, cancellationToken), cancellationToken); await Task.WhenAll(readerTask, writerTask); tableStopwatch.Stop(); _logger.LogInformation( "Table {Table} migrated in {Elapsed:F1}s", table.TableName, tableStopwatch.Elapsed.TotalSeconds); } private void LogValidationResults(IReadOnlyList results) { _logger.LogInformation("=== Validation Results ==="); var allMatch = true; foreach (var result in results) { if (result.IsMatch) { _logger.LogInformation( " {Table}: {Count} rows - OK", result.TableName, result.SourceRowCount); } else { _logger.LogWarning( " {Table}: Source={Source}, Target={Target} - MISMATCH", result.TableName, result.SourceRowCount, result.TargetRowCount); allMatch = false; } } if (allMatch) { _logger.LogInformation("All tables validated successfully"); } else { _logger.LogWarning("Some tables have row count mismatches - review the results above"); } } }