GitHubSupport MSR

About MSR

Technical Evolution

How MSR evolved from a Firebase migration prototype into an ecosystem built around a shared core and database adapters.

Table of contents


For those who want to understand how MSR evolved technically, here's the detailed journey from an early Firebase prototype to the modular ecosystem built around MSR Core and database adapters.

The 2017 Prototype: Core Concepts

The original JavaScript implementation had several key innovations that survived into the modern version:

1. Automatic Backup & Rollback

Every migration started with an automatic backup:

JavaScript
// From the 2017 runner.js
migrate() {
  return Promise.all([
    this.dbUtil.backup(this.env),
    this.migrationService.getAll(),
    this.getAllMigrationScripts()
  ])
  .then(/* run migrations */)
  .catch(err => {
    console.info('-----------------> Failed');
    console.error(err);
    console.info('-----------------> Reverting DB');
    return this.dbUtil.restore(this.env, this.backupFile);
  })
}

This pattern - backup first, rollback on failure - eliminated the fear of running migrations.

2. Migration Tracking

Migrations were tracked in Firebase with full execution history:

JavaScript
// Migration file naming pattern
V201712051400_PROJ-462_add_email_verification.js

// Tracked in Firebase:
{
  timestamp: "201712051400",
  name: "V201712051400_PROJ-462_add_email_verification.js",
  username: "developer",
  startedAt: 1512486000000,
  finishedAt: 1512486045000,
  result: { status: "ok", updated: 156, skipped: 2 }
}

The tool compared executed migrations against local files to find new ones to run, then executed them sequentially in timestamp order.

3. EntityService Pattern

The breakthrough was abstracting database operations into a service layer:

JavaScript
// 2017: Clean, declarative migrations
class EntityService extends FirebaseService {
  constructor(db, root) {
    super(db);
    this.root = root;
  }

  updateAll(callback) {
    return this.getAll().then(entities => {
      let tasks = entities.map(entity => {
        let updated = callback(entity);
        if (!updated) return { key: entity.$key, status: 'skipped' };

        return this.save(updated).then(() => ({
          key: entity.$key,
          status: 'updated'
        }));
      });

      return Promise.all(tasks).then(results => {
        // Returns: { updated: [ids], skipped: [ids] }
      });
    });
  }
}

Migrations became readable and maintainable:

JavaScript
const userService = new EntityService(db, '/users');
await userService.updateAll(user => {
  if (!user.email) return null;
  user.emailVerified = false;
  user.emailLowercase = user.email.toLowerCase();
  return user;
});

This pattern proved so valuable it became core to MSR's architecture as the handler pattern.

The 2023 Rewrite: Architectural Transformation

From Monolith to Clean Architecture

2017: Everything was coupled to Firebase

JavaScript
// Tightly coupled
let runner = new Runner(firebase.database(), environment);
runner.migrate();

2023: Clean separation of concerns

TypeScript
// Core with adapter-defined database access
interface IDatabaseMigrationHandler {
  db: IDB;
  schemaVersion: ISchemaVersion;
  backup?: IBackup;
  getName(): string;
}

// Add a compatible adapter for another database
const executor = new MigrationScriptExecutor({ handler , config });

From JavaScript to TypeScript

Type safety transformed the codebase:

TypeScript
// 2023: Full type safety
interface IMigrationScript {
  name: string;
  timestamp: string;
  up(db: IDB, info: IMigrationInfo): Promise<string>;
  down?(db: IDB): Promise<string>;
}

interface IMigrationContext {
  handler: IDatabaseMigrationHandler;
  config: Config;
  logger: ILogger;
}

From Firebase-Only to Database-Agnostic

The key insight: separate what migrations do from how they talk to databases.

Architecture
MSR Core
├── Migration discovery and ordering
├── Execution workflow
├── Validation and tracking
├── Rollback strategies
└── Interface: IDatabaseMigrationHandler
         ↓
    ┌────┴──────────────┬────────────────────┐
    │                   │                    │
Firebase adapter   PostgreSQL adapter   Future adapters
  available        in development       via the contracts

This architecture means:

  • Core works with databases through compatible adapters
  • New adapters can implement the shared contracts
  • Shared workflow improvements benefit compatible adapters
  • Database-specific optimizations stay in adapters

Key Architectural Decisions

1. Polyglot Migrations

Mix SQL, TypeScript, and JavaScript in one project:

File layout
migrations/
  ├─ V202501010001_create_users_table.up.sql
  ├─ V202501010001_create_users_table.down.sql
  ├─ V202501020001_migrate_user_data.ts
  └─ V202501030001_add_indexes.up.sql

Why? Because SQL is perfect for schema changes, but TypeScript is better for complex data transformations.

2. Library-First Design

Return results instead of calling process.exit():

TypeScript
const result = await executor.up();

if (result.success) {
  console.log(`✅ Executed ${result.executed.length} migrations`);
  // Continue running your application
} else {
  console.error('❌ Migration failed:', result.errors);
  // Handle error based on your context
  if (isProduction) alertOpsTeam(result.errors);
  if (isCLI) process.exit(1);
}

Why? Web servers, serverless functions, and test suites need to handle migration results gracefully, not have the process killed.

3. Multiple Rollback Strategies

Different projects have different safety requirements:

TypeScript
enum RollbackStrategy {
  BACKUP,  // Automatic backup/restore
  DOWN,    // Use down() methods
  BOTH,    // Belt and suspenders
  NONE     // For append-only systems
}

Why? One size doesn't fit all. Let teams choose the right trade-off between safety and speed.

4. Custom Validators

Enforce team-specific rules before migrations run:

TypeScript
class RequireJiraTicketValidator implements IMigrationValidator {
  validate(script: IMigrationScript): ValidationResult {
    const hasTicket = /PROJ-\d+/.test(script.name);
    if (!hasTicket) {
      return {
        valid: false,
        message: `Migration ${script.name} must reference a Jira ticket`
      };
    }
    return { valid: true };
  }
}

Why? Catch mistakes in development, not production.

5. Execution Summary

Structured output for CI/CD pipelines:

JSON
{
  "success": true,
  "migrationsRun": 3,
  "duration": 4521,
  "schemaVersion": "202501040001",
  "migrations": [
    {
      "name": "V202501010001_create_users",
      "status": "completed",
      "duration": 1200
    }
  ]
}

Why? CI/CD systems need structured data, not console output.

Evolution Timeline

  1. October 31, 2023

    First commit to migration-script-runner

    • Extracted core from 2017 prototype
    • Reimagined architecture with TypeScript
    • Database-agnostic interfaces
  2. November 2, 2023

    First commit to msr-firebase

    • Validated architecture with Firebase adapter
    • Proved separation of concerns worked
  3. 2023-2025

    Dormant period

    • Published to npm
    • No active development
    • Waiting for the right moment
  4. 2025

    Active development resumes

    • SQL migration support added
    • Transaction management implemented
    • Custom validators framework
    • Execution summary for CI/CD
    • Enhanced documentation
    • Vision for ecosystem hub

Read how the original problem inspired MSR in Origin Story.