mcp: use golang.org/x/time/rate for LoggingHandler rate limiting (#927)
Replaces the simple time-interval check in `LoggingHandler` with a standard `rate.Limiter` from `golang.org/x/time/rate`, as suggested by the existing TODO comment. This provides a well-tested implementation and removes the need for manual `lastMessageSent` tracking. The rate (`1/MinInterval`) and burst (1) match the previous behavior exactly. /cc @jba Closes #924 --------- Signed-off-by: wucm667 <stevenwucongmin@gmail.com> Co-authored-by: Jonathan Amsterdam <jba@users.noreply.github.com> Co-authored-by: Maciej Kisiel <mkisiel@google.com>
This commit is contained in:
parent
06c5f290f2
commit
9604499eed
1 changed files with 13 additions and 13 deletions
|
|
@ -13,6 +13,8 @@ import (
|
|||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
// Logging levels.
|
||||
|
|
@ -83,10 +85,10 @@ type LoggingHandler struct {
|
|||
// Ensures that the buffer reset is atomic with the write (see Handle).
|
||||
// A pointer so that clones share the mutex. See
|
||||
// https://github.com/golang/example/blob/master/slog-handler-guide/README.md#getting-the-mutex-right.
|
||||
mu *sync.Mutex
|
||||
lastMessageSent time.Time // for rate-limiting
|
||||
buf *bytes.Buffer
|
||||
handler slog.Handler
|
||||
mu *sync.Mutex
|
||||
limiter *rate.Limiter // for rate-limiting
|
||||
buf *bytes.Buffer
|
||||
handler slog.Handler
|
||||
}
|
||||
|
||||
// ensureLogger returns l if non-nil, otherwise a discard logger.
|
||||
|
|
@ -118,6 +120,9 @@ func NewLoggingHandler(ss *ServerSession, opts *LoggingHandlerOptions) *LoggingH
|
|||
}
|
||||
if opts != nil {
|
||||
lh.opts = *opts
|
||||
if opts.MinInterval > 0 {
|
||||
lh.limiter = rate.NewLimiter(rate.Every(opts.MinInterval), 1)
|
||||
}
|
||||
}
|
||||
return lh
|
||||
}
|
||||
|
|
@ -157,11 +162,7 @@ func (h *LoggingHandler) Handle(ctx context.Context, r slog.Record) error {
|
|||
|
||||
func (h *LoggingHandler) handle(ctx context.Context, r slog.Record) error {
|
||||
// Observe the rate limit.
|
||||
// TODO(jba): use golang.org/x/time/rate.
|
||||
h.mu.Lock()
|
||||
skip := time.Since(h.lastMessageSent) < h.opts.MinInterval
|
||||
h.mu.Unlock()
|
||||
if skip {
|
||||
if h.limiter != nil && !h.limiter.Allow() {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -184,10 +185,6 @@ func (h *LoggingHandler) handle(ctx context.Context, r slog.Record) error {
|
|||
return err
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
h.lastMessageSent = time.Now()
|
||||
h.mu.Unlock()
|
||||
|
||||
params := &LoggingMessageParams{
|
||||
Logger: h.opts.LoggerName,
|
||||
Level: slogLevelToMCP(r.Level),
|
||||
|
|
|
|||
Loading…
Reference in a new issue