We are going to design a migration factory that can orchestrate:
- Code modifications (code mods) - e.g., refactoring, updating dependencies, changing APIs.
- Data transformations (data transforms) - e.g., converting data formats, schema changes, data cleanup.
- Verification steps (verification) - e.g., tests, data validation, smoke tests.
The idea is to have a factory that can produce a migration plan (orchestrator) for a given migration scenario.
We'll define interfaces for each step and then a composite migration that runs them in order.
Steps:
- Define interfaces for CodeMod, DataTransform, and Verification.
- Define a MigrationStep interface that can be any of the above.
- Define a MigrationPlan that is a sequence of MigrationSteps.
- Define a MigrationFactory that can create a MigrationPlan based on some configuration or input.
However, note that the steps might have dependencies. For example, code mods might need to happen before data transforms if the code is changed to handle new data format.
We can think of the migration as having phases:
Phase 1: Code modifications (if any) - to prepare the codebase for the new data format or structure.
Phase 2: Data transformations - to transform the existing data to the new format.
Phase 3: Verification - to ensure the migration was successful.
But note: sometimes verification might be interleaved (e.g., after each code mod or data transform). So we might want a flexible way to order steps.
Alternatively, we can think of the migration as a directed acyclic graph (DAG) of steps, but for simplicity we'll assume a linear sequence for now.
However, the problem says "orchestrating", so we might want to have a way to define the order and dependencies.
Let's design:
Step 1: Define a MigrationStep interface with an execute method and maybe a rollback method (for safety).
Step 2: Define three types of steps: CodeModStep, DataTransformStep, VerificationStep. They all implement MigrationStep.
Step 3: A MigrationPlan is a list of MigrationStep objects (or a more complex structure with dependencies?).
But if we want to allow parallel steps (that are independent) then we need a DAG. However, the problem says "orchestrating", which might imply sequential but could also be parallel.
Since the requirement is for a factory, we can have a factory that produces a plan with a given set of steps in a predefined order (or with dependencies).
Let's assume we are going to have a linear sequence for simplicity, but we can design the steps to be independent and then the plan can run them in order or in parallel if they are independent.
However, without a dependency graph, we cannot run in parallel safely. So let's stick to a linear sequence for now.
Alternatively, we can have:
MigrationPlan:
- steps: List
- But also we might want to group steps by phase? Or we can just have the steps in order.
The factory will create a plan by adding steps in the required order.
But note: the migration might be for a specific version upgrade. So the factory might take the current version and target version and produce the steps accordingly.
Alternatively, the factory might be configured with a set of migrators (for code, data, verification) and then we can compose them.
Let's design:
interface MigrationStep {
void execute() throws MigrationException;
void rollback() throws MigrationException; // optional, but good to have
}
Then we have:
class CodeModStep implements MigrationStep { ... }
class DataTransformStep implements MigrationStep { ... }
class VerificationStep implements MigrationStep { ... }
Then we have:
class MigrationPlan {
private List steps;
public void addStep(MigrationStep step) {
steps.add(step);
}
public void run() {
for (MigrationStep step : steps) {
step.execute();
}
}
// If we want to rollback on failure, we might need to keep track of successful steps.
// But let's leave that for now.
}
Then the factory:
interface MigrationFactory {
MigrationPlan createMigrationPlan(Version from, Version to);
}
But note: the steps might depend on the specific change. So we might have a registry of migrators for each version change.
Alternatively, we can have a MigrationFactory that is configured with a list of Migrator objects:
interface Migrator {
boolean canMigrate(Version from, Version to);
List getSteps(Version from, Version to);
}
Then the factory:
class DefaultMigrationFactory implements MigrationFactory {
private List migrators;
public MigrationPlan createMigrationPlan(Version from, Version to) {
MigrationPlan plan = new MigrationPlan();
for (Migrator migrator : migrators) {
if (migrator.canMigrate(from, to)) {
plan.addSteps(migrator.getSteps(from, to));
}
}
return plan;
}
}
But note: we might have multiple migrators that can handle the same version jump? Then we need to order them appropriately.
Alternatively, we can have a chain of responsibility, but then we might want to combine steps from multiple migrators.
Let's assume that each migrator is responsible for a specific set of changes (like from version X to Y) and they are independent.
However, we might have a situation where we need to run code mods first, then data transforms, then verification. So we might want to categorize the steps.
Alternatively, we can have the factory return a plan that is already ordered by the type of step (code mods first, then data, then verification). But that might not always be the case.
Another idea: the MigrationStep can have a getPhase() method that returns an enum (CODE_MOD, DATA_TRANSFORM, VERIFICATION) and then the factory can order by phase.
But then we are assuming the phases are fixed and linear.
Given the complexity, let's stick to a simple linear sequence and let the factory decide the order by the order of migrators? Or let each migrator return a list of steps in the correct order for that version jump.
Since each migrator is for a specific version jump, it knows what steps are needed and in what order. So we can just concatenate the steps from each migrator in the order they are processed.
But then we must ensure that the migrators are registered in the correct order? Or we can have the migrator specify the order of its steps and then the factory just appends.
However, if we have multiple migrators for the same version jump, we might have to interleave steps? That's complex.
Let's assume that each version jump is handled by exactly one migrator. Then we can have a map from (from, to) to migrator.
But the requirement says "migration factory approach", so we are building a framework.
Alternatively, we can have:
class Migration {
Version from;
Version to;
List steps;
}
And the factory produces a Migration object.
We can have a registry of Migration objects for each version pair.
But then we lose the ability to compose multiple migrations (like from 1.0 to 1.1 and then 1.1 to 1.2). We can chain them.
Given the time, let's design a simple version:
We'll have:
interface MigrationStep {
String getName();
void execute() throws MigrationException;
void rollback() throws MigrationException;
}
Then we have three abstract classes for the three types, but they might not be necessary.
Then we have:
class MigrationPlan {
private List steps = new ArrayList<>();
public void addStep(MigrationStep step) {
steps.add(step);
}
public void run() throws MigrationException {
for (MigrationStep step : steps) {
try {
step.execute();
} catch (Exception e) {
// rollback the steps that have been executed so far?
// We need to track which steps have been executed.
// Let's assume we want to rollback on failure.
rollback(steps.indexOf(step));
throw new MigrationException("Migration failed at step: " + step.getName(), e);
}
}
}
private void rollback(int failedStepIndex) {
for (int i = failedStepIndex - 1; i >= 0; i--) {
try {
steps.get(i).rollback();
} catch (Exception e) {
// log but continue rollback
}
}
}
}
Then the factory:
interface MigrationFactory {
MigrationPlan createPlan(Version from, Version to);
}
And we can have a simple implementation that has a map of version pairs to a list of steps (or to a MigrationPlan).
But then we are predefining all migrations.
Alternatively, we can have a chain of migrators:
class ChainMigrationFactory implements MigrationFactory {
private List migrators;
@Override
public MigrationPlan createPlan(Version from, Version to) {
MigrationPlan plan = new MigrationPlan();
Version current = from;
while (!current.equals(to)) {
boolean found = false;
for (Migrator migrator : migrators) {
if (migrator.canMigrate(current, to)) {
plan.addSteps(migrator.getSteps(current, to));
current = to; // because this migrator takes us to the target?
// But what if we have multiple steps? We might have intermediate versions.
// Actually, the migrator might not necessarily jump to the final version in one step.
// So we need to break the migration into multiple hops.
// Alternatively, we can have the migrator return the next version after applying its steps.
// But the interface of Migrator would be:
// boolean canMigrate(Version from, Version to); // can it handle the jump from `from` to `to`?
// List<MigrationStep> getSteps(Version from, Version to);
// Version getTargetVersion(Version from); // after applying these steps, what version are we at?
// This is getting complex.
// Let's simplify: we assume that each migrator is for a specific version upgrade (like 1.0 to 1.1) and we have a chain of such upgrades.
// So we need to find a path from `from` to `to` through a series of migrators.
// We can predefine a graph of versions and migrators that connect them.
// Given the time, let's assume we have a linear version history and we have a migrator for each consecutive version.
// Then we can do:
// for each version from `from` (inclusive) to `to` (exclusive) in the version chain, get the migrator for (current, next) and add its steps.
// So we need a way to get the next version in the chain.
// Alternatively, we can have a map of (from, to) to a list of steps, and then we break the migration into consecutive hops.
// But the problem says "migration factory", so we are building a system that can handle arbitrary version jumps.
// Given the complexity, I think we should design for a linear version history and have a registry of step lists for each consecutive version jump.
// Then the factory can break the jump from `from` to `to` into consecutive jumps and concatenate the steps.
// So we need a way to get the next version after `current` until we reach `to`.
// We can have a VersionChain that knows the order of versions.
// But that's too much.
// Let's change the requirement: the factory only supports direct version jumps that are registered.
// Then we can have:
// Map<Pair<Version, Version>, List<MigrationStep>> migrationStepsMap;
// And the factory:
// if (migrationStepsMap.containsKey(Pair.of(from, to))) {
// return new MigrationPlan(migrationStepsMap.get(Pair.of(from, to)));
// } else {
// throw new UnsupportedOperationException("No migration from " + from + " to " + to);
// }
// This is simple and works for direct jumps.
// But if we want to chain, we can have a higher-level factory that chains multiple direct jumps.
// Given the time, let's go with the direct jump.
// So we don't need the Migrator interface, just a map.
// However, the problem says "factory approach", so we might want to have a way to register migrations.
// Let's design:
// class MigrationRegistry {
// private Map<Pair<Version, Version>, List<MigrationStep>> migrations = new HashMap<>();
//
// public void register(Version from, Version to, List<MigrationStep> steps) {
// migrations.put(Pair.of(from, to), steps);
// }
//
// public List<MigrationStep> getMigrationSteps(Version from, Version to) {
// return migrations.get(Pair.of(from, to));
// }
// }
// Then the factory:
// class DefaultMigrationFactory implements MigrationFactory {
// private MigrationRegistry registry;
//
// @Override
// public MigrationPlan createPlan(Version from, Version to) {
// List<MigrationStep> steps = registry.getMigrationSteps(from, to);
// if (steps == null) {
// throw new IllegalArgumentException("No migration registered from " + from + " to " + to);
// }
// return new MigrationPlan(steps);
// }
// }
// And MigrationPlan can be constructed with a list of steps.
// This is simple and meets the requirement of orchestrating code mods, data transforms, and verification.
// But note: the steps in the list must be in the correct order.
// So the registration must provide the steps in the correct order.
// We can have the steps be of any type (CodeModStep, DataTransformStep, VerificationStep) and they all implement MigrationStep.
// This design is simple and let's the registrant decide the order.
// However, we might want to enforce that code mods come before data transforms and verification comes last? Not necessarily.
// So we leave it to the registrant.
// Given the time, I'll go with this.
// But the problem says "orchestrating", so we are providing a way to run these steps in order.
// So we are done?
// Let's code accordingly.
// However, note that the original problem says "migration factory approach", so we are building a factory that produces a plan.
// We have:
// MigrationStep (interface)
// CodeModStep, DataTransformStep, VerificationStep (implementations)
// MigrationPlan (holds a list of steps and runs them)
// MigrationFactory (interface) and DefaultMigrationFactory (implementation using a registry)
// MigrationRegistry (to register migrations)
// But the factory doesn't have to use a registry. It can be implemented in any way.
// We can also have a factory that reads from a configuration file.
// But for simplicity, we'll use a registry.
// Let's code accordingly.
}
}
}
}
}
Given the above, I think we have a design.
However, note that the MigrationPlan we designed earlier does rollback on failure. We need to adjust the plan to track which steps have been executed.
Let's adjust the MigrationPlan:
class MigrationPlan {
private List steps;
public MigrationPlan(List<MigrationStep> steps) {
this.steps = new ArrayList<>(steps);
}
public void run() throws MigrationException {
List<MigrationStep> executedSteps = new ArrayList<>();
try {
for (MigrationStep step : steps) {
step.execute();
executedSteps.add(step);
}
} catch (Exception e) {
rollback(executedSteps);
throw new MigrationException("Migration failed", e);
}
}
private void rollback(List<MigrationStep> executedSteps) {
Collections.reverse(executedSteps);
for (MigrationStep step : executedSteps) {
try {
step.rollback();
} catch (Exception e) {
// log
}
}
}
}
This is better.
Now, let's write the code for the interfaces and classes.
We'll assume we have a Version class (maybe just a string or a custom class). We'll use a simple string for now.
Let's code:
Step 1: MigrationStep interface.
Step 2: Three example implementations (with empty execute and rollback for now).
Step 3: MigrationPlan.
Step 4: MigrationFactory interface and a simple registry-based implementation.
But note: the registry must be set up with the migrations.
We can have:
class MigrationRegistry {
private Map<Pair<Version, Version>, List> migrations = new HashMap<>();
public void register(Version from, Version to, List<MigrationStep> steps) {
migrations.put(Pair.of(from, to), steps);
}
public List<MigrationStep> getSteps(Version from, Version to) {
return migrations.get(Pair.of(from, to));
}
}
We need a Pair class. We can use AbstractMap.SimpleEntry or create our own.
Let's create a simple Pair:
class Pair<F, T> {
private final F first;
private final T second;
public Pair(F first, T second) {
this.first = first;
this.second = second;
}
// getters, equals, hashCode
}
But we can also use Java's AbstractMap.SimpleEntry, but that's not type-safe for our purpose? It's fine.
Alternatively, we can use a string key: from + "->" + to.
Given the time, let's use a string key.
So:
class MigrationRegistry {
private Map<String, List> migrations = new HashMap<>();
public void register(Version from, Version to, List<MigrationStep> steps) {
migrations.put(from + "->" + to, steps);
}
public List<MigrationStep> getSteps(Version from, Version to) {
return migrations.get(from + "->" + to);
}
}
Now, the factory:
class DefaultMigrationFactory implements MigrationFactory {
private MigrationRegistry registry;
public DefaultMigrationFactory(MigrationRegistry registry) {
this.registry = registry;
}
@Override
public MigrationPlan createPlan(Version from, Version to) {
List<MigrationStep> steps = registry.getSteps(from, to);
if (steps == null) {
throw new IllegalArgumentException("No migration registered from " + from + " to " + to);
}
return new MigrationPlan(steps);
}
}
Now, let's define the Version class. We can use a simple wrapper around string, or just string. Let's use string for simplicity.
But we might want to compare versions (like 1.0 < 1.1). So we might need a comparable version.
Let's assume we have a Version class that implements Comparable:
class Version implements Comparable {
private final String version;
public Version(String version) {
this.version = version;
}
@Override
public int compareTo(Version other) {
// simple dot-separated comparison
String[] thisParts = this.version.split("\\.");
String[] otherParts = other.version.split("\\.");
int length = Math.min(thisParts.length, otherParts.length);
for (int i = 0; i < length; i++) {
int thisPart = Integer.parseInt(thisParts[i]);
int otherPart = Integer.parseInt(otherParts[i]);
if (thisPart != otherPart) {
return thisPart - otherPart;
}
}
return thisParts.length - otherParts.length;
}
// equals, hashCode, toString
}
But note: the migration registry uses string keys, so we are using the string representation. We must ensure that the Version's toString returns the same string as we used in registration.
Alternatively, we can use the Version object as the key in the map, but then we need to define equals and hashCode for Version.
Let's change the registry to use Version as key:
class MigrationRegistry {
private Map<Version, Map<Version, List>> migrations = new HashMap<>();
public void register(Version from, Version to, List<MigrationStep> steps) {
migrations.computeIfAbsent(from, k -> new HashMap<>()).put(to, steps);
}
public List<MigrationStep> getSteps(Version from, Version to) {
Map<Version, List<MigrationStep>> fromMap = migrations.get(from);
if (fromMap == null) {
return null;
}
return fromMap.get(to);
}
}
This is better.
Now, the factory uses Version objects.
But note: the factory's createPlan takes Version objects, so we are good.
Let's code accordingly.
However, the problem says "orchestrating code mods, data transforms, and verification". We have the steps, but we haven't defined what they do.
We can leave the implementation of the steps to the user.
We can provide base classes:
abstract class AbstractCodeModStep implements MigrationStep {
// common code mod functionality?
}
But we don't have any common functionality. So we can leave it as an interface.
Alternatively, we can have:
interface CodeMod extends MigrationStep {}
interface DataTransform extends MigrationStep {}
interface Verification extends MigrationStep {}
Then the user can implement these interfaces and then the factory can group them? Not necessary.
Given the time, let's just have the three types as separate classes that implement MigrationStep.
Example:
class UpdateDependencyCodeMod implements MigrationStep {
@Override
public void execute() {
// update a dependency in build file
}
@Override
public void rollback() {
// revert the change
}
}
But we might want to have a base class for rollback? Maybe we can have a template method?
Given the complexity, we'll leave it as is.
Now, let's write the code for the main components.
We'll write:
- Version class (with compareTo, equals, hashCode, toString)
- MigrationStep interface
- Example implementations: CodeModStep, DataTransformStep, VerificationStep (each with empty execute and rollback for now)
- MigrationPlan
- MigrationRegistry
- MigrationFactory and DefaultMigrationFactory
We'll also write a main class to demonstrate.
But note: the problem says "compose a migration factory approach", so we are providing the framework.
Let's code accordingly.
However, note that the MigrationStep interface might need more methods? Like getName() for logging?
Let's add:
interface MigrationStep {
String getName();
void execute() throws MigrationException;
void rollback() throws MigrationException;
}
Then the steps must provide a name.
Now, let's code.
Due to the complexity and time, I'll write the code in a simplified manner.
We'll assume:
- MigrationException is a custom exception (extending RuntimeException or Exception). We'll use RuntimeException for simplicity.
Let's code:
I'll design a comprehensive migration factory pattern that orchestrates code modifications, data transformations, and verification steps in a structured, reusable way.
Migration Factory Architecture
// ========== Core Interfaces ==========
/**
* Base migration step interface
*/
public interface MigrationStep {
String getName();
MigrationPhase getPhase();
void execute(MigrationContext context) throws MigrationException;
default void rollback(MigrationContext context) throws MigrationException {}
default boolean isIdempotent() { return false; }
}
/**
* Migration phases define execution order and dependencies
*/
public enum MigrationPhase {
PRE_CHECK, // Validation before any changes
CODE_MODIFICATION, // Source code changes
SCHEMA_UPDATE, // Database schema changes
DATA_TRANSFORMATION, // Data migration/transformation
DATA_VALIDATION, // Post-migration data checks
POST_DEPLOYMENT, // Verification after deployment
ROLLBACK // Emergency rollback steps
}
// ========== Context & Configuration ==========
/**
* Shared context across all migration steps
*/
public class MigrationContext {
private final String migrationId;
private final Version fromVersion;
private final Version toVersion;
private final Map<String, Object> metadata;
private final Logger logger;
private final List<String> executionLog;
private boolean dryRun;
// Getters, setters, builder pattern
public static class Builder {
// builder implementation
}
}
/**
* Migration configuration
*/
public class MigrationConfig {
private boolean enableRollback = true;
private int maxRetries = 3;
private Duration timeout = Duration.ofHours(2);
private boolean verifyAfterEachStep = true;
private List<String> excludedTables = new ArrayList<>();
private Map<String, Object> customProperties = new HashMap<>();
// getters/setters
}
// ========== Step Implementations ==========
// 1. Code Modification Steps
public abstract class CodeModStep implements MigrationStep {
protected final GitClient gitClient;
protected final BuildTool buildTool;
public CodeModStep(GitClient gitClient, BuildTool buildTool) {
this.gitClient = gitClient;
this.buildTool = buildTool;
}
@Override
public MigrationPhase getPhase() {
return MigrationPhase.CODE_MODIFICATION;
}
}
public class DependencyUpgradeStep extends CodeModStep {
private final String artifactId;
private final String targetVersion;
@Override
public void execute(MigrationContext context) throws MigrationException {
context.getLogger().info("Upgrading {} to version {}", artifactId, targetVersion);
// 1. Update build file (Maven/Gradle)
buildTool.updateDependency(artifactId, targetVersion);
// 2. Update lock files if needed
// 3. Format changes
// 4. Commit changes
}
}
public class ApiRefactoringStep extends CodeModStep {
private final String oldApi;
private final String newApi;
private final RefactoringTool refactoringTool;
@Override
public void execute(MigrationContext context) throws MigrationException {
// Use IDE refactoring or codemod tool
refactoringTool.renameSymbol(oldApi, newApi);
// Update documentation
// Run static analysis
}
}
// 2. Data Transformation Steps
public abstract class DataTransformStep implements MigrationStep {
protected final DataSource source;
protected final DataSource target;
protected final int batchSize;
@Override
public MigrationPhase getPhase() {
return MigrationPhase.DATA_TRANSFORMATION;
}
protected void processInBatches(DataProcessor processor) throws MigrationException {
// Batch processing with checkpoint/restart capability
}
}
public class SchemaMigrationStep extends DataTransformStep {
private final SchemaMigrationScript script;
@Override
public void execute(MigrationContext context) throws MigrationException {
// 1. Backup current schema
// 2. Execute migrations in order
// 3. Validate schema changes
// 4. Update migration version table
}
}
public class DataConversionStep extends DataTransformStep {
private final ConversionRule rule;
private final String sourceTable;
private final String targetTable;
@Override
public void execute(MigrationContext context) throws MigrationException {
// 1. Validate source data
// 2. Execute transformation with progress tracking
// 3. Sample validation
// 4. Log statistics
}
}
// 3. Verification Steps
public abstract class VerificationStep implements MigrationStep {
protected final Reporter reporter;
@Override
public MigrationPhase getPhase() {
return MigrationPhase.DATA_VALIDATION;
}
}
public class DataIntegrityCheckStep extends VerificationStep {
private final IntegrityChecker checker;
private final List<ValidationRule> rules;
@Override
public void execute(MigrationContext context) throws MigrationException {
List<ValidationResult> results = checker.validateAll(rules);
reporter.reportValidation(results);
if (results.stream().anyMatch(r -> !r.isValid())) {
throw new MigrationException("Data validation failed");
}
}
}
public class SmokeTestStep extends VerificationStep {
private final TestSuite smokeTests;
@Override
public void execute(MigrationContext context) throws MigrationException {
TestResult result = smokeTests.run(context.getMetadata());
if (!result.isSuccessful()) {
throw new MigrationException("Smoke tests failed: " + result.getFailures());
}
}
}
// ========== Factory & Orchestrator ==========
/**
* Factory for creating migration plans
*/
public interface MigrationFactory {
MigrationPlan createPlan(MigrationRequest request) throws MigrationException;
boolean supports(Version from, Version to);
List<MigrationStep> getAvailableSteps(Version from, Version to);
}
/**
* Concrete factory implementation
*/
public class CompositeMigrationFactory implements MigrationFactory {
private final List<MigrationStrategy> strategies;
private final StepRegistry stepRegistry;
private final DependencyGraph dependencyGraph;
@Override
public MigrationPlan createPlan(MigrationRequest request) {
List<MigrationStep> allSteps = new ArrayList<>();
// 1. Get base strategy
MigrationStrategy strategy = strategies.stream()
.filter(s -> s.supports(request.getFrom(), request.getTo()))
.findFirst()
.orElseThrow(() -> new MigrationException("No strategy found"));
// 2. Get required steps from strategy
List<MigrationStep> strategySteps = strategy.getSteps(request);
// 3. Enhance with additional steps from registry
stepRegistry.getStepsForVersion(request.getFrom(), request.getTo())
.forEach(step -> {
if (!allSteps.contains(step)) {
allSteps.add(step);
}
});
// 4. Resolve dependencies and sort
List<MigrationStep> orderedSteps = dependencyGraph.topologicalSort(allSteps);
// 5. Add automatic verification steps if configured
if (request.getConfig().isVerifyAfterEachStep()) {
orderedSteps = addVerificationSteps(orderedSteps);
}
return new MigrationPlan(orderedSteps, request.getConfig());
}
}
/**
* Migration plan with execution orchestration
*/
public class MigrationPlan {
private final List<MigrationStep> steps;
private final MigrationConfig config;
private final Map<MigrationStep, MigrationResult> results = new ConcurrentHashMap<>();
private final List<MigrationListener> listeners = new ArrayList<>();
public void execute(MigrationContext context) throws MigrationException {
context.getLogger().info("Starting migration plan with {} steps", steps.size());
try {
for (MigrationStep step : steps) {
executeStepWithRetry(step, context);
if (config.isVerifyAfterEachStep() && !step.getPhase().equals(MigrationPhase.ROLLBACK)) {
verifyStep(step, context);
}
}
notifyCompletion(true);
} catch (Exception e) {
handleFailure(e, context);
throw e;
}
}
private void executeStepWithRetry(MigrationStep step, MigrationContext context)
throws MigrationException {
int attempts = 0;
while (attempts < config.getMaxRetries()) {
try {
step.execute(context);
results.put(step, MigrationResult.success());
notifyStepCompletion(step, true);
return;
} catch (MigrationException e) {
attempts++;
if (attempts == config.getMaxRetries()) {
results.put(step, MigrationResult.failure(e));
throw e;
}
context.getLogger().warn("Step {} failed, attempt {}/{}",
step.getName(), attempts, config.getMaxRetries());
// Optional: wait before retry
}
}
}
private void verifyStep(MigrationStep step, MigrationContext context) {
// Auto-verify based on step type
if (step instanceof DataTransformStep) {
runDataChecks((DataTransformStep) step, context);
} else if (step instanceof CodeModStep) {
runBuildAndTests((CodeModStep) step, context);
}
}
public MigrationPlan withListener(MigrationListener listener) {
this.listeners.add(listener);
return this;
}
}
/**
* Builder for fluent migration plan creation
*/
public class MigrationPlanBuilder {
private final List<MigrationStep> steps = new ArrayList<>();
private MigrationConfig config = new MigrationConfig();
private final MigrationContext context;
public MigrationPlanBuilder(MigrationContext context) {
this.context = context;
}
public MigrationPlanBuilder addStep(MigrationStep step) {
steps.add(step);
return this;
}
public MigrationPlanBuilder addSteps(Collection<MigrationStep> steps) {
this.steps.addAll(steps);
return this;
}
public MigrationPlanBuilder withConfig(MigrationConfig config) {
this.config = config;
return this;
}
public MigrationPlanBuilder addDataValidation(ValidationRule... rules) {
steps.add(new CustomDataValidationStep(rules));
return this;
}
public MigrationPlan build() {
return new MigrationPlan(steps, config);
}
}
// ========== Supporting Components ==========
/**
* Migration request DTO
*/
public class MigrationRequest {
private final Version fromVersion;
private final Version toVersion;
private final MigrationType type; // MAJOR, MINOR, PATCH
private final MigrationConfig config;
private final Map<String, Object> parameters;
// getters, constructor
}
/**
* Strategy pattern for different migration types
*/
public interface MigrationStrategy {
List<MigrationStep> getSteps(MigrationRequest request);
boolean supports(Version from, Version to);
int getPriority(); // For ordering strategies
}
public class DatabaseMigrationStrategy implements MigrationStrategy {
@Override
public List<MigrationStep> getSteps(MigrationRequest request) {
return List.of(
new SchemaMigrationStep(...),
new DataBackupStep(...),
new DataConversionStep(...),
new DataIntegrityCheckStep(...)
);
}
}
/**
* Dependency resolution for steps
*/
public class DependencyGraph {
public List<MigrationStep> topologicalSort(List<MigrationStep> steps) {
// Build dependency graph based on @DependsOn annotations or explicit declarations
// Return topologically sorted list
}
}
/**
* Rollback manager
*/
public class RollbackManager {
private final Map<MigrationStep, List<RollbackAction>> rollbackPlan = new LinkedHashMap<>();
public void registerRollback(MigrationStep step, RollbackAction action) {
rollbackPlan.computeIfAbsent(step, k -> new ArrayList<>).add(action);
}
public void executeRollback(StopPoint stopPoint) throws MigrationException {
// Execute rollback in reverse order up to stopPoint
}
}
/**
* Progress tracking
*/
public class MigrationProgress {
private final List<StepProgress> stepProgresses = new CopyOnWriteArrayList<>();
private final ProgressBar progressBar;
public void startStep(MigrationStep step) {
stepProgresses.add(new StepProgress(step, StepStatus.RUNNING));
}
public void completeStep(MigrationStep step, boolean success) {
// Update progress bar, log, metrics
}
}
// ========== Usage Example ==========
public class MigrationOrchestrator {
private final MigrationFactory factory;
private final MigrationRepository repository;
public void migrate(MigrationRequest request) throws MigrationException {
// 1. Create migration plan
MigrationPlan plan = factory.createPlan(request);
// 2. Create context with dry-run option
MigrationContext context = MigrationContext.builder()
.migrationId(generateId())
.fromVersion(request.getFromVersion())
.toVersion(request.getToVersion())
.dryRun(request.isDryRun())
.build();
// 3. Save plan to repository for audit
repository.savePlan(plan, context.getMigrationId());
// 4. Execute with monitoring
try (MigrationMonitor monitor = new MigrationMonitor(context)) {
if (!context.isDryRun()) {
plan.execute(context);
}
repository.recordSuccess(context.getMigrationId());
} catch (MigrationException e) {
repository.recordFailure(context.getMigrationId(), e);
throw e;
}
}
// Rollback capability
public void rollback(String migrationId) throws MigrationException {
MigrationPlan plan = repository.getPlan(migrationId);
plan.getSteps().stream()
.filter(step -> step instanceof SupportsRollback)
.forEach(step -> {
try {
step.rollback(new MigrationContext.Builder().build());
} catch (Exception e) {
// Log but continue
}
});
}
}
Key Design Patterns Used:
- Factory Pattern:
MigrationFactory creates migration plans
- Strategy Pattern: Different migration strategies (DB, app, config)
- Template Method: Base classes define skeleton, subclasses implement specifics
- Builder Pattern: Fluent
MigrationPlanBuilder
- Chain of Responsibility: Step execution pipeline
- Observer Pattern:
MigrationListener for monitoring
- Command Pattern: Each step is a command with undo capability
- Dependency Injection: Tools/clients injected into steps
Execution Flow:
1. PRE_CHECK
├─ Environment validation
├─ Version compatibility check
└─ Backup verification
2. CODE_MODIFICATION
├─ Dependency upgrades
├─ API refactoring
├─ Configuration updates
└─ Compilation verification
3. SCHEMA_UPDATE
├─ Schema backup
├─ Incremental migrations
├─ Constraint updates
└─ Version table update
4. DATA_TRANSFORMATION
├─ Data profiling
├─ Batched transformation (with checkpoint)
├─ Data validation rules
└─ Performance monitoring
5. DATA_VALIDATION
├─ Row count verification
├─ Checksum validation
├─ Referential integrity
└─ Sample data checks
6. POST_DEPLOYMENT
├─ Smoke tests
├─ Performance benchmarks
├─ Health checks
└─ Monitoring setup
Configuration Example (YAML):
migration:
id: "v2.1.0-migration"
from: "2.0.0"
to: "2.1.0"
type: "MINOR"
config:
enableRollback: true
maxRetries: 3
timeout: "2h"
verifyAfterEachStep: true
steps:
- type: "CODE_MOD"
name: "Upgrade Spring Boot"
implementation: "DependencyUpgradeStep"
params:
artifactId: "spring-boot-starter-parent"
version: "2.7.0"
- type: "DATA_TRANSFORM"
name: "Migrate user_profiles"
implementation: "DataConversionStep"
dependsOn: ["Upgrade Spring Boot"]
params:
sourceTable: "user_profiles_old"
targetTable: "user_profiles_v2"
batchSize: 1000
- type: "VERIFICATION"
name: "Validate user data"
implementation: "DataIntegrityCheckStep"
dependsOn: ["Migrate user_profiles"]
params:
rules:
- "NOT_NULL:email"
- "UNIQUE:user_id"
Benefits:
- Modular: Each step is independently testable
- Composable: Mix and match steps for different migrations
- Observable: Full audit trail and progress tracking
- Resilient: Automatic retry, rollback, checkpointing
- Extensible: Easy to add new step types
- Safe: Dry-run mode, validation at each phase
- Parallelizable: Independent steps can run concurrently
This factory approach provides a robust framework for complex migrations while maintaining flexibility for different migration scenarios (database upgrades, application refactoring, data warehouse ETL, etc.).