teldrive/internal/retry/retry.go

54 lines
1,001 B
Go
Raw Normal View History

2023-11-25 12:31:29 +08:00
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",
2024-02-04 15:53:27 +08:00
"RPC_CALL_FAIL",
"RPC_MCGET_FAIL",
"WORKER_BUSY_TOO_LONG_RETRY",
2024-03-20 01:01:56 +08:00
"memory limit exit",
}
2023-11-25 12:31:29 +08:00
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...),
2023-11-25 12:31:29 +08:00
}
}