Skip to content

refactor: messaging and file upload with improved error handling#66

Merged
appleboy merged 1 commit intomasterfrom
refactor
Jul 5, 2025
Merged

refactor: messaging and file upload with improved error handling#66
appleboy merged 1 commit intomasterfrom
refactor

Conversation

@appleboy
Copy link
Owner

@appleboy appleboy commented Jul 5, 2025

  • Refactor message and file sending logic into separate handleMessages and handleFiles methods
  • Stream file uploads via io.Copy rather than loading the entire content into memory
  • Add centralized http.Client with timeout for all requests
  • Enhance error handling throughout by returning more descriptive and wrapped errors
  • Improve response validation for file and message uploads, checking HTTP status and parsing error details
  • Update tests to cover plain text messages, embed messages, file uploads, color conversion, and combined features
  • Add tests using assert.Error/assert.NoError and checking specific error messages
  • Simplify and clarify configuration validation logic

Summary by CodeRabbit

  • New Features

    • Improved error messages with more detailed context for HTTP and configuration issues.
    • Enhanced memory efficiency for file uploads by streaming files directly during upload.
    • Added support for sending default messages when no custom messages are configured.
  • Refactor

    • Streamlined message and file sending logic for better modularity and maintainability.
    • Unified HTTP client usage across all network requests.
  • Tests

    • Expanded and reorganized test coverage to include more scenarios, such as file uploads, color parsing, and integrated plugin execution.
    • Improved clarity and robustness of existing tests.

…ling

- Refactor message and file sending logic into separate handleMessages and handleFiles methods
- Stream file uploads via io.Copy rather than loading the entire content into memory
- Add centralized http.Client with timeout for all requests
- Enhance error handling throughout by returning more descriptive and wrapped errors
- Improve response validation for file and message uploads, checking HTTP status and parsing error details
- Update tests to cover plain text messages, embed messages, file uploads, color conversion, and combined features
- Add tests using assert.Error/assert.NoError and checking specific error messages
- Simplify and clarify configuration validation logic

Signed-off-by: appleboy <appleboy.tw@gmail.com>
@coderabbitai
Copy link

coderabbitai bot commented Jul 5, 2025

Walkthrough

The changes refactor the plugin to introduce a reusable HTTP client, modularize message and file sending logic, improve error handling, and optimize file uploads. The test suite is expanded with new, focused tests for messages, file uploads, color parsing, and integrated execution, enhancing coverage and clarity.

Changes

File(s) Change Summary
plugin.go Added reusable httpClient to Plugin, refactored message/file sending into new methods, improved error handling, optimized file uploads, and enhanced configuration validation.
plugin_test.go Split and expanded tests for messages, file uploads, color parsing, and integrated execution; improved assertions and test clarity.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Plugin
    participant HTTPServer

    User->>Plugin: Exec(ctx)
    Plugin->>Plugin: validate config
    Plugin->>Plugin: handleMessages(ctx)
    alt No messages configured
        Plugin->>HTTPServer: Send default message via httpClient
        HTTPServer-->>Plugin: HTTP response
    else Messages configured
        alt Color configured
            Plugin->>HTTPServer: Send all messages as embeds via httpClient
            HTTPServer-->>Plugin: HTTP response
        else No color
            loop For each message
                Plugin->>HTTPServer: Send plain text message via httpClient
                HTTPServer-->>Plugin: HTTP response
            end
        end
    end
    Plugin->>Plugin: handleFiles(ctx)
    loop For each file
        Plugin->>HTTPServer: Send file via httpClient (multipart upload)
        HTTPServer-->>Plugin: HTTP response
    end
Loading

Poem

A client shared, a message sent,
Files now stream with less lament.
Colors parsed, the tests expand,
With every hop, improvements planned.
From burrow deep, this code does cheer—
Bugs beware, the rabbit’s near!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

@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.

Summary of Changes

Hello @appleboy, 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 significant architectural improvements to the plugin's messaging and file upload capabilities. By refactoring core functionalities, optimizing file handling for large payloads, and centralizing HTTP client management, the changes aim to enhance performance, reliability, and maintainability. A strong focus on comprehensive error handling and expanded test coverage ensures a more robust and predictable user experience.

Highlights

  • Code Refactoring & Modularity: The core logic for sending messages and files has been refactored into dedicated methods, handleMessages and handleFiles, improving code organization and readability within the Exec function.
  • Streamlined File Uploads: File uploads now utilize io.Copy to stream file content directly, eliminating the need to load entire files into memory. This significantly improves performance and reduces memory consumption for large files.
  • Centralized HTTP Client: A single http.Client with a defined timeout (15 seconds) is now initialized once and reused across all HTTP requests for both message and file sending, promoting consistency and better resource management.
  • Enhanced Error Handling: Error handling has been significantly improved throughout the plugin. Errors are now more descriptive, often wrapped with context using fmt.Errorf("%w", err), and response validation for both message and file uploads is more robust, checking HTTP status codes and parsing API error details from the response body.
  • Improved Configuration Validation: The Config.validate() method has been simplified and clarified, making the validation logic for webhook URLs and IDs/tokens more straightforward.
  • Expanded Test Coverage: New and more specific test cases have been added to cover plain text messages, embed messages, file uploads, color conversion logic, and combined feature scenarios. Existing tests have been updated to use assert.Error and assert.NoError for more precise error assertions.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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 is currently in preview and 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 to provide feedback.

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.

@appleboy appleboy merged commit f2b9ede into master Jul 5, 2025
3 of 8 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: 1

🧹 Nitpick comments (1)
plugin_test.go (1)

141-179: Remove unnecessary sleep in test

The 1-second sleep at the beginning of the test appears to be unnecessary and will slow down test execution.

 func TestExecWithAllFeatures(t *testing.T) {
-	time.Sleep(1 * time.Second)
 	// Create a dummy file for testing
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1bdf205 and 1453f0a.

📒 Files selected for processing (2)
  • plugin.go (6 hunks)
  • plugin_test.go (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Lint and Testing
plugin_test.go

[error] 133-133: TestColorConversion/invalid_hex failed: Not equal - expected 0 but got 16724530.


[error] 135-135: TestColorConversion/status_success failed: Not equal - expected 1752220 but got 1754624.

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: ubuntu-latest @ Go 1.23
  • GitHub Check: lint
  • GitHub Check: build-docker
🔇 Additional comments (10)
plugin.go (8)

129-137: Good addition of shared HTTP client

Adding a reusable HTTP client to the Plugin struct is a solid improvement for connection pooling and consistent timeout handling.


141-159: Clean refactoring of validation logic

The simplified validation flow with early return and improved error message construction makes the code more readable and maintainable.


178-196: Excellent optimization for file uploads

The switch from loading entire files into memory to streaming with io.Copy is a significant improvement for handling large files. Proper resource cleanup and detailed error messages enhance reliability.


220-239: Well-structured refactoring of Exec method

The initialization of a shared HTTP client with appropriate timeout and delegation to specialized methods improves code organization and maintainability.


241-287: Well-implemented message handling logic

The method correctly handles different message scenarios with appropriate grouping for embeds and immediate sending for plain text. Error messages provide clear context for debugging.


289-300: Clean file handling implementation

Simple and effective iteration with proper error handling and context.


327-346: Improved error handling in SendFile

Excellent enhancement with detailed error reporting that attempts to parse Discord's JSON error responses while gracefully handling non-JSON responses.


365-382: Correct handling of Discord webhook responses

The check for both 200 and 204 status codes is correct for Discord webhooks. The error handling is consistent with SendFile and provides good debugging information.

plugin_test.go (2)

13-19: Improved test assertions

Good use of assert.Error and error message validation to ensure the correct error is returned.


21-108: Comprehensive test coverage for new functionality

Excellent addition of focused tests that cover plain text messages, embed messages, default templates, and file uploads. Each test is well-structured and validates specific functionality.

Comment on lines +110 to 139
func TestColorConversion(t *testing.T) {
tests := []struct {
name string
colorHex string
expectedInt int
buildStatus string
expectedFall int
}{
{"valid hex", "#ffaa00", 16755200, "success", 1752220},
{"invalid hex", "not-a-hex", 0, "failure", 16724530},
{"status success", "", 0, "success", 1752220},
{"status failure", "", 0, "failure", 16724530},
{"status killed", "", 0, "killed", 16724530},
{"status default", "", 0, "running", 16767280},
}

// change color for embed message
plugin.Config.Color = "#4842f4"
plugin.Commit.Message = "Change embed color to #4842f4"
plugin.Clear()
err = plugin.Exec(context.Background())
assert.Nil(t, err)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := Plugin{
Config: Config{Color: tt.colorHex},
Build: Build{Status: tt.buildStatus},
}
if tt.colorHex != "" {
assert.Equal(t, tt.expectedInt, p.Color())
} else {
assert.Equal(t, tt.expectedFall, p.Color())
}
})
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect test expectations

The test expectations don't match the actual implementation behavior. According to the pipeline failures and the Color() method logic:

  1. When an invalid hex is provided, the method falls back to status-based colors, not 0
  2. The success color is 0x1ac600 = 1754624, not 1752220

Apply this fix to correct the test expectations:

-		{"valid hex", "#ffaa00", 16755200, "success", 1752220},
-		{"invalid hex", "not-a-hex", 0, "failure", 16724530},
-		{"status success", "", 0, "success", 1752220},
+		{"valid hex", "#ffaa00", 16755200, "success", 1754624},
+		{"invalid hex", "not-a-hex", 16724530, "failure", 16724530},
+		{"status success", "", 0, "success", 1754624},
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestColorConversion(t *testing.T) {
tests := []struct {
name string
colorHex string
expectedInt int
buildStatus string
expectedFall int
}{
{"valid hex", "#ffaa00", 16755200, "success", 1752220},
{"invalid hex", "not-a-hex", 0, "failure", 16724530},
{"status success", "", 0, "success", 1752220},
{"status failure", "", 0, "failure", 16724530},
{"status killed", "", 0, "killed", 16724530},
{"status default", "", 0, "running", 16767280},
}
// change color for embed message
plugin.Config.Color = "#4842f4"
plugin.Commit.Message = "Change embed color to #4842f4"
plugin.Clear()
err = plugin.Exec(context.Background())
assert.Nil(t, err)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := Plugin{
Config: Config{Color: tt.colorHex},
Build: Build{Status: tt.buildStatus},
}
if tt.colorHex != "" {
assert.Equal(t, tt.expectedInt, p.Color())
} else {
assert.Equal(t, tt.expectedFall, p.Color())
}
})
}
}
func TestColorConversion(t *testing.T) {
tests := []struct {
name string
colorHex string
expectedInt int
buildStatus string
expectedFall int
}{
{"valid hex", "#ffaa00", 16755200, "success", 1754624},
{"invalid hex", "not-a-hex", 16724530, "failure", 16724530},
{"status success", "", 0, "success", 1754624},
{"status failure", "", 0, "failure", 16724530},
{"status killed", "", 0, "killed", 16724530},
{"status default", "", 0, "running", 16767280},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := Plugin{
Config: Config{Color: tt.colorHex},
Build: Build{Status: tt.buildStatus},
}
if tt.colorHex != "" {
assert.Equal(t, tt.expectedInt, p.Color())
} else {
assert.Equal(t, tt.expectedFall, p.Color())
}
})
}
}
🧰 Tools
🪛 GitHub Actions: Lint and Testing

[error] 133-133: TestColorConversion/invalid_hex failed: Not equal - expected 0 but got 16724530.


[error] 135-135: TestColorConversion/status_success failed: Not equal - expected 1752220 but got 1754624.

🤖 Prompt for AI Agents
In plugin_test.go around lines 110 to 139, the test expectations for color
values are incorrect. Update the expectedInt and expectedFall values to match
the actual Color() method logic: for invalid hex inputs, expect the fallback
color based on build status instead of 0, and change the success color to
1754624 (0x1ac600) instead of 1752220. Adjust the test cases accordingly to
reflect these correct expected values.

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 does a great job of refactoring the message and file sending logic. The move to streaming file uploads is a significant performance improvement, and the centralized HTTP client and enhanced error wrapping improve maintainability and robustness. The test suite has also been significantly improved with more focused, table-driven tests. I've found a few minor issues: a bug in one of the new tests, and a couple of inconsistencies in error message formatting that could be improved for better debugging. Overall, this is a high-quality refactoring.

}
var jsonResponse map[string]interface{}
if err := json.Unmarshal(bodyBytes, &jsonResponse); err != nil {
return fmt.Errorf("failed to send file, status code: %d, body: %s", resp.StatusCode, string(bodyBytes))
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The current error message when JSON unmarshalling fails is helpful as it includes the response body, which is great for debugging. However, it doesn't wrap the underlying err from json.Unmarshal. This is inconsistent with other parts of the refactoring and the PR's goal of enhancing error handling with wrapped errors. Please consider wrapping the error to provide more context for debugging.

Suggested change
return fmt.Errorf("failed to send file, status code: %d, body: %s", resp.StatusCode, string(bodyBytes))
return fmt.Errorf("failed to send file, status code: %d, body: %s: %w", resp.StatusCode, string(bodyBytes), err)

expectedFall int
}{
{"valid hex", "#ffaa00", 16755200, "success", 1752220},
{"invalid hex", "not-a-hex", 0, "failure", 16724530},
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

There appears to be a logic error in this test case. When an invalid hex color is provided, the Color() function is expected to fall back to using the build status to determine the color. For a "failure" status, it should return 16724530. However, the test currently expects 0.

Please correct the expected value to ensure the test accurately reflects the function's behavior.

Suggested change
{"invalid hex", "not-a-hex", 0, "failure", 16724530},
{"invalid hex", "not-a-hex", 16724530, "failure", 16724530},

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