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

rework middleware and add frontend proxy #331

Merged
merged 1 commit into from
Dec 27, 2024
Merged

Conversation

Southclaws
Copy link
Owner

No description provided.

Copy link

vercel bot commented Dec 27, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
storyden ⬜️ Ignored (Inspect) Visit Preview Dec 27, 2024 6:18pm
storyden-homepage ⬜️ Ignored (Inspect) Visit Preview Dec 27, 2024 6:18pm

Copy link

coderabbitai bot commented Dec 27, 2024

📝 Walkthrough

Walkthrough

The pull request introduces a comprehensive refactoring of HTTP middleware components across multiple files. The changes standardize middleware implementation by introducing a consistent pattern of creating middleware structs with constructor functions and methods. Key modifications include centralizing configuration within middleware structs, updating method signatures to support more flexible middleware chaining, and adding new middleware components like frontend proxy and user agent context handling.

Changes

File Change Summary
app/transports/http/middleware/chaos/chaos.go Refactored chaos middleware with new Middleware struct, centralized configuration
app/transports/http/middleware/frontend/frontend.go Added new frontend proxy middleware with reverse proxy handling
app/transports/http/middleware/limiter/limiter.go Updated rate limiting and request size limit middleware, added MaxRequestSizeBytes constant
app/transports/http/middleware/middleware.go Added imports and registered new middleware components
app/transports/http/middleware/origin/cors.go Restructured CORS middleware with new Middleware struct
app/transports/http/middleware/reqlog/requestlog.go Introduced logging middleware with encapsulated logger
app/transports/http/middleware/session_cookie/cookie.go Modified auth middleware method signature
app/transports/http/middleware/useragent/ua.go Added user agent context middleware
app/transports/http/router.go Updated middleware application with new component methods
docker/all/Dockerfile Added PROXY_FRONTEND_ADDRESS environment variable
internal/config/config.go Added FrontendProxy configuration field

Sequence Diagram

sequenceDiagram
    participant Client
    participant Middleware
    participant Handler
    Client->>Middleware: HTTP Request
    Middleware->>Middleware: Apply CORS
    Middleware->>Middleware: Log Request
    Middleware->>Middleware: Frontend Proxy Check
    Middleware->>Middleware: User Agent Context
    Middleware->>Middleware: Session Authentication
    Middleware->>Middleware: Rate Limiting
    Middleware->>Handler: Forward Request
    Handler-->>Middleware: Response
    Middleware-->>Client: Return Response
Loading

Possibly Related PRs

Poem

🐰 Middleware Magic, a Rabbit's Delight
Structs and methods, now shining bright
Proxies dancing, contexts clear
Flexibility brought ever so near
Code refactored with bunny might! 🚀

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@Southclaws Southclaws merged commit 520acbb into main Dec 27, 2024
4 checks passed
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 (12)
app/transports/http/middleware/chaos/chaos.go (1)

Line range hint 26-48: Use a logger instead of fmt.Println for chaos logs.

Lines 33 and 41 utilize fmt.Println for debug output. Replacing them with a structured logger will align with best practices, providing consistent logs and supporting log levels.

- fmt.Println("[DEV_CHAOS_SLOW_MODE] waiting", wait)
+ logger.Debug("dev chaos slow mode waiting", zap.Duration("wait", wait))

- fmt.Println("[DEV_CHAOS_FAIL_RATE] crashing")
+ logger.Warn("dev chaos fail rate triggered")
app/transports/http/middleware/useragent/ua.go (1)

11-16: Include optional configuration fields in the Middleware struct.

Currently, the struct is empty. If future expansions (e.g., user agent filtering) are planned, consider adding relevant fields or placeholders.

app/transports/http/middleware/frontend/frontend.go (2)

15-17: Consider documenting the purpose of Provider.

Adding doc comments explaining that Provider manages frontend proxy logic will help new contributors understand this middleware’s role.


42-58: Refactor conditionals for clarity.

Within WithFrontendProxy(), consider early returns for /api vs. non-API traffic to simplify the code structure. Current logic works, but short-circuiting can improve readability.

app/transports/http/middleware/origin/cors.go (3)

12-14: Include configuration fields for multiple origins.

Currently, Middleware only stores the entire config. If multiple origins are needed or more advanced CORS settings, consider dedicated fields for clarity and future expansion.


16-18: Initialize default CORS settings or checks in New.

If you plan to configure multiple or dynamic origins, you might want to add default CORS logic here, ensuring that WithCORS stays minimal and focused.


Line range hint 20-72: Use a full logger instead of potential no-op statements.

If you decide to log CORS checks, consider introducing logging in this function. Currently, no logs are emitted. This could be useful for debugging or auditing.

app/transports/http/router.go (1)

32-38: Consider grouping multiple middleware parameters into a single struct.
Adding multiple middleware parameters to the function signature can lead to a large, unwieldy parameter list. Consider grouping them into a single struct or using constructor injection where appropriate, which can simplify dependency management and improve clarity.

app/transports/http/middleware/reqlog/requestlog.go (1)

50-50: Add user or request identifiers to log context if available.
When logging requests, adding identifiers (e.g., user ID, correlation ID) can make debugging even more efficient, especially if your system has multi-step transactions or multiple services.

app/transports/http/middleware/limiter/limiter.go (2)

16-20: Constants are well-defined, but consider dynamic configurability.
The MaxRequestSizeBytes is set to 10 MB. If your system’s needs change, or if certain routes need different sizes, consider exposing this as a configurable parameter from your cfg.


45-81: Rate-limiting logic is properly modularized.
Switching to a function returning http.Handler fosters middleware chaining. You might consider extracting logic for calculating request cost from the TODO comment, to a function or strategy pattern for clarity.

docker/all/Dockerfile (1)

81-81: Ensure environment variables are well-documented.

The addition of PROXY_FRONTEND_ADDRESS is crucial for configuring the reverse proxy. Document it in the project’s configuration references or README so other developers can discover and adjust it according to their environment.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b1c03b and 9a918b4.

📒 Files selected for processing (11)
  • app/transports/http/middleware/chaos/chaos.go (1 hunks)
  • app/transports/http/middleware/frontend/frontend.go (1 hunks)
  • app/transports/http/middleware/limiter/limiter.go (3 hunks)
  • app/transports/http/middleware/middleware.go (1 hunks)
  • app/transports/http/middleware/origin/cors.go (1 hunks)
  • app/transports/http/middleware/reqlog/requestlog.go (3 hunks)
  • app/transports/http/middleware/session_cookie/cookie.go (1 hunks)
  • app/transports/http/middleware/useragent/ua.go (1 hunks)
  • app/transports/http/router.go (2 hunks)
  • docker/all/Dockerfile (1 hunks)
  • internal/config/config.go (1 hunks)
🔇 Additional comments (18)
app/transports/http/middleware/chaos/chaos.go (2)

12-16: Consider concurrency safety when storing chaos configuration.

Storing chaos configuration at the struct level is generally fine, but be mindful of potential concurrent usage. If future updates to these fields are planned during runtime, ensure proper synchronization.


18-24: Validate the logic for enabling chaos behavior.

Line 20's condition cfg.DevChaosFailRate > 0 || cfg.DevChaosSlowMode == 0 means that chaos is considered “enabled” if there is any fail rate or if the slow mode is zero. Make sure that this logic accurately reflects the desired behavior.

app/transports/http/middleware/middleware.go (2)

6-12: Organize imported middleware packages effectively.

The newly added imports (chaos, frontend, origin, reqlog, useragent) align well with the modular approach. Consider verifying that no unintended import cycles are introduced.


17-23: Ensure correct dependency injection ordering.

Registering middleware providers in this list is straightforward, but be aware of startup order if any middleware has cross-dependencies. Validate that each New function is sufficiently independent or arranged properly.

app/transports/http/middleware/useragent/ua.go (1)

19-33: Avoid overwriting request context if it includes a prior user agent.

Ensure that any existing user agent data in the request context is either replaced intentionally or combined if needed. This logic is fine as is, but some applications might prefer merging context values.

app/transports/http/middleware/frontend/frontend.go (2)

19-40: Validate HTTP proxy edge cases.

When cfg.FrontendProxy is non-nil, this logic properly builds a reverse proxy. Confirm that error handling and timeouts are configured if the proxied service is unreachable or slow.


60-64: Modularize the build step if more advanced logic is needed.

The current Build() function simply provides the New constructor. If advanced initialization or custom error handling is required later, break out logic into smaller functions for maintainability.

app/transports/http/router.go (2)

10-10: New dependency import looks consistent.
The import path for the chaos middleware is aligned with your project's structure, which simplifies future refactoring and keeps dependencies organized.


42-49: Review middleware chaining order for potential side effects.
Review the sequence in which middleware is applied (e.g., logging vs. chaos vs. rate limiting). For example, you might want logging to happen before chaos injection for better visibility on artificially induced failures. Ensure this order aligns with your observability and security needs.

app/transports/http/middleware/reqlog/requestlog.go (3)

13-15: Struct-based design promotes better encapsulation.
Defining a Middleware struct that holds the logger is a positive step, ensuring that configuration is kept close to the logic that uses it. This design makes the middleware easier to extend and maintain.


17-21: Constructor usage is straightforward and clear.
The New constructor clarifies how to acquire a logging-enabled middleware. This is a good practice for code readability and testability.


Line range hint 37-81: Thorough error handling ensures resilience.
The updated WithLogger method captures panics and logs them, then returns an HTTP 500 response. This robust error handling improves reliability. Consider verifying through integration tests that those logs are emitted with the expected level and format.

app/transports/http/middleware/limiter/limiter.go (3)

24-27: Enhanced state in the Middleware struct is clear and self-contained.
Including sizeLimit as part of the struct consolidates configuration. Verify that other areas referencing request size limits (if any) adapt to this single source of truth.


38-41: Constructor sets sensible defaults.
Your constructor picks up MaxRequestSizeBytes for sizeLimit. This centralizes logic, making it simpler to change defaults later.


102-105: Request size limiting is integrated consistently.
Wrapping the request body via http.MaxBytesReader is straightforward and effective. Remember to confirm error handling in controllers for incomplete reads if large requests are truncated.

internal/config/config.go (1)

16-19: New FrontendProxy field extends configuration flexibility.
The addition of FrontendProxy allows routing requests to a separate frontend service. Ensure that any references to this field handle potential nil values gracefully if the environment variable is unset.

app/transports/http/middleware/session_cookie/cookie.go (1)

124-131: Refactor to leverage consistent middleware chaining.

Great use of a higher-order function for consistent chaining. This aligns with the approach in other middleware components, resulting in a more flexible and uniform API. Note that the newly introduced closure correctly captures the j instance and properly injects the session context.

docker/all/Dockerfile (1)

79-79: Clarify the comment for RUN_FRONTEND usage.

Changing the comment to specify that the API process will run the Next.js server and proxy requests provides clarity on the relationship between the backend and frontend. This helps developers understand the underlying infrastructure better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant