From afb63d6437a6955124e5339ec9ff2d14ce7f575e Mon Sep 17 00:00:00 2001 From: Aleksandr Razumov Date: Fri, 29 Nov 2024 10:20:49 +0300 Subject: [PATCH] feat(telegram): add OnSelfError Ref: #1458 --- telegram/client.go | 4 ++++ telegram/connect.go | 6 ++++++ telegram/options.go | 8 ++++++++ 3 files changed, 18 insertions(+) diff --git a/telegram/client.go b/telegram/client.go index 32ffa4eaf1..bd39d5acd1 100644 --- a/telegram/client.go +++ b/telegram/client.go @@ -134,6 +134,9 @@ type Client struct { // onTransfer is called in transfer. onTransfer AuthTransferHandler + + // onSelfError is called on error calling Self(). + onSelfError func(ctx context.Context, err error) error } // NewClient creates new unstarted client. @@ -169,6 +172,7 @@ func NewClient(appID int, appHash string, opt Options) *Client { noUpdatesMode: opt.NoUpdates, mw: opt.Middlewares, onTransfer: opt.OnTransfer, + onSelfError: opt.OnSelfError, } if opt.TracerProvider != nil { client.tracer = opt.TracerProvider.Tracer(oteltg.Name) diff --git a/telegram/connect.go b/telegram/connect.go index 3b359dbc3d..92ec227cef 100644 --- a/telegram/connect.go +++ b/telegram/connect.go @@ -30,6 +30,12 @@ func (c *Client) runUntilRestart(ctx context.Context) error { if !auth.IsUnauthorized(err) { c.log.Warn("Got error on self", zap.Error(err)) } + if h := c.onSelfError; h != nil { + // Help with https://github.com/gotd/td/issues/1458. + if err := h(ctx, err); err != nil { + return errors.Wrap(err, "onSelfError") + } + } return nil } diff --git a/telegram/options.go b/telegram/options.go index 9c271fd149..a35e3f85d3 100644 --- a/telegram/options.go +++ b/telegram/options.go @@ -100,6 +100,14 @@ type Options struct { // OnTransfer is called during authorization transfer. // See [AuthTransferHandler] for details. OnTransfer AuthTransferHandler + + // OnSelfError is called when client receives error calling Self() on connect. + // Return error to stop reconnection. + // + // NB: this method is called immediately after connection, so it's not expected to be + // non-nil error on first connection before auth, so it's safe to return nil until + // first successful auth. + OnSelfError func(ctx context.Context, err error) error } func (opt *Options) setDefaults() {