Skip to content

Commit

Permalink
Merge pull request #837 from gotd/feat/add-exchange-timeout-option
Browse files Browse the repository at this point in the history
feat(client): add ExchangeTimeout, DialTimeout to options
  • Loading branch information
ernado authored Aug 7, 2022
2 parents 26f5d01 + b47cc20 commit 97c64c0
Show file tree
Hide file tree
Showing 29 changed files with 80 additions and 78 deletions.
4 changes: 2 additions & 2 deletions bin/bin.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
// This package is not intended to be used directly.
//
// Ref:
// * https://core.telegram.org/mtproto/serialize
// * https://core.telegram.org/mtproto/TL-abstract-types
// - https://core.telegram.org/mtproto/serialize
// - https://core.telegram.org/mtproto/TL-abstract-types
package bin

// Basic TL types.
Expand Down
2 changes: 1 addition & 1 deletion clock/clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ func StopTimer(t Timer) {
}
}

// Ticker abstracts a channel that delivers ``ticks'' of a clock at intervals.
// Ticker abstracts a channel that delivers ticks of a clock at intervals.
type Ticker = neo.Ticker
2 changes: 1 addition & 1 deletion constant/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ package constant
// test authentication.
//
// Reference:
// * https://github.com/telegramdesktop/tdesktop/blob/5f665b8ecb48802cd13cfb48ec834b946459274a/docs/api_credentials.md
// - https://github.com/telegramdesktop/tdesktop/blob/5f665b8ecb48802cd13cfb48ec834b946459274a/docs/api_credentials.md
const (
TestAppID = 17349
TestAppHash = "344583e45741c457fe1862106095a5eb"
Expand Down
13 changes: 6 additions & 7 deletions gorules/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import (

// ZapPreferNoWith suggests replace expressions like
//
// l.With(...).Debug("")
// l.With(...).Debug("")
//
// to
//
// l.Debug("", ...).
// l.Debug("", ...).
//
// where l is a *zap.Logger.
func ZapPreferNoWith(m dsl.Matcher) {
Expand All @@ -25,11 +25,11 @@ func ZapPreferNoWith(m dsl.Matcher) {

// UberStyleErrors detects error messages like
//
// errors.Wrap(err, "failed to do something")
// errors.Wrap(err, "failed to do something")
//
// but you should avoid "failed to" and use
//
// errors.Wrap(err, "do something")
// errors.Wrap(err, "do something")
//
// according to https://github.com/uber-go/guide/blob/master/style.md#error-wrapping.
func UberStyleErrors(m dsl.Matcher) {
Expand All @@ -48,12 +48,11 @@ func UberStyleErrors(m dsl.Matcher) {

// UnnecessaryErrorFormat detects unnecessary error formatting like
//
// errors.New("error")
// errors.New("error")
//
// and suggests instead
//
// errors.New("error")
//
// errors.New("error")
func UnnecessaryErrorFormat(m dsl.Matcher) {
m.Match("fmt.Errorf($msg)").Suggest("errors.New($msg)")
m.Match("errors.Errorf($msg)").Suggest("errors.New($msg)")
Expand Down
1 change: 1 addition & 0 deletions internal/crypto/dh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
// See https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
//
// Values:
//
// gA is g_a
// dhPrime is dh_prime
// gB is g_b
Expand Down
2 changes: 1 addition & 1 deletion internal/crypto/doc.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Package crypto implements cryptographical primitives for MTproto.
//
// Reference:
// * https://core.telegram.org/mtproto/auth_key
// - https://core.telegram.org/mtproto/auth_key
package crypto
1 change: 1 addition & 0 deletions internal/crypto/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ func aesIV(sha256a, sha256b []byte, v *bin.Int256) {
// See https://core.telegram.org/mtproto/description#defining-aes-key-and-initialization-vector
//
// Example:
//
// key, iv := crypto.Keys(authKey, messageKey, crypto.Client)
// cipher, err := aes.NewCipher(key[:])
// if err != nil {
Expand Down
1 change: 1 addition & 0 deletions internal/crypto/keys_old.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func sha1d(r []byte, authKey Key, msgKey bin.Int128, x int) []byte {
// See https://core.telegram.org/mtproto/description_v1#defining-aes-key-and-initialization-vector
//
// Example:
//
// key, iv := crypto.OldKeys(authKey, messageKey, crypto.Client)
// cipher, err := aes.NewCipher(key[:])
// if err != nil {
Expand Down
14 changes: 6 additions & 8 deletions internal/gen/names.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,12 @@ func splitByWords(s string) []string {

// pascal converts the given name into a PascalCase.
//
// user_info => UserInfo
// full_name => FullName
// user_id => UserID
// full-admin => FullAdmin
// cdnConfig => CDNConfig
// cdn_1_config => CDN1Config
//
// user_info => UserInfo
// full_name => FullName
// user_id => UserID
// full-admin => FullAdmin
// cdnConfig => CDNConfig
// cdn_1_config => CDN1Config
func pascal(s string) string {
words := splitByWords(s)
return pascalWords(words)
Expand All @@ -107,7 +106,6 @@ func pascal(s string) string {
// full_name => fullName
// user_id => userID
// full-admin => fullAdmin
//
func camel(s string) string {
words := splitByWords(s)
if len(words) == 1 {
Expand Down
11 changes: 11 additions & 0 deletions internal/mtproto/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ func (c *Conn) createAuthKey(ctx context.Context) error {
c.exchangeLock.Lock()
defer c.exchangeLock.Unlock()

if ce := c.log.Check(zap.DebugLevel, "Initializing new key exchange"); ce != nil {
// Useful for debugging i/o timeout errors on tcp reads or writes.
fields := []zap.Field{
zap.Duration("timeout", c.exchangeTimeout),
}
if deadline, ok := ctx.Deadline(); ok {
fields = append(fields, zap.Time("context_deadline", deadline))
}
ce.Write(fields...)
}

r, err := exchange.NewExchanger(c.conn, c.dcID).
WithClock(c.clock).
WithLogger(c.log.Named("exchange")).
Expand Down
2 changes: 1 addition & 1 deletion internal/mtproto/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func (opt *Options) setDefaults() {
opt.MaxRetries = 5
}
if opt.DialTimeout == 0 {
opt.DialTimeout = 15 * time.Second
opt.DialTimeout = 35 * time.Second
}
if opt.ExchangeTimeout == 0 {
opt.ExchangeTimeout = exchange.DefaultTimeout
Expand Down
15 changes: 8 additions & 7 deletions internal/tdsync/cancel_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ type CancellableGroup struct {
// NewCancellableGroup creates new CancellableGroup.
//
// Example:
// g := NewCancellableGroup(ctx)
// g.Go(func(ctx context.Context) error {
// <-ctx.Done()
// return ctx.Err()
// })
// g.Cancel()
// g.Wait()
//
// g := NewCancellableGroup(ctx)
// g.Go(func(ctx context.Context) error {
// <-ctx.Done()
// return ctx.Err()
// })
// g.Cancel()
// g.Wait()
func NewCancellableGroup(parent context.Context) *CancellableGroup {
ctx, cancel := context.WithCancel(parent)
group, groupCtx := errgroup.WithContext(ctx)
Expand Down
3 changes: 2 additions & 1 deletion internal/testutil/external.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import (
// like TestExternalE2EConnect.
//
// Run all tests with following command in module root:
// GOTD_TEST_EXTERNAL=1 go test -v -run ^TestExternalE2E ./...
//
// GOTD_TEST_EXTERNAL=1 go test -v -run ^TestExternalE2E ./...
func SkipExternal(tb testing.TB) {
const env = "GOTD_TEST_EXTERNAL"

Expand Down
1 change: 0 additions & 1 deletion session/tdesktop/tdesktop.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ type Account struct {
// Shorthand for:
//
// ReadFS(os.DirFS(root), passcode)
//
func Read(root string, passcode []byte) ([]Account, error) {
return ReadFS(os.DirFS(root), passcode)
}
Expand Down
12 changes: 7 additions & 5 deletions telegram/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@ func sessionDir() (string, error) {
// using environment variables.
//
// Variables:
// SESSION_FILE: path to session file
// SESSION_DIR: path to session directory, if SESSION_FILE is not set
// ALL_PROXY, NO_PROXY: see https://pkg.go.dev/golang.org/x/net/proxy#FromEnvironment
//
// SESSION_FILE: path to session file
// SESSION_DIR: path to session directory, if SESSION_FILE is not set
// ALL_PROXY, NO_PROXY: see https://pkg.go.dev/golang.org/x/net/proxy#FromEnvironment
func OptionsFromEnvironment(opts Options) (Options, error) {
// Setting up session storage if not provided.
if opts.SessionStorage == nil {
Expand Down Expand Up @@ -77,8 +78,9 @@ func OptionsFromEnvironment(opts Options) (Options, error) {
// but does not connect to server.
//
// Variables:
// APP_ID: app_id of Telegram app.
// APP_HASH: app_hash of Telegram app.
//
// APP_ID: app_id of Telegram app.
// APP_HASH: app_hash of Telegram app.
func ClientFromEnvironment(opts Options) (*Client, error) {
appID, err := strconv.Atoi(os.Getenv("APP_ID"))
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion telegram/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const (
// test authentication.
//
// Reference:
// * https://github.com/telegramdesktop/tdesktop/blob/5f665b8ecb48802cd13cfb48ec834b946459274a/docs/api_credentials.md
// - https://github.com/telegramdesktop/tdesktop/blob/5f665b8ecb48802cd13cfb48ec834b946459274a/docs/api_credentials.md
const (
TestAppID = constant.TestAppID
TestAppHash = constant.TestAppHash
Expand Down
2 changes: 2 additions & 0 deletions telegram/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ func NewClient(appID int, appHash string, opt Options) *Client {
MaxRetries: opt.MaxRetries,
CompressThreshold: opt.CompressThreshold,
MessageID: opt.MessageID,
ExchangeTimeout: opt.ExchangeTimeout,
DialTimeout: opt.DialTimeout,
Clock: opt.Clock,

Types: getTypesMapping(),
Expand Down
4 changes: 2 additions & 2 deletions telegram/message/inline/message_geo.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func MessageGeo(point tg.InputGeoPointClass) *MessageMediaGeoBuilder {
// Heading sets for live locations¹, a direction in which the location moves, in degrees; 1-360.
//
// Links:
// 1) https://core.telegram.org/api/live-location
// 1. https://core.telegram.org/api/live-location
func (b *MessageMediaGeoBuilder) Heading(heading int) *MessageMediaGeoBuilder {
b.message.Heading = heading
return b
Expand All @@ -51,7 +51,7 @@ func (b *MessageMediaGeoBuilder) PeriodSeconds(period int) *MessageMediaGeoBuild
// alerts, in meters (0-100000)
//
// Links:
// 1) https://core.telegram.org/api/live-location
// 1. https://core.telegram.org/api/live-location
func (b *MessageMediaGeoBuilder) ProximityNotificationRadius(radius int) *MessageMediaGeoBuilder {
b.message.ProximityNotificationRadius = radius
return b
Expand Down
13 changes: 6 additions & 7 deletions telegram/message/join.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@ import (
// JoinLink joins to private chat using given link or hash.
// Input examples:
//
// t.me/+AAAAAAAAAAAAAAAA
// https://t.me/+AAAAAAAAAAAAAAAA
// t.me/joinchat/AAAAAAAAAAAAAAAA
// https://t.me/joinchat/AAAAAAAAAAAAAAAA
// tg:join?invite=AAAAAAAAAAAAAAAA
// tg://join?invite=AAAAAAAAAAAAAAAA
//
// t.me/+AAAAAAAAAAAAAAAA
// https://t.me/+AAAAAAAAAAAAAAAA
// t.me/joinchat/AAAAAAAAAAAAAAAA
// https://t.me/joinchat/AAAAAAAAAAAAAAAA
// tg:join?invite=AAAAAAAAAAAAAAAA
// tg://join?invite=AAAAAAAAAAAAAAAA
func (s *Sender) JoinLink(ctx context.Context, link string) (tg.UpdatesClass, error) {
hash := link
if deeplink.IsDeeplinkLike(link) {
Expand Down
4 changes: 2 additions & 2 deletions telegram/message/markup/hide.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ func Hide() tg.ReplyMarkupClass {
// SelectiveHide creates markup to hide markup.
// Use this builder if you want to remove the keyboard for specific users only.
// Targets:
// 1) users that are @mentioned in the text of the Message object;
// 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
// 1. users that are @mentioned in the text of the Message object;
// 2. if the bot's message is a reply (has reply_to_message_id), sender of the original message.
//
// Example: A user votes in a poll, bot returns confirmation message in reply to the vote
// and removes the keyboard for that user, while still showing the keyboard with poll
Expand Down
4 changes: 2 additions & 2 deletions telegram/message/markup/keyboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ func (b *ReplyKeyboardMarkupBuilder) SingleUse() *ReplyKeyboardMarkupBuilder {

// Selective sets flag to show the keyboard to specific users only.
// Targets:
// 1) users that are @mentioned in the text of the Message object;
// 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message.
// 1. users that are @mentioned in the text of the Message object;
// 2. if the bot's message is a reply (has reply_to_message_id), sender of the original message.
//
// Example: A user requests to change the bot‘s language, bot replies to the request
// with a keyboard to select the new language.
Expand Down
12 changes: 4 additions & 8 deletions telegram/message/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ func (s *Sender) Self() *RequestBuilder {
// +13115552368
// +1 (311) 555-0123
// +1 311 555-6162
//
func (s *Sender) Resolve(from string, decorators ...peer.PromiseDecorator) *RequestBuilder {
return s.builder(peer.Resolve(s.resolver, from), decorators)
}
Expand All @@ -86,9 +85,9 @@ func (s *Sender) Resolve(from string, decorators ...peer.PromiseDecorator) *Requ
// It resolves peer of message using given Resolver.
// Input example:
//
// +13115552368
// +1 (311) 555-0123
// +1 311 555-6162
// +13115552368
// +1 (311) 555-0123
// +1 311 555-6162
//
// NB: ResolvePhone just deletes any non-digit symbols from phone argument.
// For now, Telegram sends contact number as string like "13115552368".
Expand All @@ -103,7 +102,6 @@ func (s *Sender) ResolvePhone(phone string, decorators ...peer.PromiseDecorator)
//
// @telegram
// telegram
//
func (s *Sender) ResolveDomain(domain string, decorators ...peer.PromiseDecorator) *RequestBuilder {
return s.builder(peer.ResolveDomain(s.resolver, domain), decorators)
}
Expand All @@ -117,7 +115,6 @@ func (s *Sender) ResolveDomain(domain string, decorators ...peer.PromiseDecorato
// https://t.me/telegram
// tg:resolve?domain=telegram
// tg://resolve?domain=telegram
//
func (s *Sender) ResolveDeeplink(link string, decorators ...peer.PromiseDecorator) *RequestBuilder {
return s.builder(peer.ResolveDeeplink(s.resolver, link), decorators)
}
Expand Down Expand Up @@ -171,8 +168,7 @@ func (s *Sender) Answer(
// Reply uses given message update to create message for same chat and create a reply.
// Shorthand for
//
// sender.Answer(uctx, upd).ReplyMsg(upd.GetMessage())
//
// sender.Answer(uctx, upd).ReplyMsg(upd.GetMessage())
func (s *Sender) Reply(uctx tg.Entities, upd AnswerableMessageUpdate, decorators ...peer.PromiseDecorator) *Builder {
return s.Answer(uctx, upd, decorators...).ReplyMsg(upd.GetMessage())
}
3 changes: 0 additions & 3 deletions telegram/message/peer/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ type Promise func(ctx context.Context) (tg.InputPeerClass, error)
// +1 (311) 555-0123
// +1 311 555-6162
// 13115556162
//
func Resolve(r Resolver, from string) Promise {
from = strings.TrimSpace(from)

Expand Down Expand Up @@ -88,7 +87,6 @@ func ResolvePhone(r Resolver, phone string) Promise {
//
// @telegram
// telegram
//
func ResolveDomain(r Resolver, domain string) Promise {
return func(ctx context.Context) (tg.InputPeerClass, error) {
domain = strings.TrimPrefix(domain, "@")
Expand All @@ -114,7 +112,6 @@ func validateDomain(domain string) error {
// https://t.me/telegram
// tg:resolve?domain=telegram
// tg://resolve?domain=telegram
//
func ResolveDeeplink(r Resolver, u string) Promise {
return func(ctx context.Context) (tg.InputPeerClass, error) {
link, err := deeplink.Expect(u, deeplink.Resolve)
Expand Down
4 changes: 4 additions & 0 deletions telegram/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ type Options struct {
RetryInterval time.Duration
// MaxRetries is limit of send retries.
MaxRetries int
// ExchangeTimeout is timeout of every key exchange request.
ExchangeTimeout time.Duration
// DialTimeout is timeout of creating connection.
DialTimeout time.Duration

// CompressThreshold is a threshold in bytes to determine that message
// is large enough to be compressed using GZIP.
Expand Down
Loading

0 comments on commit 97c64c0

Please sign in to comment.