Skip to content

Conversation

@sixcolors
Copy link
Member

@sixcolors sixcolors commented Dec 1, 2025

Summary

This PR adds two critical migrations to fix session-related issues identified in gofiber/recipes#3841:

1. Storage Version Migration

  • Migrates storage package imports to their latest versions
  • Handles v2 → v3 upgrades for redis and postgres
  • Handles unversioned → v2 upgrades for 17 storage adapters (sqlite3, mysql, mongodb, etc.)
  • Leaves v1/unversioned packages unchanged (aerospike, nats, cassandra, etc.)
  • Comprehensive version mapping based on actual package versions from gofiber/storage

2. Session Release Migration

  • Adds defer sess.Release() for legacy Store Pattern in Fiber v3
  • Detects sess, err := store.Get(c) patterns
  • Intelligently inserts defer after error check blocks
  • Handles multi-line error checks and various formatting styles
  • Critical: v3 Store Pattern requires manual session cleanup (unlike v2)

Test Coverage

  • 270 tests passing (100% pass rate)
  • 5 comprehensive test scenarios for storage versions
  • 4 test scenarios for session release
  • 0 linting issues (golangci-lint v2.6.2)
  • ✅ Idempotent - won't re-migrate or create duplicates

Files Changed

  • cmd/internal/migrations/v3/storage_versions.go - Storage version migration logic
  • cmd/internal/migrations/v3/storage_versions_test.go - 5 test cases
  • cmd/internal/migrations/v3/session_release.go - Session release migration logic
  • cmd/internal/migrations/v3/session_release_test.go - 4 test cases
  • cmd/internal/migrations/lists.go - Integration into migration sequence

Storage Adapters Covered

v3 adapters (2): postgres, redis
v2 adapters (17): arangodb, azureblob, badger, bbolt, couchbase, dynamodb, etcd, memcache, memory, mongodb, mssql, mysql, pebble, ristretto, s3, sqlite3
v1/unversioned (13+): aerospike, cassandra, clickhouse, cloudflarekv, coherence, leveldb, minio, mockstorage, nats, neo4j, rueidis, scylladb, surrealdb, valkey

Related Issues

Fixes gofiber/recipes#3841

Summary by CodeRabbit

  • New Features

    • Introduced new automated migration steps that optimize storage configuration management and improve session resource cleanup during system upgrades.
    • Enhanced upgrade process with improved handling of storage versions and package dependency resolution.
  • Tests

    • Added comprehensive test coverage for new migration features to ensure proper execution and reliability across various upgrade scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

This commit adds two critical migrations to fix session-related issues in PR #3841:

1. Storage Version Migration (storage_versions.go):
   - Migrates storage package imports to their latest versions
   - Handles v2 → v3 upgrades for redis and postgres
   - Handles unversioned → v2 upgrades for 17 adapters
   - Leaves v1/unversioned packages unchanged
   - Comprehensive version mapping based on actual package versions

2. Session Release Migration (session_release.go):
   - Adds defer sess.Release() for legacy Store Pattern in Fiber v3
   - Detects sess, err := store.Get(c) patterns
   - Intelligently inserts defer after error check blocks
   - Idempotent - won't add duplicate defer statements

Both migrations include comprehensive test coverage:
- 5 test scenarios for storage versions
- 4 test scenarios for session release
- All 270 tests passing
- 0 linting issues

Fixes: gofiber/recipes#3841
@sixcolors sixcolors requested a review from a team as a code owner December 1, 2025 17:24
@welcome
Copy link

welcome bot commented Dec 1, 2025

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

@sixcolors sixcolors requested review from ReneWerner87, efectn and gaby and removed request for a team December 1, 2025 17:24
@ReneWerner87 ReneWerner87 added the ✏️ Feature New feature or request label Dec 1, 2025
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @sixcolors, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces two crucial automated migrations designed to streamline the upgrade process to Fiber v3 and resolve identified session-related issues. The first migration ensures that github.com/gofiber/storage package imports are updated to reflect their correct major versions, handling transitions from unversioned or older versions to v2 or v3 as appropriate. The second migration addresses a breaking change in Fiber v3's session handling by intelligently inserting defer sess.Release() statements after session retrieval calls, ensuring proper resource management and preventing potential leaks in applications using the legacy Store Pattern.

Highlights

  • Storage Version Migration: Updates github.com/gofiber/storage package imports to their correct major versions (e.g., redis to redis/v3, sqlite3 to sqlite3/v2), addressing v2 -> v3 upgrades for some and unversioned -> v2 for many others.
  • Session Release Migration: Automatically inserts defer sess.Release() calls after store.Get() or store.GetByID() in Fiber v3 applications, which is crucial for manual session cleanup in the new version.
  • Migration Integration: Both new migrations are integrated into the existing v3 migration sequence, ensuring they are applied during the upgrade process.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces two crucial migrations for Fiber v3: updating storage package imports to their correct major versions and ensuring proper session cleanup by adding defer sess.Release() calls. Both migrations are thoughtfully designed, leveraging regular expressions to accurately identify and modify code patterns. The session_release.go migration demonstrates intelligence in handling diverse error checking styles and ensures idempotency, preventing redundant defer statements. Similarly, the storage_versions.go migration utilizes a clear mapping to update import paths, also maintaining idempotency. The comprehensive test suites accompanying both migrations cover various scenarios and edge cases, affirming the robustness and reliability of these changes for a smooth transition to Fiber v3.

@coderabbitai
Copy link

coderabbitai bot commented Dec 1, 2025

Walkthrough

This PR adds two new migration functions to the v3 migration framework. MigrateStorageVersions rewrites storage package imports to include version suffixes (e.g., github.com/gofiber/storage/<pkg>/<major>), while MigrateSessionRelease injects defer sess.Release() calls after session access patterns. Both are registered in the migrations list and include comprehensive test coverage.

Changes

Cohort / File(s) Summary
Migration Registration
cmd/internal/migrations/lists.go
Adds v3migrations.MigrateStorageVersions and v3migrations.MigrateSessionRelease to the Functions slice for migrations from >=2.0.0-0 to <4.0.0-0.
Session Release Migration
cmd/internal/migrations/v3/session_release.go, cmd/internal/migrations/v3/session_release_test.go
Implements MigrateSessionRelease function that scans Go source files for session store Get/GetByID patterns, locates error-handling blocks, and injects defer <sessVar>.Release() if not already present. Includes helper findErrorBlockEnd for block boundary detection and preserves indentation. Test file covers insertion when missing, no-duplicate scenarios, GetByID patterns, and multiline error handling.
Storage Versions Migration
cmd/internal/migrations/v3/storage_versions.go, cmd/internal/migrations/v3/storage_versions_test.go
Implements MigrateStorageVersions function with regex pattern matching to detect and rewrite storage imports to include version suffixes based on storageMinimumVersions map. Test file covers initial upgrades, already-versioned imports, mixed versions, v2-to-v3 transitions, and unknown package handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–25 minutes

  • findErrorBlockEnd logic in session_release.go requires careful verification of brace counting and block boundary detection for correctness
  • Indentation preservation across both migrations to ensure consistent code formatting
  • Edge cases in pattern matching (e.g., already-versioned imports, duplicate Release calls, malformed error blocks)
  • Test coverage completeness for regex and AST-like pattern matching scenarios

Possibly related PRs

Suggested reviewers

  • gaby
  • efectn

Poem

🐰 Hops through storage paths with glee,
Session defer calls, wild and free,
v3 migrations now complete,
From v2's old patterns, what a treat!
Code transforms right before our eyes,
Ready for the v3 sunrise! 🌅

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main changes: adding two new migrations (storage version and session release) for v3, which aligns perfectly with the changeset.
Description check ✅ Passed The PR description is comprehensive, covering the problem being solved (session-related issues from gofiber/recipes#3841), detailed explanations of both migrations, test coverage, files changed, and storage adapters covered. It follows the repository's template spirit with clear technical details.
Linked Issues check ✅ Passed The PR successfully implements the v3 migration requirements: storage package imports are updated to latest versions with v2→v3 upgrades for redis/postgres and unversioned→v2 upgrades for 17 adapters, and session release handling is added for Fiber v3's Store Pattern requirements.
Out of Scope Changes check ✅ Passed All code changes are directly scoped to the stated objectives: two new migration modules (storage_versions.go and session_release.go with corresponding tests) and integration into the migration sequence via lists.go. No unrelated modifications detected.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/session-migration-pr-3841

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (5)
cmd/internal/migrations/v3/session_release.go (3)

23-23: Regex may produce false positives on non-session store.Get calls.

The regex (\w+)\.(Get(?:ByID)?)\( matches any x.Get( or x.GetByID( pattern, not specifically session store calls. This could incorrectly insert defer .Release() for unrelated .Get() methods (e.g., map access helpers, HTTP client calls).

Consider adding context validation—such as checking that the file imports middleware/session or that the store variable is assigned from session.NewStore()—before inserting the defer.


63-65: Condition blockEnd >= len(lines) is overly strict.

When blockEnd == len(lines) - 1 (i.e., the closing brace is on the last line), the condition blockEnd >= len(lines) is false, so processing continues. However, at line 69-72, if blockEnd is the last valid index, searchEnd may still be valid but there are no lines after blockEnd to search. This is handled, but the comment at line 125 says "Returns the line index after the closing brace" which is inconsistent with returning the actual brace line index.

The logic works but the comment is misleading—findErrorBlockEnd returns the index of the closing brace, not the index after it.

-// findErrorBlockEnd finds the end of an error handling block
-// Returns the line index after the closing brace, or -1 if not found
+// findErrorBlockEnd finds the end of an error handling block
+// Returns the line index of the closing brace, or -1 if not found

126-126: Unused parameter in findErrorBlockEnd.

The third parameter (originally indent) is named _ indicating it's unused. Consider removing it from the function signature if not needed.

-func findErrorBlockEnd(lines []string, startIdx int, _ string) int {
+func findErrorBlockEnd(lines []string, startIdx int) int {

And update the call site at line 60:

-			blockEnd := findErrorBlockEnd(lines, nextLineIdx, indent)
+			blockEnd := findErrorBlockEnd(lines, nextLineIdx)
cmd/internal/migrations/v3/session_release_test.go (1)

178-181: Assertion may be fragile due to multiple } characters in content.

strings.Index(result, "}") finds the first } in the file, which could be in the import block or elsewhere, not necessarily the error block's closing brace. This makes the assertion potentially unreliable.

Consider a more precise assertion:

-	// Verify defer comes after the error block
-	deferIdx := strings.Index(result, "defer sess.Release()")
-	errorBlockEnd := strings.Index(result, "}")
-	assert.Greater(t, deferIdx, errorBlockEnd, "defer should come after error block")
+	// Verify defer comes after the error block by checking it appears after "return err"
+	returnIdx := strings.Index(result, "return err")
+	deferIdx := strings.Index(result, "defer sess.Release()")
+	assert.Greater(t, deferIdx, returnIdx, "defer should come after error handling block")
cmd/internal/migrations/v3/storage_versions.go (1)

15-42: LGTM!

Well-documented version mapping with clear comments indicating actual versions that are currently up-to-date (postgres v3.3.1 tagged Nov 28, 2025). The explicit exclusion of v1/unversioned adapters in comments helps maintainability.

Consider adding a comment describing how to update this map when new adapter versions are released—this will help future maintainers keep versions synchronized with latest gofiber/storage releases.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 036ded6 and 3606a8c.

📒 Files selected for processing (5)
  • cmd/internal/migrations/lists.go (1 hunks)
  • cmd/internal/migrations/v3/session_release.go (1 hunks)
  • cmd/internal/migrations/v3/session_release_test.go (1 hunks)
  • cmd/internal/migrations/v3/storage_versions.go (1 hunks)
  • cmd/internal/migrations/v3/storage_versions_test.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (5)
cmd/internal/migrations/v3/storage_versions.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
cmd/internal/migrations/v3/storage_versions_test.go (1)
cmd/internal/migrations/v3/storage_versions.go (1)
  • MigrateStorageVersions (46-93)
cmd/internal/migrations/lists.go (2)
cmd/internal/migrations/v3/storage_versions.go (1)
  • MigrateStorageVersions (46-93)
cmd/internal/migrations/v3/session_release.go (1)
  • MigrateSessionRelease (17-122)
cmd/internal/migrations/v3/session_release.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
cmd/internal/migrations/v3/session_release_test.go (1)
cmd/internal/migrations/v3/session_release.go (1)
  • MigrateSessionRelease (17-122)
🔇 Additional comments (12)
cmd/internal/migrations/v3/session_release.go (1)

1-12: LGTM!

Package declaration and imports are appropriate for the functionality.

cmd/internal/migrations/v3/session_release_test.go (3)

14-52: LGTM!

Good basic test case verifying the defer insertion for the standard store.Get(c) pattern.


54-96: LGTM!

Excellent idempotency test ensuring the migration doesn't add duplicate defer statements.


98-136: LGTM!

Good coverage for the GetByID variant.

cmd/internal/migrations/lists.go (1)

73-74: LGTM!

The new migrations are correctly registered in the v3 migration list. The ordering (storage versions before session release) is logical since import updates should happen before code transformations.

cmd/internal/migrations/v3/storage_versions_test.go (5)

13-53: LGTM!

Comprehensive test for basic storage version migration covering sqlite3→v2, redis→v3, postgres→v3 upgrades.


55-93: LGTM!

Good idempotency test ensuring already-versioned imports remain unchanged without duplicate suffixes.


95-136: LGTM!

Good test for mixed version scenarios.


138-179: LGTM!

Excellent test case for v2→v3 upgrades (redis, postgres) while sqlite3 correctly stays at v2.


181-219: LGTM!

Good test verifying unknown packages (aerospike, nats) remain unchanged while known packages are upgraded.

cmd/internal/migrations/v3/storage_versions.go (2)

54-83: LGTM!

The implementation correctly:

  1. Matches both versioned and unversioned imports
  2. Preserves unknown packages unchanged
  3. Skips already-correct versions
  4. Uses internal.ChangeFileContent which handles goimports processing

52-52: Regex pattern could theoretically match nested paths, but this is safely handled by the package name lookup.

The regex ([a-zA-Z0-9_-]+)(?:/v(\d+))? does allow matching nested paths (e.g., capturing internal from redis/internal). However, the code is safe because line 69 performs a map lookup against storageVersionMap, which only contains known storage adapter names (postgres, redis, mongodb, etc.). If the regex matched a nested subpath, the lookup would fail and the original import would be returned unchanged. Additionally, the gofiber/storage ecosystem uses only single-level package names without exposed internal subpaths.

- Improve brace detection in session release migration to handle '} else {' patterns
- Add explicit check for 'else' keyword to prevent premature termination
- Update comment to accurately describe findErrorBlockEnd return value
- Add note about brace counting limitation in strings/comments

These changes address the code review feedback from CodeRabbit while
maintaining compatibility with typical Go error handling patterns.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
cmd/internal/migrations/v3/session_release.go (1)

125-156: Brace counting limitation is properly documented.

The comment at lines 127-128 correctly acknowledges that brace counting may not handle braces inside strings or comments. This is a known limitation that's acceptable for migration tooling targeting typical Go error handling patterns.

🧹 Nitpick comments (2)
cmd/internal/migrations/v3/session_release.go (2)

98-98: Consider extracting the comment text as a constant.

The inline comment "// Important: Manual cleanup required" could be extracted for easier maintenance if the message needs to change.

+const releaseComment = "// Important: Manual cleanup required"
+
 // MigrateSessionRelease adds defer sess.Release() after store.Get() calls
 ...
-			deferLine := indent + "defer " + sessVar + ".Release() // Important: Manual cleanup required"
+			deferLine := indent + "defer " + sessVar + ".Release() " + releaseComment

129-129: Remove unused parameter.

The indent parameter (now _ string) is unused. Consider removing it from the function signature to improve clarity.

-func findErrorBlockEnd(lines []string, startIdx int, _ string) int {
+func findErrorBlockEnd(lines []string, startIdx int) int {

And update the call site at line 60:

-			blockEnd := findErrorBlockEnd(lines, nextLineIdx, indent)
+			blockEnd := findErrorBlockEnd(lines, nextLineIdx)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3606a8c and 03e3a86.

📒 Files selected for processing (1)
  • cmd/internal/migrations/v3/session_release.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
cmd/internal/migrations/v3/session_release.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: lint
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, macos-latest)
🔇 Additional comments (4)
cmd/internal/migrations/v3/session_release.go (4)

1-12: LGTM!

Package declaration and imports are appropriate for the migration functionality.


17-57: Consider handling the case where error is discarded.

The migration only triggers when there's an error check pattern (if errVar != nil). If users wrote sess, _ := store.Get(c) (discarding the error), the migration won't insert the defer sess.Release() call.

This may be intentional since discarding the error is already a code smell, but it's worth noting that such patterns would still need manual migration.


67-84: LGTM - Idempotency check is well-implemented.

The search for existing Release() calls with a 20-line window and the improved brace detection logic (addressing the } else { case) provides reasonable idempotency guarantees. The code won't create duplicate defer statements on re-runs.


137-139: Single-line detection could produce false positives.

The check strings.Contains(line, "{") && strings.Contains(line, "}") detects single-line if statements, but may incorrectly match lines where braces appear in unequal counts or within string literals:

// Would be detected as single-line but isn't complete:
if err != nil { doSomething(

For a migration tool with typical Go idioms, this edge case is rare. The limitation is documented.

Per René's suggestion, renamed storageVersionMap to storageMinimumVersions
to better communicate that these are minimum required major versions for
Fiber v3 compatibility rather than just 'latest' versions.

- Renamed variable: storageVersionMap -> storageMinimumVersions
- Updated documentation to emphasize these are minimum required versions
- Updated all references throughout the migration logic
- All tests passing, no functional changes
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
cmd/internal/migrations/v3/storage_versions.go (2)

53-53: Consider compiling regex at package level.

Compiling the regex inside the function works correctly, but Go best practices recommend compiling regex patterns at package level using regexp.MustCompile to avoid repeated compilation and to fail fast on invalid patterns during initialization.

+// reStorageImport matches storage imports with or without version suffix
+var reStorageImport = regexp.MustCompile(`"github\.com/gofiber/storage/([a-zA-Z0-9_-]+)(?:/v(\d+))?"`)
+
 // MigrateStorageVersions updates storage package imports to use the correct latest version.
 // This migration handles storage packages from github.com/gofiber/storage/*.
 func MigrateStorageVersions(cmd *cobra.Command, cwd string, _, _ *semver.Version) error {
-	// Regex to match storage imports with or without version suffix
-	// Examples:
-	//   "github.com/gofiber/storage/sqlite3"
-	//   "github.com/gofiber/storage/redis/v2"
-	//   "github.com/gofiber/storage/postgres/v3"
-	reStorageImport := regexp.MustCompile(`"github\.com/gofiber/storage/([a-zA-Z0-9_-]+)(?:/v(\d+))?"`)

92-93: Consider adjusting message tense.

The message "Migrating storage package versions" is printed after the migration is already complete. Consider using past tense ("Migrated") for clarity, or moving the print before the operation begins.

 	if !changed {
 		return nil
 	}

-	cmd.Println("Migrating storage package versions")
+	cmd.Println("Migrated storage package versions")
 	return nil
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03e3a86 and 296a96b.

📒 Files selected for processing (1)
  • cmd/internal/migrations/v3/storage_versions.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
cmd/internal/migrations/v3/storage_versions.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Analyse
  • GitHub Check: Build (1.25.x, ubuntu-latest)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, macos-13)
🔇 Additional comments (3)
cmd/internal/migrations/v3/storage_versions.go (3)

1-11: LGTM!

Package declaration and imports are correctly structured. All imports are used appropriately.


13-43: Well-documented version mapping.

The categorization is clear and the exclusion of v1/unversioned adapters is appropriately documented. The inline version comments (e.g., // Latest: v3.3.1) are helpful for maintainability.


76-82: Verify intended behavior for version comparison.

The current logic sets any non-matching version to the target version without semantic comparison. This means if a package were already at a higher version (e.g., hypothetical redis/v4), it would be "downgraded" to v3.

While this scenario is unlikely since the migration targets v2→v3 upgrades and higher versions don't currently exist, consider whether adding a version comparison (only upgrade if current < target) would be more robust for future-proofing.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
cmd/internal/migrations/v3/session_release.go (1)

19-25: Pattern breadth may cause false positives on non-session Get calls.

The regex matches any x, err := y.Get( or GetByID( pattern, which could inadvertently match non-session types like caches, maps, or database accessors that have a Get method. While the releaseComment signals manual review is needed and goimports would catch invalid .Release() calls at write time, consider whether a more targeted pattern (e.g., matching only identifiers containing "store", "session", or "sess") would reduce noise.

If you want to reduce false positives, you could restrict the store variable name:

-	reStoreGet := regexp.MustCompile(`(?m)^(\s*)(\w+),\s*(\w+)\s*:=\s*(\w+)\.(Get(?:ByID)?)\(`)
+	// Match store-like variable names to reduce false positives
+	reStoreGet := regexp.MustCompile(`(?m)^(\s*)(\w+),\s*(\w+)\s*:=\s*(\w*[Ss]tore\w*)\.(Get(?:ByID)?)\(`)

Alternatively, keep the broad pattern if the intent is to catch all possible session store naming conventions.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 296a96b and 96e63b1.

⛔ Files ignored due to path filters (1)
  • go.mod is excluded by !**/*.mod
📒 Files selected for processing (3)
  • Makefile (1 hunks)
  • cmd/internal/migrations/v3/session_release.go (1 hunks)
  • cmd/internal/migrations/v3/storage_versions.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/internal/migrations/v3/storage_versions.go
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-03T12:18:29.841Z
Learnt from: CR
Repo: gofiber/cli PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-03T12:18:29.841Z
Learning: Use the Makefile commands for common tasks (e.g., `make lint`, `make test`)

Applied to files:

  • Makefile
🧬 Code graph analysis (1)
cmd/internal/migrations/v3/session_release.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
🔇 Additional comments (5)
Makefile (1)

1-1: Routine patch-release toolchain update.

Bumping from go1.25.0 to go1.25.5 is a standard maintenance update. Patch releases are backward-compatible and contain bug fixes.

Please confirm this toolchain update aligns with your CI/CD pipeline and that the project remains building and linting cleanly with go1.25.5.

cmd/internal/migrations/v3/session_release.go (4)

1-14: LGTM!

Imports are appropriate and the releaseComment constant clearly documents the purpose of the inserted code for manual review.


54-59: Error check detection may miss compound conditions.

The prefix check if errVar+" != nil" won't match compound error conditions like if err != nil && otherCondition { or if err == nil { (for early-exit patterns). For a migration tool this is acceptable since the most common pattern is handled, but worth noting that some valid patterns may be skipped.


69-97: Good idempotency check for existing Release calls.

The search window and early termination logic correctly prevent duplicate insertions. The fix from the previous review addressing } else { patterns is properly implemented.


127-158: Brace counting limitation is properly documented.

The comment at lines 129-130 clearly acknowledges that braces within strings and comments may cause incorrect detection, which appropriately addresses the concern from the previous review. For typical Go error handling patterns, this implementation is sufficient.

@sixcolors sixcolors force-pushed the fix/session-migration-pr-3841 branch from 96e63b1 to 296a96b Compare December 2, 2025 20:02
- Extract release comment as constant for easier maintenance
- Remove unused indent parameter from findErrorBlockEnd
- Move regex compilation to package level (Go best practice)
- Fix message tense: 'Migrating' → 'Migrated'

These refactors improve code maintainability and follow Go conventions.
@gofiber gofiber deleted a comment from ReneWerner87 Dec 2, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
cmd/internal/migrations/v3/session_release.go (1)

69-86: Consider edge case with closing braces in nested structures.

The search for existing Release() calls stops when encountering lines starting with }. While the added !strings.Contains(trimmed, "else") check addresses the } else { concern from previous reviews, there's a subtle edge case: lines like }) or }, from nested function calls or composite literals could still terminate the search prematurely.

For example:

sess, err := store.Get(c)
if err != nil {
    return err
}
result := ProcessData(Data{
    Field: "value",
}) // <- `})` would stop the search here
defer sess.Release() // <- existing Release() not detected, duplicate inserted

This is likely a rare scenario in practice, and acceptable given the tool's migration-focused scope. However, if you want to be more precise, consider checking indent levels rather than just brace presence:

// Track the indent level of the error block for more accurate scope detection
blockIndent := len(indent)
for j := blockEnd + 1; j < searchEnd; j++ {
    if strings.Contains(lines[j], sessVar+".Release()") {
        hasRelease = true
        break
    }
    trimmed := strings.TrimSpace(lines[j])
    currentIndent := len(lines[j]) - len(strings.TrimLeft(lines[j], " \t"))
    // Stop only at closing braces at the same or lower indent than the original block
    if strings.HasPrefix(trimmed, "}") && !strings.Contains(trimmed, "{") && 
       !strings.Contains(trimmed, "else") && currentIndent <= blockIndent {
        break
    }
}
cmd/internal/migrations/v3/storage_versions.go (1)

21-51: Comprehensive and well-documented version mapping.

The storageMinimumVersions map covers 17 packages comprehensively with clear inline documentation of target versions. The distinction between v3, v2, and v1/unversioned adapters is well-explained in the comments, making the migration strategy transparent.

Optional: Consider renaming storageMinimumVersions to storageFiberV3Versions or storageTargetVersions to clarify that these represent the specific versions required for Fiber v3 compatibility, rather than minimum version constraints. The current name could be interpreted as "at least v2" when it actually means "exactly v2 for v3 compatibility." However, the existing comments do explain this clearly, so it's a minor naming consideration.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 96e63b1 and 8588617.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/session_release.go (1 hunks)
  • cmd/internal/migrations/v3/storage_versions.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
cmd/internal/migrations/v3/storage_versions.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Analyse
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, ubuntu-latest)
🔇 Additional comments (6)
cmd/internal/migrations/v3/session_release.go (3)

19-26: Pattern matching logic looks solid.

The regex correctly captures session acquisition patterns including store.Get() and store.GetByID(), and properly extracts the session variable, error variable, and indentation. This will handle the common Store Pattern usage effectively.


127-158: Helper function is well-documented with known limitations.

The findErrorBlockEnd function correctly handles both single-line and multi-line error blocks using brace counting. The comment at lines 129-130 appropriately documents the limitation regarding braces in strings/comments, which is an acceptable trade-off for a migration tool targeting typical Go error handling patterns.


19-125: Overall migration logic is sound and well-structured.

The implementation correctly:

  • Identifies Store Pattern usage via regex
  • Locates the corresponding error handling block
  • Inserts defer sess.Release() at the appropriate position
  • Maintains idempotence by checking for existing Release() calls
  • Preserves indentation and formatting

The acknowledged limitations (brace counting in strings/comments) are reasonable for a migration tool and well-documented.

cmd/internal/migrations/v3/storage_versions.go (3)

13-19: Regex pattern correctly handles versioned and unversioned imports.

The pattern "github\.com/gofiber/storage/([a-zA-Z0-9_-]+)(?:/v(\d+))?" properly captures both package name and optional version suffix, supporting all import formats including aliased imports.


53-95: Migration logic is clean and correct.

The implementation properly:

  • Extracts package name and current version from imports
  • Looks up target version from the mapping
  • Skips unknown packages (leaves unchanged)
  • Skips already-correct versions (idempotent)
  • Constructs properly versioned import paths

The integration with internal.ChangeFileContent ensures automatic import cleanup via goimports, and error handling with context wrapping is appropriate.


77-80: Version comparison assumes upgrade-only scenario.

The equality check currentVersion == minVersion skips replacement only when versions match exactly. This works correctly for the v2→v3 migration scenario and handles unversioned→v2 upgrades as intended.

Note: A future edge case could arise if a package has a version higher than the mapped target (e.g., user on v4, map specifies v3), which would incorrectly downgrade. This isn't relevant for the current migration but could be addressed in future versions with semantic version comparison if storage packages evolve beyond v3.

This is working as designed for the current migration. If you anticipate storage packages releasing v4+ in the near future, consider adding version comparison logic:

// Parse and compare semantic versions to prevent downgrades
currentSemver, err := semver.NewVersion(currentVersion)
minSemver, err := semver.NewVersion(minVersion)
if err == nil && currentSemver.GreaterThan(minSemver) {
    return match // Don't downgrade
}

However, this adds complexity that may not be needed for the current v2→v3 migration scope.

@sixcolors
Copy link
Member Author

govulncheck "Your code is affected by 1 vulnerability from the Go standard library.
This scan also found 0 vulnerabilities in packages you import and 2
vulnerabilities in modules you require, but your code doesn't appear to call
these vulnerabilities."

Right, safe to ignore.

@ReneWerner87 ReneWerner87 merged commit 1f0a899 into master Dec 2, 2025
14 of 15 checks passed
@ReneWerner87 ReneWerner87 deleted the fix/session-migration-pr-3841 branch December 2, 2025 20:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✏️ Feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants