Skip to content

Add context timeout middleware - #2380

Merged
aldas merged 11 commits into
labstack:masterfrom
hakankutluay:master
Feb 1, 2023
Merged

aldas merged 11 commits into
labstack:masterfrom
hakankutluay:master

Conversation

@hakankutluay

@hakankutluay hakankutluay commented Jan 19, 2023 •

Copy link
Copy Markdown
Contributor

We need to introduce a new middleware (middleware.ContextTimeout()) that creates context with timeout and injects ContextWithTimeout to c.Request().Context(). If the handler returns an error that wraps context.DeadlineExceeded, it returns Service Unavailable (503)

This fixes #2379, #2306.

Co-authored-by: @erhanakp

Add context timeout middleware 

Co-authored-by: Erhan Akpınar <erhan.akpinar@yemeksepeti.com>
@hakankutluay hakankutluay changed the title Add context timeout middleware (#1) Add context timeout middleware Jan 19, 2023

@aldas aldas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think this error handling part is too rigid. It should be left to developer to decide.

Also err = c.Request().Context().Err() should not be needed as then context timeouts your timeout aware methods should return that error. unless you are warpping somewhere you should not need to check it from request.

and middlewares should not handle errors like that return c.JSON(http.StatusServiceUnavailable, suResponse)

this means that now your middleware "commits" that response and midlewares up in stack can not handle errors anymore

I propose something like that instead:

type ContextTimeoutConfig struct {
	Skipper      middleware.Skipper
	ErrorHandler func(err error, c echo.Context) error
	Timeout      time.Duration
}

func ContextTimeout(timeout time.Duration) echo.MiddlewareFunc {
	return ContextTimeoutWithConfig(ContextTimeoutConfig{Timeout: timeout})
}

func ContextTimeoutWithConfig(config ContextTimeoutConfig) echo.MiddlewareFunc {
	return config.ToMiddleware()
}

func (config ContextTimeoutConfig) ToMiddleware() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			if config.Skipper(c) || config.Timeout == 0 {
				return next(c)
			}

			timeoutContext, cancel := context.WithTimeout(c.Request().Context(), config.Timeout)
			defer cancel()

			c.SetRequest(c.Request().WithContext(timeoutContext))

			err := next(c)
			if err != nil && config.ErrorHandler != nil {
				return config.ErrorHandler(err, c)
			}
			return err
		}
	}
}

@hakankutluay

Copy link
Copy Markdown
Contributor Author

Thanks @aldas for your valuable feedback and comments.

Would you please review the updated PR?

Comment thread middleware/context_timeout.go Outdated
Comment thread middleware/context_timeout.go Outdated
Comment thread middleware/context_timeout.go Outdated
Comment thread middleware/context_timeout.go Outdated
Comment thread middleware/context_timeout_test.go Outdated
Comment thread middleware/context_timeout_test.go Outdated
Comment thread middleware/context_timeout_test.go Outdated
Comment thread middleware/context_timeout_test.go Outdated
hakankutluay and others added 2 commits January 22, 2023 13:34
* remove example
* remove TestContextTimeoutWithErrorMessage
* remove TestContextTimeoutRecoversPanic
* remove DefaultContextTimeoutConfig
* add creator function
* remove TestContextTimeoutWithFullEchoStack
@hakankutluay
hakankutluay requested a review from aldas January 24, 2023 16:24
Comment thread middleware/context_timeout.go Outdated
Comment thread middleware/context_timeout.go Outdated
@hakankutluay
hakankutluay requested a review from aldas January 25, 2023 07:13
@hakankutluay

Copy link
Copy Markdown
Contributor Author

@aldas, thanks for your comments. all change requests are completed.

@codecov

codecov Bot commented Jan 26, 2023 •

Copy link
Copy Markdown

Codecov Report

Base: 92.75% // Head: 92.80% // Increases project coverage by +0.05% 🎉

Coverage data is based on head (0f8434b) compared to base (24a3061).
Patch coverage: 100.00% of modified lines in pull request are covered.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2380      +/-   ##
==========================================
+ Coverage   92.75%   92.80%   +0.05%     
==========================================
  Files          37       38       +1     
  Lines        4473     4506      +33     
==========================================
+ Hits         4149     4182      +33     
  Misses        236      236              
  Partials       88       88              
Impacted Files Coverage Δ
middleware/context_timeout.go 100.00% <100.00%> (ø)
router.go 97.79% <0.00%> (-0.01%) ⬇️

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@aldas aldas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

coverage.coverprofile file is added here by accident with latest commit and should be removed

@erhanakp

erhanakp commented Jan 27, 2023 •

Copy link
Copy Markdown
Contributor

coverage.coverprofile file is added here by accident with latest commit and should be removed @aldas

👍 removed

@aldas aldas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

erhanakp and others added 2 commits January 28, 2023 20:19
- remove unnecessary control
- change sleep
- change stop execution
- increase timeouts golang/go#17696

Co-authored-by: @erhanakp
@hakankutluay

Copy link
Copy Markdown
Contributor Author

@aldas timeout durations increased to fix tests.

@aldas aldas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@aldas
aldas merged commit 82a964c into labstack:master Feb 1, 2023
@HeCorr

HeCorr commented May 24, 2023

Copy link
Copy Markdown

Just checking, was #2306 meant to be auto-closed with the merge of this? Because it's still open.

@aldas

aldas commented May 24, 2023

Copy link
Copy Markdown
Contributor

@HeCorr , no idea. that issue is probably long running file download wrapped by timeout, that does not finish by the time context gets reused. but this is a wild guess as there are no meaningful information

@HeCorr

HeCorr commented Jun 23, 2023 •

Copy link
Copy Markdown

@aldas I asked because it seems @hakankutluay meant to close it together with #2379 by the way he wrote it:
image

but the fixes/closes keywords don't seem to support a comma-separated list of issues, so only the first one was closed.

@aldas

aldas commented Jun 23, 2023

Copy link
Copy Markdown
Contributor

I closed #2306 this MW is answer for some of the problems there.

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.

ContextWithTimeout middleware feature request

4 participants