LocalData/Sources/LocalData/Migrations/SimpleLegacyMigration.swift
Matt Bruce e40205ef89 documentation v1
Signed-off-by: Matt Bruce <mbrucedogs@gmail.com>
2026-01-17 10:22:07 -06:00

64 lines
2.4 KiB
Swift

import Foundation
/// Simple 1:1 legacy migration from a single source key.
public struct SimpleLegacyMigration<Value: Codable & Sendable>: StorageMigration {
/// Destination key for migrated data.
public let destinationKey: StorageKey<Value>
/// Source key providing legacy data.
public let sourceKey: AnyStorageKey
/// Creates a migration from a legacy key to a destination key.
public init(destinationKey: StorageKey<Value>, 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
)
}
}