mirror of
https://github.com/tgdrive/teldrive.git
synced 2024-11-14 11:45:29 +08:00
49 lines
911 B
Go
49 lines
911 B
Go
package retry
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/go-faster/errors"
|
|
"github.com/gotd/td/bin"
|
|
"github.com/gotd/td/telegram"
|
|
"github.com/gotd/td/tg"
|
|
"github.com/gotd/td/tgerr"
|
|
)
|
|
|
|
var internalErrors = []string{
|
|
"Timedout",
|
|
"No workers running",
|
|
}
|
|
|
|
type retry struct {
|
|
max int
|
|
errors []string
|
|
}
|
|
|
|
func (r retry) Handle(next tg.Invoker) telegram.InvokeFunc {
|
|
return func(ctx context.Context, input bin.Encoder, output bin.Decoder) error {
|
|
retries := 0
|
|
|
|
for retries < r.max {
|
|
if err := next.Invoke(ctx, input, output); err != nil {
|
|
if tgerr.Is(err, r.errors...) {
|
|
retries++
|
|
continue
|
|
}
|
|
return errors.Wrap(err, "retry middleware skip")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
return fmt.Errorf("retry limit reached after %d attempts", r.max)
|
|
}
|
|
}
|
|
|
|
func New(max int, errors ...string) telegram.Middleware {
|
|
return retry{
|
|
max: max,
|
|
errors: append(errors, internalErrors...),
|
|
}
|
|
}
|