Enhancement: Git Integration For Rollback Safety Branch
Hey guys! Let's dive into an enhancement that's going to make our blueprint rollbacks way safer and more reliable. Currently, the blueprint rollback API has a cool feature for creating safety branches, but it's not fully implemented with Git integration. So, when createBranch=true, we're gonna make sure it actually creates a Git branch before rolling back, giving us that extra layer of security for production rollbacks. This article will cover the existing issues and steps needed to resolve those issues by adding git integration to the rollback feature.
Issue: Rollback Safety Branch Creation Missing Git Integration
Description
The blueprint rollback API supports the optional creation of safety branches, but guess what? It's not fully hooked up yet! When you set createBranch=true, the API should be creating a Git branch before any rollback happens. This is crucial because it acts as a safety net, especially when we're dealing with production rollbacks. Imagine having a parachute before jumping – that's what this branch is for!
Current Behavior
Right now, if you try to rollback a blueprint and set createBranch=true, the API kinda shrugs. It'll log a note saying, "Branch creation not implemented yet," and then it'll just return a placeholder object. The rollback proceeds as if nothing happened, without actually creating that safety branch. Not ideal, right?
Expected Behavior
Here's what we want to happen when createBranch=true:
- Git Integration: The API needs to talk to a Git service (either our existing
GitHubServiceor a shiny newGitService). - Branch Creation: It should create a new Git branch with a descriptive name. Think something like
rollback-v{version}-{timestamp}. This makes it super easy to identify what the branch is for. - Return Branch Info: The API should then give us back some juicy details about the branch, including its name, URL, and the commit SHA.
- Rollback Time: Only after all that should the rollback operation proceed.
- Audit Logging: Finally, we need to log that the branch was created successfully. This gives us a clear audit trail of what happened.
Files Affected
To get this done, we'll be touching these files:
app/api/blueprints/[id]/rollback/route.ts– Specifically, lines 67-82. This is where the rollback logic lives.lib/services/github-service.ts– We might need to add some Git branch creation methods here.lib/env.ts– We might also need to tweak the Git repository configuration.
Current Code Location
Here's the snippet of code that's currently just a placeholder:
// app/api/blueprints/[id]/rollback/route.ts:67-82
// Optional: Create safety branch (would require Git integration)
let branchInfo = null;
if (createBranch) {
try {
// This would integrate with Git service to create a branch
// branchInfo = await GitService.createBranch(project.id, `rollback-v${targetVersion.version}-${Date.now()}`);
branchInfo = { note: "Branch creation not implemented yet" };
} catch (error) {
logger.warn("Failed to create safety branch", {
requestId: context.requestId,
blueprintId: id,
error: error instanceof Error ? error.message : String(error),
});
// Continue with rollback even if branch creation fails
}
}
See that comment? Yeah, that's where the magic should be happening.
Required Integration
Alright, let's get down to the nitty-gritty of what needs to be done.
1. Add Git Branch Creation Method to GitHubService
First, we need to add a createBranch method to our GitHubService. This method will handle the actual Git branch creation.
async createBranch(
projectId: number,
branchName: string,
baseBranch: string = 'main'
): Promise<BranchInfo> {
const project = await this.getProjectById(projectId);
const url = `${this.baseUrl}/repos/${project.gitHubRepo.full_name}/git/refs`;
// Get current branch SHA
const baseRef = await fetch(`${url}/heads/${baseBranch}`, {
headers: { Authorization: `token ${this.token}` }
});
const baseSha = (await baseRef.json()).object.sha;
// Create new branch
const response = await fetch(url, {
method: 'POST',
headers: {
Authorization: `token ${this.token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
ref: `refs/heads/${branchName}`,
sha: baseSha
})
});
return {
name: branchName,
url: `https://github.com/${project.gitHubRepo.full_name}/tree/${branchName}`,
sha: (await response.json()).object.sha,
createdAt: new Date().toISOString()
};
}
This method does the following:
- Fetches Project: Gets the project details using the
projectId. - Constructs URL: Creates the API endpoint URL for creating Git references (refs).
- Gets Base SHA: Retrieves the SHA of the base branch (defaulting to
main). This is the commit from which our new branch will be created. - Creates Branch: Sends a POST request to the Git API to create the new branch.
- Returns Branch Info: Returns an object containing the branch name, URL, SHA, and creation timestamp.
2. Integrate Branch Creation into Rollback API
Next, we need to integrate this new method into our rollback API.
if (createBranch) {
try {
branchInfo = await GitHubService.getInstance().createBranch(
project.id,
`rollback-v${targetVersion.version}-${Date.now()}`
);
logger.info("Safety branch created", {
requestId: context.requestId,
blueprintId: id,
branchName: branchInfo.name,
branchUrl: branchInfo.url
});
} catch (error {
logger.warn("Failed to create safety branch", {
requestId: context.requestId,
blueprintId: id,
error: error instanceof Error ? error.message : String(error),
});
// Continue with rollback even if branch creation fails
}
}
Here's what's happening in this snippet:
- Check
createBranch: We first check ifcreateBranchis set totrue. - Call
createBranch: If it is, we call thecreateBranchmethod fromGitHubService. - Log Success: If the branch creation is successful, we log it with all the relevant details.
- Handle Failure: If something goes wrong, we catch the error, log a warning, and continue with the rollback anyway. This is important so that a failed branch creation doesn't completely halt the rollback process.
3. Update Rollback Response to Include Branch Information
Finally, we need to update the rollback response to include the branch information.
return {
success: true,
data: {
blueprint: rolledBackBlueprint,
previousVersion: {
id: currentVersion.id,
version: currentVersion.version,
contentMarkdown: currentVersion.contentMarkdown,
},
branchInfo: branchInfo // Include branch information if created
}
};
This ensures that the client receives the branch information after a successful rollback, which can be super useful for tracking and verification.
Business Impact
This enhancement has several positive impacts on the business:
- Risk Reduction: Safety branches provide a quick way to recover if a rollback causes any issues. Think of it as an "undo" button for production.
- Enterprise Value: Enterprise customers expect comprehensive rollback capabilities, including safety mechanisms like this.
- Customer Experience: Reducing the anxiety associated with production rollbacks leads to a better overall customer experience. Knowing there's a safety net makes everyone breathe a little easier.
- Audit Trail: Branch creation provides an additional audit trail for rollback operations, making it easier to track changes and diagnose issues.
Severity Analysis
- Severity: P2 (Medium)
- Type: enhancement
- Reason: Strengthens an existing rollback feature with an important safety mechanism.
Acceptance Criteria
To make sure we've done this right, here are the acceptance criteria:
- [ ] Add
createBranchmethod toGitHubService - [ ] Integrate branch creation into rollback API
- [ ] Update rollback response to include branch information
- [ ] Handle branch creation failures gracefully (rollback continues)
- [ ] Add tests for branch creation
- [ ] Add tests for rollback with branch creation
- [ ] Verify all quality gates pass (0 vulnerabilities, 0 lint errors, 0 type errors, tests pass)
Testing Notes
Here's what we need to test:
- Branch is created when
createBranch=true - Branch name follows the pattern
rollback-v{version}-{timestamp} - Branch is created from the correct base branch
- Branch information is returned in the response
- Rollback proceeds even if branch creation fails
- Branch creation failure is logged appropriately
- Rollback without branch creation works as before
Related Features
This enhancement is related to these features:
- Blueprint version management (
app/api/blueprints/[id]/versions/route.ts) - Rollback API (
app/api/blueprints/[id]/rollback/route.ts) - GitHub repository creation (
lib/services/github-service.ts)
By implementing these changes, we'll significantly improve the safety and reliability of our blueprint rollbacks. This enhancement not only reduces risk but also enhances the overall customer experience and provides a more robust audit trail. Let's get this done, team!