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

feat: Webserver #17

Merged
merged 13 commits into from
Jun 28, 2024
Merged

feat: Webserver #17

merged 13 commits into from
Jun 28, 2024

Conversation

FMotalleb
Copy link
Owner

@FMotalleb FMotalleb commented Jun 27, 2024

Currently can emit events

Summary by CodeRabbit

  • New Features

    • Introduced web server configurations, including address, username, password, and timezone settings.
    • Added basic authentication and event dispatch capabilities to the web server.
  • Bug Fixes

    • Corrected a typo in a log message in Windows credential validation.
  • Refactor

    • Removed unused or redundant methods (Cancel) from several event handling structs for cleaner architecture.
    • Consolidated validation logic into a single function for better maintenance.
  • Chores

    • Updated go.mod with new dependencies to support web server and validation functionalities.
  • Documentation

    • Updated .env.example to include new web server configuration settings.

Copy link

coderabbitai bot commented Jun 27, 2024

Warning

Rate limit exceeded

@FMotalleb has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 33 minutes and 1 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between c0d0143 and 1d096e6.

Walkthrough

The updates introduce configurations for a web server, including credentials and time zone settings, validate configurations, and implement a new web event listener mechanism. These changes involve significant updates across multiple files, adding new dependencies, and enhancing logging and validation functionalities.

Changes

Files Change Summary
.env.example Added configuration settings for the web server listen address, username, password, and timezone.
.vscode/settings.json Added a new configuration "webserver" to the list of settings under "linters".
abstraction/event.go Removed Cancel() method from the Event interface.
cmd/root.go Added bindings for environment variables related to the web server configuration in initConfig function.
config.local.yaml Changed event from interval to web-event and other minor adjustments.
config/compiler/event.go Added a new case for sh.WebEvent, creating a new EventListener based on this event type.
config/compiler/event_test.go Removed initialization of a variable log without assignment.
config/config.go Added new fields for command executor, web server settings, and WebEvent in JobEvent.
config/events_validator_test.go Included setting WebEvent to an empty string in test data.
config/helpers.go Introduced function debugLog in Config struct for logging based on log level.
config/job_valdiator.go Added Validate methods to JobConfig and JobEvent structs.
config/task_validator.go Introduced Validate method for Task struct and several validation functions.
config/validators.go Consolidated validation logic and added validateWebserverConfig function.
core/event/cron.go Removed Cancel method and added check in BuildTickChannel method.
core/event/init.go Removed Cancel method and replaced its call with close(c.notifyChan) in BuildTickChannel method.
core/event/interval.go Updated BuildTickChannel method to check if the ticker is built before creating it and removed Cancel method.
core/event/web_event.go Introduced WebEventListener type with methods for creating an event listener and building a tick channel.
core/global/global_context.go Introduced GlobalContext struct to manage event listeners.
core/jobs/runner.go Removed unnecessary empty line in InitializeJobs function.
core/os_credential/windows_credential.go Updated log message to fix a typo.
core/webserver/endpoint/event_dispatch.go Implemented event dispatching to registered listeners.
core/webserver/webserver.go Introduced WebServer struct for handling web server functionality using Gin framework.
ctxutils/keys.go Added FailedRemotes and EventListeners context keys.
go.mod Added new dependencies for web server functionality and validation.
logger/logger.go Added AddHook function in logging setup.
main.go Initialized and started a web server in the main() function if certain configurations are set.

Poem

🍃 The code has bloomed, like flowers in the spring,
Web servers hum, and configurations sing.
No more "Cancel" in the code, listen close,
For web events whisper, as network traffic flows.
Validators stand guard, ensuring all is well,
As tasks embark, within their YAML shell.
🐇 The rabbit smiles, a job well done,
A tale of progress, in the code has begun. 🌸


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

@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: 10

Outside diff range and nitpick comments (1)
cmd/root.go (1)

Line range hint 60-60: Refactor initConfig to reduce complexity.

The initConfig function is flagged by static analysis for being too long. Consider breaking it down into smaller, more manageable functions to improve readability and maintainability.

- func initConfig() {
+ func initConfig() {
+   initLogConfig()
+   initWebServerConfig()
+   initShellConfig()
+ }

+ func initLogConfig() {
+   // Log-related configuration
+ }

+ func initWebServerConfig() {
+   // Web-server related configuration
+ }

+ func initShellConfig() {
+   // Shell-related configuration
+ }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2eb2e8a and 8e5a070.

Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
Files selected for processing (27)
  • .env.example (1 hunks)
  • .vscode/settings.json (1 hunks)
  • abstraction/event.go (1 hunks)
  • cmd/root.go (1 hunks)
  • config.local.yaml (1 hunks)
  • config/compiler/event.go (1 hunks)
  • config/compiler/event_test.go (1 hunks)
  • config/config.go (2 hunks)
  • config/events_validator_test.go (1 hunks)
  • config/helpers.go (1 hunks)
  • config/job_valdiator.go (1 hunks)
  • config/task_validator.go (1 hunks)
  • config/validators.go (3 hunks)
  • core/event/cron.go (2 hunks)
  • core/event/init.go (1 hunks)
  • core/event/interval.go (2 hunks)
  • core/event/web_event.go (1 hunks)
  • core/global/global_context.go (1 hunks)
  • core/jobs/runner.go (1 hunks)
  • core/os_credential/windows_credential.go (1 hunks)
  • core/webserver/endpoint/event_dispatch.go (1 hunks)
  • core/webserver/webserver.go (1 hunks)
  • ctxutils/keys.go (1 hunks)
  • go.mod (4 hunks)
  • logger/logger.go (1 hunks)
  • main.go (1 hunks)
  • schema.json (1 hunks)
Files not reviewed due to errors (1)
  • config/job_valdiator.go (no review received)
Files skipped from review due to trivial changes (7)
  • .env.example
  • .vscode/settings.json
  • abstraction/event.go
  • config.local.yaml
  • config/compiler/event_test.go
  • core/jobs/runner.go
  • core/os_credential/windows_credential.go
Additional context used
golangci-lint
core/global/global_context.go

1-1: ST1000: at least one file in a package should have a package comment

(stylecheck)

cmd/root.go

60-60: Function 'initConfig' is too long (116 > 100)

(funlen)

GitHub Check: ci (macos-latest)
core/global/global_context.go

[failure] 1-1:
ST1000: at least one file in a package should have a package comment (stylecheck)

GitHub Check: analyze (go)
core/global/global_context.go

[failure] 1-1:
ST1000: at least one file in a package should have a package comment (stylecheck)


[failure] 1-1:
ST1000: at least one file in a package should have a package comment (stylecheck)

GitHub Check: ci (ubuntu-latest)
core/global/global_context.go

[failure] 1-1:
ST1000: at least one file in a package should have a package comment (stylecheck)

Additional comments not posted (12)
core/event/init.go (1)

13-13: Ensure proper channel handling after closure.

Closing the channel is a good practice to signal that no more data will be sent. However, ensure that there are no further sends on c.notifyChan after it's closed, as this would cause a panic at runtime.

ctxutils/keys.go (1)

7-13: Context keys addition approved.

New context keys for FailedRemotes and EventListeners are added. Ensure that these keys are used consistently across the project and documented appropriately if they are part of the public API.

core/event/web_event.go (1)

5-26: Review of WebEventListener implementation.

This implementation introduces a new way to handle web events. Ensure that the channel c is properly synchronized if accessed from multiple goroutines. Also, verify that global.CTX.AddEventListener properly handles the registration and cleanup of event listeners to avoid memory leaks or unexpected behavior.

config/helpers.go (1)

14-29: Review of controlled logging method debugLog.

The method debugLog introduces conditional logging based on the internal log level. Ensure that the method cfg.LogLevel.ToLogrusLevel() is efficient and does not introduce significant overhead, especially if called frequently. Consider caching the result if it's costly to compute.

core/global/global_context.go (1)

38-43: Optimize locking strategy to avoid potential deadlocks.

The method AddEventListener uses a lock to ensure thread safety, which is good. However, consider optimizing the locking strategy to avoid locking while performing non-critical operations.

+ ctx.lock.Lock()
  listeners := ctx.EventListeners()
+ ctx.lock.Unlock()
- ctx.lock.Lock()
  listeners[event] = append(listeners[event], listener)
  ctx.Context = context.WithValue(ctx.Context, ctxutils.EventListeners, listeners)
- ctx.lock.Unlock()
main.go (1)

23-25: Imports added for global context, jobs, and webserver modules.

Ensure that these modules are used appropriately in the file and there are no unused imports.

logger/logger.go (1)

28-30: Addition of AddHook function to logger.

This function allows adding hooks to the logger, which can be useful for extending logging capabilities (e.g., sending logs to external systems). Ensure that the hooks added are thread-safe if the logger is accessed concurrently.

cmd/root.go (1)

96-125: Ensure consistent environment variable naming and handling.

The bindings for web server configuration are introduced correctly using viper.BindEnv. However, it's important to ensure that the naming convention used for environment variables (webserver_port, webserver_address, etc.) is consistent across the entire application. Also, consider adding default values for these settings to improve the robustness of the application initialization.

go.mod (1)

Line range hint 8-81: Review added dependencies for relevance and compatibility.

The newly added dependencies are necessary for the web server functionality and other enhancements. Ensure that these dependencies are compatible with the existing system and do not introduce any known vulnerabilities. Regularly check for updates to these dependencies to maintain security and performance.

config/task_validator.go (1)

17-134: Ensure robust validation logic in task configurations.

The validation functions are well-structured and cover various aspects of task configuration. However, ensure that the error messages are clear and provide enough detail to help users correct configuration errors. Also, consider using constants for error messages to avoid duplication and facilitate easier updates.

config/config.go (1)

Line range hint 12-48: Validate new configuration fields for web server settings.

The new fields added to the Config struct for web server settings are correctly annotated for serialization. Ensure that these fields are properly validated during application startup to prevent misconfiguration issues.

schema.json (1)

120-123: Validate new JSON schema field for web events.

The addition of the web-event field in the JSON schema is correctly defined. Ensure that this field is used consistently in the application and that the description provides enough information for users to understand its purpose.

core/webserver/endpoint/event_dispatch.go Outdated Show resolved Hide resolved
core/event/interval.go Show resolved Hide resolved
core/global/global_context.go Show resolved Hide resolved
main.go Outdated Show resolved Hide resolved
config/compiler/event.go Show resolved Hide resolved
core/event/cron.go Show resolved Hide resolved
config/validators.go Show resolved Hide resolved
@@ -16,6 +16,7 @@ func TestJobEvent_Validate_PositiveInterval(t *testing.T) {
Interval: 10,
Cron: "",
OnInit: false,
WebEvent: "",
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Modification to include WebEvent in test validation was not fully verified.

The test cases in config/events_validator_test.go do not comprehensively cover the WebEvent attribute. Ensure that both positive and negative scenarios for WebEvent are included in the test cases.

  • Add test cases that validate the behavior when WebEvent is set to valid and invalid values.
Analysis chain

Modification to include WebEvent in test validation.

The test now checks the WebEvent attribute as part of the JobEvent validation. Ensure that the test covers all relevant scenarios for WebEvent, including both positive and negative cases.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the test coverage for `WebEvent`.
# Test: Search for test cases involving `WebEvent`.
rg --type go $'WebEvent' ./tests/

Length of output: 81



Script:

#!/bin/bash
# Locate all Go test files and search for `WebEvent` within those files.
fd --type f --extension go | xargs rg 'WebEvent'

Length of output: 664



Script:

#!/bin/bash
# Extract test functions involving `WebEvent` from `config/events_validator_test.go`
ast-grep --lang go --pattern 'func Test$_($$_) { $$$ }' config/events_validator_test.go | rg 'WebEvent'

Length of output: 103



Script:

#!/bin/bash
# Display the contents of `config/events_validator_test.go` for manual inspection.
cat config/events_validator_test.go

Length of output: 2026

core/webserver/webserver.go Show resolved Hide resolved
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: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 8e5a070 and c0d0143.

Files selected for processing (3)
  • config/events_validator_test.go (1 hunks)
  • core/webserver/endpoint/event_dispatch.go (1 hunks)
  • main.go (2 hunks)

Comment on lines +19 to +31
func (ed *EventDispatchEndpoint) Endpoint(c *gin.Context) {
event := c.Param("event")
listeners := global.CTX.EventListeners()[event]
if len(listeners) == 0 {
c.String(http.StatusNotFound, fmt.Sprintf("event: '%s' not found", event))
return
}
listenerCount := len(listeners)
for _, listener := range listeners {
go listener()
}
c.String(http.StatusOK, fmt.Sprintf("event: '%s' emitted, %d listeners where found", event, listenerCount))
}
Copy link

Choose a reason for hiding this comment

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

Review of Event Dispatch Endpoint:

The implementation properly handles the case when an event is not found, and it correctly dispatches events to listeners. However, the use of goroutines for listeners without error handling or tracking could lead to unmanaged goroutine proliferation or silent failures.

  • Error Handling: Each listener is invoked in a separate goroutine without any error handling. Consider capturing errors from listeners and managing their lifecycle to prevent potential issues in production environments.
  • Response Handling: The response is correctly formatted and returns the appropriate status code. However, consider adding more detailed logging or metrics around event dispatching to improve observability.
+ import "sync"
  func (ed *EventDispatchEndpoint) Endpoint(c *gin.Context) {
      event := c.Param("event")
      listeners := global.CTX.EventListeners()[event]
      if len(listeners) == 0 {
          c.String(http.StatusNotFound, fmt.Sprintf("event: '%s' not found", event))
          return
      }
      listenerCount := len(listeners)
+     var wg sync.WaitGroup
+     wg.Add(listenerCount)
      for _, listener := range listeners {
-         go listener()
+         go func(l func()) {
+             defer wg.Done()
+             l()
+         }(listener)
      }
+     wg.Wait()
      c.String(http.StatusOK, fmt.Sprintf("event: '%s' emitted, %d listeners where found", event, listenerCount))
  }

This change introduces a wait group to manage the goroutines and ensure all listeners have completed before responding. This can help in tracking the lifecycle of each listener and handle errors if needed.

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 (ed *EventDispatchEndpoint) Endpoint(c *gin.Context) {
event := c.Param("event")
listeners := global.CTX.EventListeners()[event]
if len(listeners) == 0 {
c.String(http.StatusNotFound, fmt.Sprintf("event: '%s' not found", event))
return
}
listenerCount := len(listeners)
for _, listener := range listeners {
go listener()
}
c.String(http.StatusOK, fmt.Sprintf("event: '%s' emitted, %d listeners where found", event, listenerCount))
}
import "sync"
func (ed *EventDispatchEndpoint) Endpoint(c *gin.Context) {
event := c.Param("event")
listeners := global.CTX.EventListeners()[event]
if len(listeners) == 0 {
c.String(http.StatusNotFound, fmt.Sprintf("event: '%s' not found", event))
return
}
listenerCount := len(listeners)
var wg sync.WaitGroup
wg.Add(listenerCount)
for _, listener := range listeners {
go func(l func()) {
defer wg.Done()
l()
}(listener)
}
wg.Wait()
c.String(http.StatusOK, fmt.Sprintf("event: '%s' emitted, %d listeners where found", event, listenerCount))
}

Comment on lines +36 to +46
if cmd.CFG.WebServerAddress != "" {
go webserver.
NewWebServer(
global.CTX,
cmd.CFG.WebServerAddress,
cmd.CFG.WebServerPort,
cmd.CFG.WebserverUsername,
cmd.CFG.WebServerPassword,
).
Serve()
}
Copy link

Choose a reason for hiding this comment

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

Review of Web Server Initialization in Main Function:

The web server is conditionally started based on configuration. However, the current implementation lacks error handling for the Serve method within the goroutine, which could lead to silent failures or unhandled errors.

- go webserver.NewWebServer(...).Serve()
+ go func() {
+     err := webserver.NewWebServer(...).Serve()
+     if err != nil {
+         log.Error("Web server failed to start:", err)
+     }
+ }()

This change introduces error handling within the goroutine to ensure that any issues during the web server startup are logged and managed appropriately.

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
if cmd.CFG.WebServerAddress != "" {
go webserver.
NewWebServer(
global.CTX,
cmd.CFG.WebServerAddress,
cmd.CFG.WebServerPort,
cmd.CFG.WebserverUsername,
cmd.CFG.WebServerPassword,
).
Serve()
}
if cmd.CFG.WebServerAddress != "" {
go func() {
err := webserver.
NewWebServer(
global.CTX,
cmd.CFG.WebServerAddress,
cmd.CFG.WebServerPort,
cmd.CFG.WebserverUsername,
cmd.CFG.WebServerPassword,
).
Serve()
if err != nil {
log.Error("Web server failed to start:", err)
}
}()
}

Comment on lines +14 to +27
func TestJobEvent_Validate_WebEvent(t *testing.T) {
event := config.JobEvent{
Interval: 0,
Cron: "",
OnInit: false,
WebEvent: "test-event",
}
logger, _ := mocklogger.HijackOutput(logrus.New())
log := logrus.NewEntry(logger)

err := event.Validate(log)

assert.NoError(t, err)
}
Copy link

Choose a reason for hiding this comment

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

Review of Test Case for WebEvent Validation:

The test case for WebEvent validation checks for no errors when a valid event name is provided. However, it lacks negative test cases which are crucial for thorough testing.

  • Completeness: Include negative test scenarios to ensure robust validation. Test cases should cover scenarios where WebEvent is set to invalid values to ensure the validation logic correctly identifies and handles errors.
func TestJobEvent_Validate_WebEvent_Invalid(t *testing.T) {
    event := config.JobEvent{
        WebEvent: "invalid-event",
    }
    logger, _ := mocklogger.HijackOutput(logrus.New())
    log := logrus.NewEntry(logger)

    err := event.Validate(log)

    assert.Error(t, err, "expected error for invalid web event")
}

This additional test case ensures that the validation logic correctly handles invalid WebEvent values.

@FMotalleb FMotalleb merged commit 1f3ee76 into main Jun 28, 2024
4 of 5 checks passed
@FMotalleb FMotalleb deleted the feat-webserver branch June 28, 2024 14:51
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