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

Enhance Error Execution Utilities: Add Retry, Timeout, Cancellation, and Advanced Error Handling #153

Conversation

UTSAVS26
Copy link

This PR enhances the existing error execution utilities with new features such as timeout, cancellation, retry logic, and execution logging. Specifically:

  • Timeout and cancellation: Added support for context-based cancellation and timeout in concurrent executions.
  • Retry logic: Introduced a retry mechanism to retry failed functions a configurable number of times with delays.
  • Improved error handling: Extended the error handling in ErrExecSequential to accumulate errors and stop execution on critical errors using a custom error type.
  • Execution logging: Added a logging function to track execution times of concurrent tasks.

These improvements make the error handling system more robust, especially for real-world applications where failures can occur intermittently and tasks need to be managed carefully.

Fixes #130

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

  • Ran unit tests to ensure retry and timeout mechanisms work correctly.
  • Tested sequential execution to verify error accumulation and stopping on critical errors.
  • Tested concurrent execution with logging to ensure execution times are accurately logged.
  • (Any other specific tests relevant to your changes)

Sorry, something went wrong.

UTSAVS26 added 3 commits March 7, 2025 15:22

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
…and advanced error handling

This commit introduces several improvements to the error execution utilities to make them more robust and production-ready. The following changes have been implemented:

1. **Timeout and Cancellation Support**:  
   - Updated `ErrExec` and `ErrExecWithTimeout` to support context-based cancellation and timeout. This ensures that functions can be terminated early if they take too long or if the operation is canceled.

2. **Retry Logic**:  
   - Added a `RetryExec` function to retry failed functions a configurable number of times with delays in between retries.  
   - Added `ErrExecWithRetry` to execute functions concurrently while automatically retrying any failed ones.

3. **Advanced Error Handling**:  
   - Enhanced `ErrExecSequential` to accumulate errors and stop execution based on custom error types (e.g., stop on `CustomError` with a critical severity).  
   - Introduced `CustomError` with logic to control whether execution should stop upon encountering a specific error.

4. **Logging and Monitoring**:  
   - Added `LogExecution` to log the execution time of functions. This helps in monitoring performance and debugging execution times.

These improvements make the utilities more flexible, resilient, and suitable for handling complex scenarios in production systems, such as dealing with timeouts, retries, and advanced error handling.

Signed-off-by: UTSAV SINGHAL <[email protected]>

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
…n-utils

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
…ogic, and logging

- Added timeout and cancellation support to ErrExec and ErrExecWithTimeout functions.
- Introduced retry logic in RetryExec to handle temporary failures with a configurable retry count and delay.
- Updated ErrExecSequential to support more flexible error accumulation and early termination on critical errors using CustomError.
- Added LogExecution to track function execution time, integrated with ErrExecWithLogging for concurrent function execution.
- Improved error handling for functions, allowing for retries and graceful error reporting.

These changes improve the robustness and flexibility of error handling in concurrent and sequential function executions.

Signed-off-by: UTSAV SINGHAL <[email protected]>
@UTSAVS26
Copy link
Author

UTSAVS26 commented Mar 16, 2025

Hi @shubham19may @zriyanshdz ,please review this PR and update if any necessary changes required.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
@zriyanshdz
Copy link
Collaborator

cc - @shubham19may @hash-data

Copy link
Collaborator

@hash-data hash-data left a comment

Choose a reason for hiding this comment

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

It seems, these changes are not necessary. Can you take some important issues that are required.

Thanks

func ErrExec(functions ...func() error) error {
group, _ := errgroup.WithContext(context.Background())
group, ctx := errgroup.WithContext(context.Background())
Copy link
Collaborator

Choose a reason for hiding this comment

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

this ctx is not passed to any function so no cancellation will happen.

Comment on lines +19 to +26
group.Go(func() error {
select {
case <-ctx.Done(): // Check if the context is canceled or times out
return ctx.Err()
default:
return one()
}
})
Copy link
Collaborator

Choose a reason for hiding this comment

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

not required

Comment on lines +55 to +68
func RetryExec(function func() error, retries int, delay time.Duration) error {
var err error
for i := 0; i <= retries; i++ {
err = function()
if err == nil {
return nil // Function succeeded
}
log.Printf("Attempt %d failed: %v", i+1, err)
time.Sleep(delay) // Wait before retrying
}

return fmt.Errorf("failed after %d retries: %w", retries, err)
}

Copy link
Collaborator

Choose a reason for hiding this comment

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

already available check backoff

Comment on lines +115 to +146
// CustomError represents a custom error type with an additional field to indicate if execution should stop.
type CustomError struct {
Message string
Severity string
}

func (e *CustomError) Error() string {
return e.Message
}

// ShouldStop checks if the custom error indicates that execution should be halted.
func (e *CustomError) ShouldStop() bool {
return e.Severity == "critical" // Example logic: Stop on "critical" errors
}

// LogExecution logs the execution of a function (can be customized as needed).
func LogExecution(functionName string, startTime time.Time) {
duration := time.Since(startTime)
log.Printf("Function '%s' executed in %v", functionName, duration)
}

// ErrExecWithLogging executes a list of functions concurrently and logs execution time for each.
func ErrExecWithLogging(functions ...func() error) error {
group, ctx := errgroup.WithContext(context.Background())

for _, one := range functions {
group.Go(func() error {
startTime := time.Now()
defer LogExecution("Function", startTime) // Log execution after function completes
return one()
})
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

dont think so it is required right now.

@shubham19may
Copy link
Contributor

@UTSAVS26 closing this as currently its not needed. most of the changes done are not needed or already implemented as a part of other function.

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.

Enhance Error Execution Utilities: Add Retry, Timeout, Cancellation, and Advanced Error Handling
4 participants