Repository navigation
feat: retry Telegram FLOOD_WAIT instead of failing media groups #199
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pesh178
wants to merge
2
commits into
EverythingSuckz:main
Choose a base branch
from
pesh178:fix/flood-wait-retry
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,20 +1,84 @@ | ||
| package bot | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "EverythingSuckz/fsb/config" | ||
|
|
||
| "github.com/gotd/contrib/middleware/floodwait" | ||
| "github.com/gotd/contrib/middleware/ratelimit" | ||
| "github.com/gotd/td/bin" | ||
| "github.com/gotd/td/telegram" | ||
| "github.com/gotd/td/tg" | ||
| "github.com/gotd/td/tgerr" | ||
| "go.uber.org/zap" | ||
| "golang.org/x/time/rate" | ||
| ) | ||
|
|
||
| // floodWaitLogger reports FLOOD_WAIT answers from Telegram. It sits between the | ||
| // waiter and the rate limiter, so every single attempt that got throttled is | ||
| // logged, not just the final failure. | ||
| type floodWaitLogger struct { | ||
| log *zap.Logger | ||
| } | ||
|
|
||
| func (m floodWaitLogger) Handle(next tg.Invoker) telegram.InvokeFunc { | ||
| return func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { | ||
| err := next.Invoke(ctx, input, output) | ||
| if d, ok := tgerr.AsFloodWait(err); ok { | ||
| m.log.Warn("Telegram asked to wait, retrying", | ||
| zap.String("method", methodName(input)), | ||
| zap.Duration("wait", d), | ||
| ) | ||
| } | ||
| return err | ||
| } | ||
| } | ||
|
|
||
| // methodName strips the generated type decoration, e.g. | ||
| // *tg.MessagesForwardMessagesRequest becomes MessagesForwardMessages. | ||
| func methodName(input bin.Encoder) string { | ||
| name := fmt.Sprintf("%T", input) | ||
| name = strings.TrimPrefix(name, "*tg.") | ||
| name = strings.TrimSuffix(name, "Request") | ||
| return name | ||
| } | ||
|
|
||
| // GetFloodMiddleware returns the middleware chain used by every Telegram | ||
| // client (main bot, workers and userbot). | ||
| // | ||
| // Order matters: middlewares are applied in slice order, so the waiter is the | ||
| // outermost one and its retries go through the logger and the rate limiter | ||
| // again. That way a retried request is both logged and rate limited. | ||
| func GetFloodMiddleware(log *zap.Logger) []telegram.Middleware { | ||
| waiter := floodwait.NewSimpleWaiter().WithMaxRetries(10) | ||
| ratelimiter := ratelimit.New(rate.Every(time.Millisecond*100), 5) | ||
| return newFloodMiddleware( | ||
| log.Named("FloodWait"), | ||
| uint(config.ValueOf.FloodWaitMaxRetries), | ||
| time.Duration(config.ValueOf.FloodWaitMaxWaitSec)*time.Second, | ||
| time.Duration(config.ValueOf.RateLimitIntervalMs)*time.Millisecond, | ||
| config.ValueOf.RateLimitBurst, | ||
| ) | ||
| } | ||
|
|
||
| // newFloodMiddleware builds the chain from explicit values so it can be | ||
| // exercised in tests without touching the global config. | ||
| func newFloodMiddleware( | ||
| log *zap.Logger, | ||
| maxRetries uint, | ||
| maxWait time.Duration, | ||
| interval time.Duration, | ||
| burst int, | ||
| ) []telegram.Middleware { | ||
| waiter := floodwait.NewSimpleWaiter(). | ||
| WithMaxRetries(maxRetries). | ||
| WithMaxWait(maxWait) | ||
| limiter := ratelimit.New(rate.Every(interval), burst) | ||
| return []telegram.Middleware{ | ||
| waiter, | ||
| ratelimiter, | ||
| floodWaitLogger{log: log}, | ||
| limiter, | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| package bot | ||
|
|
||
| import ( | ||
| "context" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/gotd/td/bin" | ||
| "github.com/gotd/td/telegram" | ||
| "github.com/gotd/td/tg" | ||
| "github.com/gotd/td/tgerr" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| func chain(middlewares []telegram.Middleware, next tg.Invoker) tg.Invoker { | ||
| for i := len(middlewares) - 1; i >= 0; i-- { | ||
| next = middlewares[i].Handle(next) | ||
| } | ||
| return next | ||
| } | ||
|
|
||
| func TestFloodMiddlewareRetriesFloodWait(t *testing.T) { | ||
| var attempts atomic.Int32 | ||
| invoker := telegram.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { | ||
| if attempts.Add(1) < 2 { | ||
| return tgerr.New(420, "FLOOD_WAIT_0") | ||
| } | ||
| return nil | ||
| }) | ||
|
|
||
| mw := newFloodMiddleware(zap.NewNop(), 5, time.Minute, time.Millisecond, 1) | ||
| if err := chain(mw, invoker).Invoke(context.Background(), &tg.HelpGetConfigRequest{}, nil); err != nil { | ||
| t.Fatalf("invoke returned error: %v", err) | ||
| } | ||
| if got := attempts.Load(); got != 2 { | ||
| t.Fatalf("attempts = %d, want 2", got) | ||
| } | ||
| } | ||
|
|
||
| func TestFloodMiddlewareHonoursMaxWait(t *testing.T) { | ||
| var attempts atomic.Int32 | ||
| invoker := telegram.InvokeFunc(func(ctx context.Context, input bin.Encoder, output bin.Decoder) error { | ||
| attempts.Add(1) | ||
| return tgerr.New(420, "FLOOD_WAIT_600") | ||
| }) | ||
|
|
||
| mw := newFloodMiddleware(zap.NewNop(), 5, 10*time.Second, time.Millisecond, 1) | ||
| err := chain(mw, invoker).Invoke(context.Background(), &tg.HelpGetConfigRequest{}, nil) | ||
| if err == nil { | ||
| t.Fatal("invoke returned nil, want error") | ||
| } | ||
| if _, ok := tgerr.AsFloodWait(err); !ok { | ||
| t.Fatalf("error %v does not wrap the flood wait", err) | ||
| } | ||
| if got := attempts.Load(); got != 1 { | ||
| t.Fatalf("attempts = %d, want 1", got) | ||
| } | ||
| } | ||
|
|
||
| func TestMethodName(t *testing.T) { | ||
| if got := methodName(&tg.MessagesForwardMessagesRequest{}); got != "MessagesForwardMessages" { | ||
| t.Fatalf("methodName = %q", got) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package utils | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "time" | ||
|
|
||
| "github.com/gotd/td/tgerr" | ||
| ) | ||
|
|
||
| // DescribeFloodWait turns a FLOOD_WAIT error into a message a user can act on. | ||
| // It returns false when err is not a flood wait. | ||
| func DescribeFloodWait(err error) (string, bool) { | ||
| if err == nil { | ||
| return "", false | ||
| } | ||
| wait, ok := tgerr.AsFloodWait(err) | ||
| if !ok { | ||
| return "", false | ||
| } | ||
| if wait <= 0 { | ||
| wait = time.Second | ||
| } | ||
| return fmt.Sprintf( | ||
| "Telegram is rate limiting this bot, please try again in %s.", | ||
| wait.Round(time.Second), | ||
| ), true | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| package utils | ||
|
|
||
| import ( | ||
| "errors" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/gotd/td/tgerr" | ||
| ) | ||
|
|
||
| func TestDescribeFloodWait(t *testing.T) { | ||
| if _, ok := DescribeFloodWait(nil); ok { | ||
| t.Fatal("nil error described as flood wait") | ||
| } | ||
| if _, ok := DescribeFloodWait(errors.New("boom")); ok { | ||
| t.Fatal("generic error described as flood wait") | ||
| } | ||
| hint, ok := DescribeFloodWait(tgerr.New(420, "FLOOD_WAIT_7")) | ||
| if !ok { | ||
| t.Fatal("flood wait not detected") | ||
| } | ||
| if !strings.Contains(hint, "7s") { | ||
| t.Fatalf("hint = %q, want the wait duration", hint) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.