You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.go 3.5KB

Add context cache as a request level cache (#22294) To avoid duplicated load of the same data in an HTTP request, we can set a context cache to do that. i.e. Some pages may load a user from a database with the same id in different areas on the same page. But the code is hidden in two different deep logic. How should we share the user? As a result of this PR, now if both entry functions accept `context.Context` as the first parameter and we just need to refactor `GetUserByID` to reuse the user from the context cache. Then it will not be loaded twice on an HTTP request. But of course, sometimes we would like to reload an object from the database, that's why `RemoveContextData` is also exposed. The core context cache is here. It defines a new context ```go type cacheContext struct { ctx context.Context data map[any]map[any]any lock sync.RWMutex } var cacheContextKey = struct{}{} func WithCacheContext(ctx context.Context) context.Context { return context.WithValue(ctx, cacheContextKey, &cacheContext{ ctx: ctx, data: make(map[any]map[any]any), }) } ``` Then you can use the below 4 methods to read/write/del the data within the same context. ```go func GetContextData(ctx context.Context, tp, key any) any func SetContextData(ctx context.Context, tp, key, value any) func RemoveContextData(ctx context.Context, tp, key any) func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error) ``` Then let's take a look at how `system.GetString` implement it. ```go func GetSetting(ctx context.Context, key string) (string, error) { return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) { return cache.GetString(genSettingCacheKey(key), func() (string, error) { res, err := GetSettingNoCache(ctx, key) if err != nil { return "", err } return res.SettingValue, nil }) }) } ``` First, it will check if context data include the setting object with the key. If not, it will query from the global cache which may be memory or a Redis cache. If not, it will get the object from the database. In the end, if the object gets from the global cache or database, it will be set into the context cache. An object stored in the context cache will only be destroyed after the context disappeared.
1 year ago
Rewrite logger system (#24726) ## ⚠️ Breaking The `log.<mode>.<logger>` style config has been dropped. If you used it, please check the new config manual & app.example.ini to make your instance output logs as expected. Although many legacy options still work, it's encouraged to upgrade to the new options. The SMTP logger is deleted because SMTP is not suitable to collect logs. If you have manually configured Gitea log options, please confirm the logger system works as expected after upgrading. ## Description Close #12082 and maybe more log-related issues, resolve some related FIXMEs in old code (which seems unfixable before) Just like rewriting queue #24505 : make code maintainable, clear legacy bugs, and add the ability to support more writers (eg: JSON, structured log) There is a new document (with examples): `logging-config.en-us.md` This PR is safer than the queue rewriting, because it's just for logging, it won't break other logic. ## The old problems The logging system is quite old and difficult to maintain: * Unclear concepts: Logger, NamedLogger, MultiChannelledLogger, SubLogger, EventLogger, WriterLogger etc * Some code is diffuclt to konw whether it is right: `log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs `log.DelLogger("console")` * The old system heavily depends on ini config system, it's difficult to create new logger for different purpose, and it's very fragile. * The "color" trick is difficult to use and read, many colors are unnecessary, and in the future structured log could help * It's difficult to add other log formats, eg: JSON format * The log outputer doesn't have full control of its goroutine, it's difficult to make outputer have advanced behaviors * The logs could be lost in some cases: eg: no Fatal error when using CLI. * Config options are passed by JSON, which is quite fragile. * INI package makes the KEY in `[log]` section visible in `[log.sub1]` and `[log.sub1.subA]`, this behavior is quite fragile and would cause more unclear problems, and there is no strong requirement to support `log.<mode>.<logger>` syntax. ## The new design See `logger.go` for documents. ## Screenshot <details> ![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff) ![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9) ![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee) </details> ## TODO * [x] add some new tests * [x] fix some tests * [x] test some sub-commands (manually ....) --------- Co-authored-by: Jason Song <i@wolfogre.com> Co-authored-by: delvh <dev.lh@web.de> Co-authored-by: Giteabot <teabot@gitea.io>
1 year ago
Rewrite logger system (#24726) ## ⚠️ Breaking The `log.<mode>.<logger>` style config has been dropped. If you used it, please check the new config manual & app.example.ini to make your instance output logs as expected. Although many legacy options still work, it's encouraged to upgrade to the new options. The SMTP logger is deleted because SMTP is not suitable to collect logs. If you have manually configured Gitea log options, please confirm the logger system works as expected after upgrading. ## Description Close #12082 and maybe more log-related issues, resolve some related FIXMEs in old code (which seems unfixable before) Just like rewriting queue #24505 : make code maintainable, clear legacy bugs, and add the ability to support more writers (eg: JSON, structured log) There is a new document (with examples): `logging-config.en-us.md` This PR is safer than the queue rewriting, because it's just for logging, it won't break other logic. ## The old problems The logging system is quite old and difficult to maintain: * Unclear concepts: Logger, NamedLogger, MultiChannelledLogger, SubLogger, EventLogger, WriterLogger etc * Some code is diffuclt to konw whether it is right: `log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs `log.DelLogger("console")` * The old system heavily depends on ini config system, it's difficult to create new logger for different purpose, and it's very fragile. * The "color" trick is difficult to use and read, many colors are unnecessary, and in the future structured log could help * It's difficult to add other log formats, eg: JSON format * The log outputer doesn't have full control of its goroutine, it's difficult to make outputer have advanced behaviors * The logs could be lost in some cases: eg: no Fatal error when using CLI. * Config options are passed by JSON, which is quite fragile. * INI package makes the KEY in `[log]` section visible in `[log.sub1]` and `[log.sub1.subA]`, this behavior is quite fragile and would cause more unclear problems, and there is no strong requirement to support `log.<mode>.<logger>` syntax. ## The new design See `logger.go` for documents. ## Screenshot <details> ![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff) ![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9) ![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee) </details> ## TODO * [x] add some new tests * [x] fix some tests * [x] test some sub-commands (manually ....) --------- Co-authored-by: Jason Song <i@wolfogre.com> Co-authored-by: delvh <dev.lh@web.de> Co-authored-by: Giteabot <teabot@gitea.io>
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package common
  4. import (
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "code.gitea.io/gitea/modules/cache"
  9. "code.gitea.io/gitea/modules/context"
  10. "code.gitea.io/gitea/modules/process"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/web/middleware"
  13. "code.gitea.io/gitea/modules/web/routing"
  14. "gitea.com/go-chi/session"
  15. "github.com/chi-middleware/proxy"
  16. chi "github.com/go-chi/chi/v5"
  17. )
  18. // ProtocolMiddlewares returns HTTP protocol related middlewares, and it provides a global panic recovery
  19. func ProtocolMiddlewares() (handlers []any) {
  20. // first, normalize the URL path
  21. handlers = append(handlers, stripSlashesMiddleware)
  22. // prepare the ContextData and panic recovery
  23. handlers = append(handlers, func(next http.Handler) http.Handler {
  24. return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  25. defer func() {
  26. if err := recover(); err != nil {
  27. RenderPanicErrorPage(resp, req, err) // it should never panic
  28. }
  29. }()
  30. req = req.WithContext(middleware.WithContextData(req.Context()))
  31. next.ServeHTTP(resp, req)
  32. })
  33. })
  34. handlers = append(handlers, func(next http.Handler) http.Handler {
  35. return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  36. ctx, _, finished := process.GetManager().AddTypedContext(req.Context(), fmt.Sprintf("%s: %s", req.Method, req.RequestURI), process.RequestProcessType, true)
  37. defer finished()
  38. next.ServeHTTP(context.WrapResponseWriter(resp), req.WithContext(cache.WithCacheContext(ctx)))
  39. })
  40. })
  41. if setting.ReverseProxyLimit > 0 {
  42. opt := proxy.NewForwardedHeadersOptions().
  43. WithForwardLimit(setting.ReverseProxyLimit).
  44. ClearTrustedProxies()
  45. for _, n := range setting.ReverseProxyTrustedProxies {
  46. if !strings.Contains(n, "/") {
  47. opt.AddTrustedProxy(n)
  48. } else {
  49. opt.AddTrustedNetwork(n)
  50. }
  51. }
  52. handlers = append(handlers, proxy.ForwardedHeaders(opt))
  53. }
  54. if setting.IsRouteLogEnabled() {
  55. handlers = append(handlers, routing.NewLoggerHandler())
  56. }
  57. if setting.IsAccessLogEnabled() {
  58. handlers = append(handlers, context.AccessLogger())
  59. }
  60. return handlers
  61. }
  62. func stripSlashesMiddleware(next http.Handler) http.Handler {
  63. return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  64. // First of all escape the URL RawPath to ensure that all routing is done using a correctly escaped URL
  65. req.URL.RawPath = req.URL.EscapedPath()
  66. urlPath := req.URL.RawPath
  67. rctx := chi.RouteContext(req.Context())
  68. if rctx != nil && rctx.RoutePath != "" {
  69. urlPath = rctx.RoutePath
  70. }
  71. sanitizedPath := &strings.Builder{}
  72. prevWasSlash := false
  73. for _, chr := range strings.TrimRight(urlPath, "/") {
  74. if chr != '/' || !prevWasSlash {
  75. sanitizedPath.WriteRune(chr)
  76. }
  77. prevWasSlash = chr == '/'
  78. }
  79. if rctx == nil {
  80. req.URL.Path = sanitizedPath.String()
  81. } else {
  82. rctx.RoutePath = sanitizedPath.String()
  83. }
  84. next.ServeHTTP(resp, req)
  85. })
  86. }
  87. func Sessioner() func(next http.Handler) http.Handler {
  88. return session.Sessioner(session.Options{
  89. Provider: setting.SessionConfig.Provider,
  90. ProviderConfig: setting.SessionConfig.ProviderConfig,
  91. CookieName: setting.SessionConfig.CookieName,
  92. CookiePath: setting.SessionConfig.CookiePath,
  93. Gclifetime: setting.SessionConfig.Gclifetime,
  94. Maxlifetime: setting.SessionConfig.Maxlifetime,
  95. Secure: setting.SessionConfig.Secure,
  96. SameSite: setting.SessionConfig.SameSite,
  97. Domain: setting.SessionConfig.Domain,
  98. })
  99. }