LocalData/Sources/LocalData/Migrations/SimpleLegacyMigration.swift
Matt Bruce 281c9d5e91 migration
Signed-off-by: Matt Bruce <mbrucedogs@gmail.com>
2026-01-16 13:47:12 -06:00

63 lines
2.3 KiB
Swift

import Foundation
/// Simple 1:1 legacy migration.
public struct SimpleLegacyMigration<Destination: StorageKey>: StorageMigration {
public typealias DestinationKey = Destination
public let destinationKey: Destination
public let sourceKey: AnyStorageKey
public init(destinationKey: Destination, sourceKey: AnyStorageKey) {
self.destinationKey = destinationKey
self.sourceKey = sourceKey
}
public func shouldMigrate(using router: StorageRouter, context: MigrationContext) async throws -> Bool {
guard try await router.shouldAllowMigration(for: destinationKey, context: context) else {
return false
}
if try await router.exists(destinationKey) {
return false
}
return try await router.exists(descriptor: sourceKey.descriptor)
}
public func migrate(using router: StorageRouter, context: MigrationContext) async throws -> MigrationResult {
let startTime = Date()
var errors: [MigrationError] = []
var migratedCount = 0
do {
guard let sourceData = try await router.retrieve(for: sourceKey.descriptor) else {
return MigrationResult(success: false, errors: [.sourceDataNotFound])
}
let unsecuredData = try await router.applySecurity(
sourceData,
for: sourceKey.descriptor,
isEncrypt: false
)
let value = try router.deserialize(unsecuredData, with: destinationKey.serializer)
try await router.set(value, for: destinationKey)
try await router.delete(for: sourceKey.descriptor)
migratedCount = 1
Logger.info("!!! [MIGRATION] Successfully migrated from '\(sourceKey.descriptor.name)' to '\(destinationKey.name)'")
} catch {
let storageError = error as? StorageError ?? .fileError(error.localizedDescription)
errors.append(.storageFailed(storageError))
Logger.error("!!! [MIGRATION] Failed to migrate from '\(sourceKey.descriptor.name)': \(error)")
}
let duration = Date().timeIntervalSince(startTime)
return MigrationResult(
success: errors.isEmpty,
migratedCount: migratedCount,
errors: errors,
duration: duration
)
}
}