package telegram

import (
	
	
	
	

	
	
	
	

	

	
	
	
	
	
	
)

// API returns *tg.Client for calling raw MTProto methods.
func ( *Client) () *tg.Client {
	return .tg
}

// Invoke invokes raw MTProto RPC method. It sends input and decodes result
// into output.
func ( *Client) ( context.Context,  bin.Encoder,  bin.Decoder) error {
	if .tracer != nil {
		 := "Invoke"
		var  []attribute.KeyValue
		if ,  := .(interface{ () uint32 });  {
			 := .()
			 = append(,
				attribute.Int64("tg.method.id_int", int64()),
				attribute.String("tg.method.id", fmt.Sprintf("%x", )),
			)
			 := .opts.Types.Get()
			if  == "" {
				 = fmt.Sprintf("0x%x", )
			} else {
				 = append(, attribute.String("tg.method.name", ))
			}
			 = fmt.Sprintf("Invoke: %s", )
		}
		,  := .tracer.Start(, ,
			trace.WithAttributes(...),
			trace.WithSpanKind(trace.SpanKindClient),
		)
		 = 
		defer .End()
	}

	return .invoker.Invoke(, , )
}

// measuredInvoker records gotd.client.invoke.duration of requests through
// the client invoker, with middlewares: Client.Invoke and Client.API.
type measuredInvoker struct {
	client *Client
	next   tg.Invoker
}

func ( measuredInvoker) ( context.Context,  bin.Encoder,  bin.Decoder) error {
	 := .client
	 := .now()
	 := .next.Invoke(, , )
	 := .meters()
	.invokeDuration.Record(, .now().Sub().Seconds(), .invokeResult(, )...)
	return 
}

// invokeDirect directly invokes RPC method, automatically handling datacenter redirects.
func ( *Client) ( context.Context,  bin.Encoder,  bin.Decoder) error {
	 := .invokeConn(, , )
	if  != nil {
		// Handling datacenter migration request.
		if ,  := tgerr.As();  && strings.HasSuffix(.Type, "_MIGRATE") {
			 := .Argument
			 := .log.With(
				log.String("error_type", .Type),
				log.Int("target_dc", ),
			)
			// If migration error is FILE_MIGRATE or STATS_MIGRATE, then the method
			// called by authorized client, so we should try to transfer auth to new DC
			// and create new connection.
			if .IsOneOf("FILE_MIGRATE", "STATS_MIGRATE") {
				.Debug(, "Invoking on target DC")
				.meters().fileMigrations.Add(, 1, dcAttrs(,
					attribute.String("source", "primary"),
				))
				return .invokeSub(, , , )
			}

			// Otherwise we should change primary DC.
			.Info(, "Migrating to target DC")
			 = .invokeMigrate(, , , )
			.observeAuth(, , )
			return 
		}

		.observeAuth(, , )
		return 
	}

	// Only primary connection results reveal primary session authorization:
	// sub-connection (FILE_MIGRATE) results are not observed.
	.observeAuth(, , nil)
	return nil
}

// invokeConn directly invokes RPC call on primary connection without any
// additional handling.
//
// If the connection dies before the request is processed by the server,
// invokeConn waits until the reconnection loop replaces the connection and
// retries the request on it, see https://github.com/gotd/td/issues/1030.
func ( *Client) ( context.Context,  bin.Encoder,  bin.Decoder) error {
	var  time.Duration
	if .requestTimeout != nil {
		 = .requestTimeout()
	}
	 := 0
	 := false
	for {
		.connMux.Lock()
		 := .conn
		 := .connChanged
		.connMux.Unlock()

		,  := , context.CancelCauseFunc(func(error) {})
		if  > 0 {
			,  = .withResponseDeadline(, , )
		}
		 := .Invoke(, , )
		 :=  != nil && .Err() == nil && errors.Is(context.Cause(), errNoResponse)
		(nil)
		if  {
			// Response deadline passed, but caller still waits: connection is
			// suspected to be dead.
			 := methodName()
			if  {
				.meters().requestTimeout.Add(, 1, metric.WithAttributes(
					attribute.String("result", "failed"),
					attribute.String("method", ),
				))
				.log.Warn(, "No response in time after resend",
					log.Duration("timeout", ),
					log.String("method", ),
				)
				return errors.Errorf("no response in %s: %w", , context.DeadlineExceeded)
			}
			 = true
			.meters().requestTimeout.Add(, 1, metric.WithAttributes(
				attribute.String("result", "resent"),
				attribute.String("method", ),
			))
			.log.Warn(, "No response in time, reconnecting to resend request",
				log.Duration("timeout", ),
				log.String("method", ),
			)
			if  := .restartSuspect(, );  != nil {
				return errors.Wrap(, "reconnect")
			}
			continue
		}
		if  == nil || !errRetryableOnNewConn() {
			return 
		}

		var  <-chan struct{}
		if .ctx != nil {
			 = .ctx.Done()
		}
		++
		.log.Debug(, "Primary connection is dead, waiting for new connection to retry",
			log.Error(),
			log.Int("attempt", ),
		)
		select {
		case <-.Done():
			return errors.Wrap(.Err(), "wait for reconnect")
		case <-:
			// Client is closed, no reconnection will happen.
			return errors.Wrap(.ctx.Err(), "client closed")
		case <-:
			.log.Debug(, "Primary connection replaced, retrying request", log.Int("attempt", ))
		}
	}
}

// methodName returns TL name of the innermost request, e.g. "messages.getHistory".
func ( bin.Encoder) string {
	if ,  := unwrapQuery().(interface{ () string });  {
		return .()
	}
	return "unknown"
}

// errRetryableOnNewConn reports whether request failed because connection
// died before the request was processed by the server (request was not sent,
// or sent but not acknowledged), so it is safe to retry the request on a new
// connection.
func ( error) bool {
	return errors.Is(, pool.ErrConnDead) || errors.Is(, rpc.ErrEngineClosed)
}

// restartSuspect restarts primary connection, unless it was already replaced
// (connChanged is closed), and waits until new connection is ready.
func ( *Client) ( context.Context,  <-chan struct{}) error {
	// Another request may be restarting a connection that never gets ready:
	// do not wait for it past own context.
	select {
	case .restartSem <- struct{}{}:
	case <-.Done():
		return .Err()
	}
	defer func() { <-.restartSem }()

	select {
	case <-:
		// Already reconnected, e.g. by another timed out request.
		return nil
	default:
	}
	return .ensureRestart(, restartTimeout)
}

// errNoResponse is the cause of request context cancellation when response
// deadline passes.
var errNoResponse = errors.New("no response in time")

// withResponseDeadline returns context that is canceled with errNoResponse
// once timeout passes after conn became ready to send requests.
//
// Time spent waiting for the connection (dial, key exchange, initConnection)
// does not count: a slow handshake must not be taken for a dead connection,
// or each request would restart it before it gets ready.
func ( *Client) (
	 context.Context,  clientConn,  time.Duration,
) (context.Context, context.CancelCauseFunc) {
	,  := context.WithCancelCause()

	var  <-chan struct{}
	if ,  := .(interface{ () <-chan struct{} });  {
		 = .()
	}
	 := .clock
	if  == nil {
		 = clock.System
	}
	go func() {
		if  != nil {
			select {
			case <-:
			case <-.Done():
				return
			}
		}
		 := .Timer()
		defer clock.StopTimer()
		select {
		case <-.C():
			(errNoResponse)
		case <-.Done():
		}
	}()

	return , 
}