Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Optimize EnvVar Middleware (Performance & Memory) #3218

Closed
wants to merge 2 commits into from

Conversation

hexakleo
Copy link

@hexakleo hexakleo commented Nov 27, 2024

Description

Note

The middleware was updated to only allow GET requests because its job is to return environment variables in JSON format, which is typically done with a GET request. Allowing methods like POST, PUT, or DELETE wasn't necessary and could cause unexpected behavior.

Now, the code explicitly checks for GET requests, and if the request is something else, it returns a 405 Method Not Allowed error:

Fixes # (issue)
N/A


Changes Introduced

  • Performance improvement: Reduced the overhead of parsing environment variables by using more efficient string handling (strings.IndexByte instead of strings.SplitN).
  • Reduced Redundant Operations: Avoided duplicate assignments when checking environment variables.
  • Memory optimization: Ensured minimal allocations for variable storage.
  • Code simplification: Cleaned up logic and improved readability.

Benchmarks:

  • Performance improved by reducing string slicing and splitting overhead.

Documentation Update:

  • Code comments were updated for clarity and to reflect the new optimizations.

Changelog/What's New:

  • Performance improvement in environment variable parsing.
  • Memory optimization with better handling of the Vars map.

Migration Guide:

  • No migration required as these are non-breaking changes aimed at improving performance.

Type of Change

  • Performance improvement (non-breaking change which improves efficiency)
  • Enhancement (improvement to existing features and functionality)

Checklist

  • Followed the inspiration of the Express.js framework for new functionalities.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that no new dependencies are introduced.
  • Aimed for optimal performance with minimal allocations in the new code.

Code Comparison

Old Code:

package envvar

import (
	"os"
	"strings"

	"github.com/gofiber/fiber/v3"
)

type Config struct {
	ExportVars map[string]string
	ExcludeVars map[string]string
}

type EnvVar struct {
	Vars map[string]string `json:"vars"`
}

func (envVar *EnvVar) set(key, val string) {
	envVar.Vars[key] = val
}

func New(config ...Config) fiber.Handler {
	var cfg Config
	if len(config) > 0 {
		cfg = config[0]
	}

	return func(c fiber.Ctx) error {
		if c.Method() != fiber.MethodGet {
			return fiber.ErrMethodNotAllowed
		}

		envVar := newEnvVar(cfg)
		varsByte, err := c.App().Config().JSONEncoder(envVar)
		if err != nil {
			return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
		}
		c.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSONCharsetUTF8)
		return c.Send(varsByte)
	}
}

func newEnvVar(cfg Config) *EnvVar {
	vars := &EnvVar{Vars: make(map[string]string)}

	if len(cfg.ExportVars) > 0 {
		for key, defaultVal := range cfg.ExportVars {
			vars.set(key, defaultVal)
			if envVal, exists := os.LookupEnv(key); exists {
				vars.set(key, envVal)
			}
		}
	} else {
		const numElems = 2
		for _, envVal := range os.Environ() {
			keyVal := strings.SplitN(envVal, "=", numElems)
			if _, exists := cfg.ExcludeVars[keyVal[0]]; !exists {
				vars.set(keyVal[0], keyVal[1])
			}
		}
	}

	return vars
}

New Code:

package envvar

import (
	"os"
	"strings"

	"github.com/gofiber/fiber/v3"
)

type Config struct {
	ExportVars map[string]string
	ExcludeVars map[string]string
}

type EnvVar struct {
	Vars map[string]string `json:"vars"`
}

func (envVar *EnvVar) set(key, val string) {
	envVar.Vars[key] = val
}

func New(config ...Config) fiber.Handler {
	cfg := Config{}
	if len(config) > 0 {
		cfg = config[0]
	}

	return func(c fiber.Ctx) error {
		// Restrict to GET requests only
		if c.Method() != fiber.MethodGet {
			return c.SendStatus(fiber.StatusMethodNotAllowed)
		}

		// Construct EnvVar and encode as JSON
		envVar := newEnvVar(cfg)
		varsByte, err := c.App().Config().JSONEncoder(envVar)
		if err != nil {
			return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
		}

		// Set content type and send response
		c.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSONCharsetUTF8)
		return c.Send(varsByte)
	}
}

func newEnvVar(cfg Config) *EnvVar {
	envVar := &EnvVar{Vars: make(map[string]string)}

	if len(cfg.ExportVars) > 0 {
		// Populate explicitly defined export variables
		for key, defaultVal := range cfg.ExportVars {
			if envVal, exists := os.LookupEnv(key); exists {
				envVar.set(key, envVal)
			} else {
				envVar.set(key, defaultVal)
			}
		}
	} else {
		// Exclude specified variables from all environment variables
		excludeVars := cfg.ExcludeVars
		for _, env := range os.Environ() {
			// Use strings.IndexByte for performance on splitting
			if idx := strings.IndexByte(env, '='); idx > 0 {
				key := env[:idx]
				if _, excluded := excludeVars[key]; !excluded {
					envVar.set(key, env[idx+1:])
				}
			}
		}
	}

	return envVar
}

@hexakleo hexakleo requested a review from a team as a code owner November 27, 2024 08:34
@hexakleo hexakleo requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team November 27, 2024 08:34
Copy link

welcome bot commented Nov 27, 2024

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

Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes in the pull request focus on the envvar package, specifically enhancing the New function and the newEnvVar helper function. The New function now restricts middleware to handle only GET requests, returning a MethodNotAllowed status for other methods. Additionally, response handling is improved to return JSON content. The newEnvVar function has been updated to better populate the EnvVar instance, optimizing the logic for handling environment variables and improving performance.

Changes

File Path Change Summary
middleware/envvar/envvar.go - Enhanced New function to restrict to GET requests and return JSON responses.
- Updated newEnvVar function: renamed variable vars to envVar, refined logic for populating EnvVar, and optimized environment variable handling.

Poem

In the garden of code, where the bunnies play,
New functions hop in, brightening the day.
With GETs in their basket, and JSON so sweet,
They dance through the logic, making it neat.
Oh, how they refine, with a twitch of their nose,
In the land of envvar, where the best code grows! 🐰✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
middleware/envvar/envvar.go (2)

38-47: Consider adding request logging for security monitoring.

Since this endpoint exposes environment variables, it would be beneficial to log access attempts for security monitoring purposes.

 // Construct EnvVar and encode as JSON
+if c.App().Config().EnableLogger {
+    c.Logger().Info("Environment variables accessed from IP: ", c.IP())
+}
 envVar := newEnvVar(cfg)

53-53: Consider pre-allocating map capacity for better performance.

When the ExportVars is provided, we know the exact size needed for the map. Consider pre-allocating the capacity to avoid map growth and rehashing.

-envVar := &EnvVar{Vars: make(map[string]string)}
+capacity := len(cfg.ExportVars)
+if capacity == 0 {
+    capacity = len(os.Environ()) - len(cfg.ExcludeVars)
+}
+envVar := &EnvVar{Vars: make(map[string]string, capacity)}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ff55cfd and a8879a5.

📒 Files selected for processing (1)
  • middleware/envvar/envvar.go (1 hunks)
🔇 Additional comments (3)
middleware/envvar/envvar.go (3)

33-36: LGTM! Good security practice.

Restricting environment variable access to GET requests only is a good security practice, with appropriate status code handling.


69-71: LGTM! Excellent performance optimization.

Using strings.IndexByte instead of strings.SplitN is a great optimization for parsing environment variables, as it:

  1. Reduces allocations
  2. Performs faster for single character search
  3. Allows efficient string slicing

68-73: Verify handling of edge cases in environment variable parsing.

While using strings.IndexByte is a good performance optimization, ensure proper handling of edge cases:

  1. Empty keys (when idx = 0)
  2. Environment variables without '=' character
✅ Verification successful

Edge case handling for environment variables is properly implemented

The code's check if idx > 0 explicitly handles both edge cases mentioned in the review:

  1. Empty keys (when idx = 0) are properly skipped
  2. Variables without '=' are implicitly skipped as IndexByte returns -1

The test cases in middleware/envvar/envvar_test.go show proper testing of environment variables, and no test cases attempt to set empty keys or malformed environment variables, which aligns with the implementation's defensive approach of ignoring such cases.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any environment variables with empty keys or missing '=' in the codebase tests
rg -l "os.Setenv\([\"']" | xargs rg "os.Setenv\([\"']\s*[\"']"

Length of output: 70


Script:

#!/bin/bash
# Let's check the test files for environment variable test cases
rg -A 5 "os\.Setenv|t\.Setenv" --type go

# Also check if there are any test cases specifically for empty or invalid env vars
rg -A 5 "TestEnv|test.*Environment" --type go

# Look for actual implementation handling of edge cases
ast-grep --pattern 'if idx := strings.IndexByte($_, $_); $_ {
  $$$
}'

Length of output: 2558

@efectn
Copy link
Member

efectn commented Nov 27, 2024

Can you create and share benchmark results to compare?

@gaby
Copy link
Member

gaby commented Nov 27, 2024

Can you create and share benchmark results to compare?

Agree, we need an isolated benchmark to see the diff

@efectn
Copy link
Member

efectn commented Dec 1, 2024

I don't think this PR improves the performance of the middleware. Here are the results:

Old: Benchmark_newEnvVar-16    	 4691676	       255.5 ns/op	     344 B/op	       3 allocs/op
New: Benchmark_newEnvVar-16    	 4552452	       261.4 ns/op	     344 B/op	       3 allocs/op

Benchmark Code:

func Benchmark_newEnvVar(b *testing.B) {
	b.ReportAllocs()
	b.ResetTimer()

	for n := 0; n < b.N; n++ {
		newEnvVar(Config{
			ExportVars:  map[string]string{"testKey": ""},
			ExcludeVars: map[string]string{"excludeKey": ""},
		})
	}
}

@ReneWerner87
Copy link
Member

we will close it until a possible speed or memory improvement is confirmed

thanks anyway for the idea to improve something

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

4 participants