package telegram

import (
	
	

	
	
	

	

	
	
	
	
	
)

// runUntilRestart runs the primary connection until restart. It stores the
// DC of the connection in dc, so that its state is reported for the right DC
// even after migration changed the session.
func ( *Client) ( context.Context,  *int) error {
	.connMux.Lock()
	 := .conn
	* = .connDC
	.connMux.Unlock()

	.notifyConnectionState(ConnectionStateConnecting, *)

	 := tdsync.NewCancellableGroup()
	.Go(.Run)

	// Report readiness of this primary connection only.
	//
	// We must not emit this from the shared OnSession handler, because it is
	// also used by pool/sub connections (including same-DC ones), which would
	// produce spurious ready events. Waiting on the connection's own Ready
	// channel scopes the event strictly to the primary connection.
	//
	// Always watched: readiness is also logged and counted in metrics.
	 := *
	if ,  := .(interface{ () <-chan struct{} });  {
		.Go(func( context.Context) error {
			if !waitReady(, .()) {
				return .Err()
			}
			.notifyConnectionState(ConnectionStateReady, )
			return nil
		})
	}

	// If we don't need updates, so there is no reason to subscribe for it.
	if !.noUpdatesMode {
		.Go(func( context.Context) error {
			// Call method which requires authorization, to subscribe for updates.
			// See https://core.telegram.org/api/updates#subscribing-to-updates.
			,  := .Self()
			if  != nil {
				// Ignore unauthorized errors.
				if !auth.IsUnauthorized() {
					.log.Warn(, "Got error on self", log.Error())
				}
				if IsAuthLost() {
					// OnAuthLost runs on its own goroutine: wait for it to
					// know whether it stops Run.
					if  := .waitAuthLost();  != nil {
						return 
					}
				}
				if .auth.stopped.Load() {
					// OnAuthLost already reported this error and stops Run.
					return nil
				}
				if  := .onSelfError;  != nil {
					// Help with https://github.com/gotd/td/issues/1458.
					if  := (, );  != nil {
						return errors.Wrap(, "onSelfError")
					}
				}
				return nil
			}

			.markAuthorized()
			if  := .onSelfSuccess;  != nil {
				()
			}

			.log.Info(, "Got self", log.String("username", .Username))
			return nil
		})
	}

	.Go(func( context.Context) error {
		select {
		case <-.Done():
			return .Err()
		case <-.restart:
			.log.Debug(, "Restart triggered")
			// Should call cancel() to cancel group.
			.Cancel()

			return nil
		}
	})

	return .Wait()
}

// waitReady blocks until ready is closed or ctx is done and reports whether
// ready was closed.
//
// Readiness wins when both happen: a request may complete on the fresh
// connection and cancel ctx before this goroutine is scheduled, and a plain
// select would then drop the ready event at random.
func ( context.Context,  <-chan struct{}) bool {
	select {
	case <-:
		return true
	case <-.Done():
		select {
		case <-:
			return true
		default:
			return false
		}
	}
}

func ( *Client) ( error) bool {
	// See https://github.com/gotd/td/issues/1458.
	if errors.Is(, exchange.ErrKeyFingerprintNotFound) {
		return true
	}
	if tgerr.Is(, "AUTH_KEY_UNREGISTERED", "SESSION_EXPIRED", "AUTH_KEY_DUPLICATED") {
		return true
	}
	if tgerr.Is(, "AUTH_KEY_PERM_EMPTY") {
		// PFS: the temporary key binding was lost, a reconnect re-binds.
		return false
	}
	if auth.IsUnauthorized() {
		return true
	}
	return false
}

func ( *Client) ( context.Context) error {
	// Note that we currently have no timeout on connection, so this is
	// potentially eternal.
	 := tdsync.SyncBackoff(backoff.WithContext(.newConnBackoff(), ))
	.connBackoff.Store(&)

	// DC of the last run primary connection.
	var  int
	return backoff.RetryNotify(func() error {
		if  := .runUntilRestart(, &);  != nil {
			if ,  := asConfigError();  {
				// Same initConnection fails again on every reconnect.
				.log.Error(, "Server rejected connection setup, check app ID and device config, "+
					"will not reconnect", log.Error())
				// RetryNotify does not call notify for permanent errors.
				.notifyConnectionState(ConnectionStateDisconnected, )
				return backoff.Permanent()
			}
			if .isPermanentError() {
				.log.Warn(, "Permanent connection error, will not reconnect", log.Error())
				.notifyConnectionState(ConnectionStateDisconnected, )
				return backoff.Permanent()
			}
			return 
		}

		return nil
	}, , func( error,  time.Duration) {
		.log.Info(context.Background(), "Restarting connection",
			log.Error(),
			log.Duration("backoff", ),
			log.Int("dc_id", ),
		)
		.meters().reconnects.Add(context.Background(), 1, dcAttrs())
		.notifyConnectionState(ConnectionStateDisconnected, )

		.connMux.Lock()
		// Some PFS errors require dropping persisted keys before recreating conn.
		.handlePrimaryConnDead()
		.replaceConn(.createPrimaryConn(nil))
		.connMux.Unlock()
		.log.Debug(context.Background(), "Primary connection replaced after restart")
	})
}

func ( *Client) () {
	.log.Debug(context.Background(), "Ready")
	.ready.Signal()

	if  := .connBackoff.Load();  != nil {
		// Reconnect faster next time.
		(*).Reset()
	}
}

func ( *Client) () {
	.ready.Reset()
}

// Run starts client session and blocks until connection close.
// The f callback is called on successful session initialization and Run
// will return on f() result.
//
// Context of callback will be canceled if fatal error is detected.
// The ctx is used for background operations like updates handling or pools.
//
// Run is single-use: create a new Client to run again. See Start, Close and
// Wait for the classic approach without explicit callback; Run and Start are
// mutually exclusive on one Client (ErrAlreadyStarted). Done and Wait report
// the result of Run once it returned.
func ( *Client) ( context.Context,  func( context.Context) error) ( error) {
	if !.life.mode.CompareAndSwap(int32(modeIdle), int32(modeRun)) {
		switch lifecycleMode(.life.mode.Load()) {
		case modeStart:
			return errDrivenByStart
		case modeClosed:
			return ErrClientClosed
		}
		// Run again, fails as the client is closed.
		return .run(, )
	}
	// First Run: report its result via Done and Wait.
	defer func() { .finishStart(, false) }()
	return .run(, )
}

// run implements Run, see Run and Start.
func ( *Client) ( context.Context,  func( context.Context) error) ( error) {
	if .ctx != nil {
		select {
		case <-.ctx.Done():
			return errors.Wrap(.ctx.Err(), "client already closed")
		default:
		}
	}

	// Setting up client context for background operations like updates
	// handling or pool creation.
	.ctx, .cancel = context.WithCancel()

	.log.Info(, "Starting")
	defer .log.Info(context.Background(), "Closed")
	defer .registerPoolsGauge()()
	defer .downloadSchedulers.unregister()
	// Wait for a running OnAuthLost call after c.ctx (passed to it) is
	// canceled and pools are closed below, so that it doesn't outlive Run.
	// If it asked to stop Run, report that even if f returned first.
	defer func() {
		_ = .waitAuthLost(context.Background())
		select {
		case  := <-.authLost:
			var  *AuthLostError
			switch {
			case  == nil:
				 = 
			case !errors.As(, &):
				 = multierr.Append(, )
			}
		default:
		}
	}()
	defer func() {
		 := .subConns.drain()
		 = append(, .filePools.drain()...)
		.fileInvokersMux.Lock()
		.fileInvokers = map[int]tg.Invoker{}
		.fileInvokersMux.Unlock()

		 := .cdnPools.drain()

		// Close outside locks to avoid lock inversion with pool callbacks.
		for ,  := range  {
			if  := .Close(); !errors.Is(, context.Canceled) {
				multierr.AppendInto(&, )
			}
		}
		for ,  := range  {
			if  := .Close(); !errors.Is(, context.Canceled) {
				multierr.AppendInto(&, )
			}
		}
	}()
	// Cancel client before deferred cleanup snapshot to block concurrent pool
	// creations while we are draining cached connections.
	defer .cancel()

	.resetReady()
	if  := .restoreConnection();  != nil {
		return 
	}

	 := tdsync.NewCancellableGroup()
	.Go(.reconnectUntilClosed)
	.Go(func( context.Context) error {
		select {
		case <-.Done():
			return .Err()
		case  := <-.authLost:
			if .Err() != nil {
				// Group is already stopping, so err may be lost by g.Wait:
				// put it back for the deferred check above.
				select {
				case .authLost <- :
				default:
				}
				return .Err()
			}
			return 
		}
	})
	.Go(func( context.Context) error {
		select {
		case <-.Done():
			.cancel()
			return .Err()
		case <-.ctx.Done():
			return .ctx.Err()
		}
	})
	.Go(func( context.Context) error {
		select {
		case <-.Done():
			return .Err()
		case <-.ready.Ready():
			if  := ();  != nil {
				return errors.Wrap(, "callback")
			}
			// Should call cancel() to cancel ctx.
			// This will terminate c.conn.Run().
			.log.Debug(, "Callback returned, stopping")
			.Cancel()
			return nil
		}
	})
	if  := .Wait(); !errors.Is(, context.Canceled) {
		return 
	}

	return nil
}