package telegram

import (
	
	

	
	
	

	

	
	
	
)

// subConnCall is an in-flight creation of a pool to some DC.
type subConnCall struct {
	done chan struct{}
	conn CloseInvoker
	err  error
}

// dcPoolCache caches data pools per DC.
type dcPoolCache struct {
	mux     sync.Mutex
	conns   map[int]CloseInvoker
	pending map[int]*subConnCall
	// max is the pool size.
	max int64
	// kind is the pool kind for metrics and logs.
	kind string
}

func ( int64,  string) *dcPoolCache {
	return &dcPoolCache{
		conns:   map[int]CloseInvoker{},
		pending: map[int]*subConnCall{},
		max:     ,
		kind:    ,
	}
}

// len returns the number of cached pools.
func ( *dcPoolCache) () int {
	.mux.Lock()
	defer .mux.Unlock()
	return len(.conns)
}

// drain removes and returns all cached pools.
func ( *dcPoolCache) () []CloseInvoker {
	.mux.Lock()
	defer .mux.Unlock()
	 := make([]CloseInvoker, 0, len(.conns))
	for ,  := range .conns {
		 = append(, )
	}
	.conns = map[int]CloseInvoker{}
	return 
}

// evict removes conn from cache if it is still the cached pool of dc and
// closes it.
func ( *dcPoolCache) ( int,  CloseInvoker) {
	.mux.Lock()
	,  := .conns[]
	if ! ||  !=  {
		.mux.Unlock()
		return
	}
	delete(.conns, )
	.mux.Unlock()
	_ = .Close()
}

// errClientNotRunning is returned when DC pool is requested before Run.
var errClientNotRunning = errors.New("client is not running")

func ( *Client) ( context.Context,  int,  bin.Encoder,  bin.Decoder) error {
	return .invokeCachedDC(, .subConns, , , )
}

// invokeCachedDC invokes request on cached data pool of dc.
//
// If the request fails as unauthorized, the pool may be cached with a failed
// authorization transfer, e.g. created before sign in completed: it is
// dropped and the request is retried once on a new pool, which transfers
// authorization again.
func ( *Client) (
	 context.Context,
	 *dcPoolCache,
	 int,
	 bin.Encoder,
	 bin.Decoder,
) error {
	for  := 0; ; ++ {
		,  := .cachedDC(, , )
		if  != nil {
			return errors.Wrapf(, "create connection to DC %d", )
		}
		 = .Invoke(, , )
		if  == 0 && auth.IsUnauthorized() {
			.log.Warn(, "Unauthorized on cached pool, recreating it",
				log.Int("dc_id", ),
				log.String("kind", .kind),
				log.Error(),
			)
			.meters().poolEvicted.Add(, 1, dcAttrs(,
				attribute.String("kind", .kind),
				attribute.String("reason", "unauthorized"),
			))
			.evict(, )
			// The key of this DC is not authorized (any more): the next pool
			// must transfer the authorization.
			.setDCAuthorized(, , false)
			continue
		}
		return 
	}
}

// cachedDC returns cached data pool to given DC or creates new one.
//
// Creation (dial, key exchange and authorization transfer) is done once per DC
// without holding cache lock, so other DCs and calls to already created pools
// are not blocked. Creation is bounded by migration timeout and is not
// canceled when the caller that started it gives up. Failed creation is not
// cached.
func ( *Client) ( context.Context,  *dcPoolCache,  int) (CloseInvoker, error) {
	if .ctx == nil {
		// Pools are bound to client context, which is set by Run.
		return nil, errClientNotRunning
	}
	.mux.Lock()
	if ,  := .conns[];  {
		.mux.Unlock()
		return , nil
	}
	,  := .pending[]
	if ! {
		 = &subConnCall{done: make(chan struct{})}
		.pending[] = 
		go .createCachedDC(, , , )
	}
	.mux.Unlock()

	select {
	case <-.done:
		return .conn, .err
	case <-.Done():
		return nil, .Err()
	}
}

func ( *Client) ( context.Context,  *dcPoolCache,  int,  *subConnCall) {
	// Keep caller values (tracing, logging), but not its cancellation:
	// creation is shared by all callers waiting for this DC.
	 := .ctx
	,  := context.WithCancel(context.WithoutCancel())
	defer ()
	 := context.AfterFunc(, )
	defer ()
	if .migrationTimeout > 0 {
		var  context.CancelFunc
		,  = context.WithTimeout(, .migrationTimeout)
		defer ()
	}

	 := .now()
	,  := .dc(, , .max, .primaryDC(), manager.ConnModeData)
	if  != nil && .Err() != nil {
		 = errors.Wrap(.Err(), "client closed")
	}

	.mux.Lock()
	delete(.pending, )
	if  == nil {
		if .Err() != nil {
			// Client is closing (or closed) and has already drained the cache.
			 = errors.Wrap(.Err(), "client closed")
		} else {
			.conns[] = 
		}
	}
	.conn, .err = , 
	if  != nil {
		.conn = nil
	}
	.mux.Unlock()
	// Waiters are released only after the result is recorded and logged, so
	// they observe it, and nothing of this call outlives them.
	defer close(.done)

	// Creation is detached from the caller's context: only client shutdown
	// cancels it, which is not a failure of the DC.
	 :=  != nil && .Err() != nil
	 := "ok"
	switch {
	case :
		 = "canceled"
	case  != nil:
		 = "error"
	}
	 := .now().Sub()
	 := .meters()
	.poolCreated.Add(, 1, dcAttrs(,
		attribute.String("kind", .kind),
		attribute.String("result", ),
	))
	.poolDuration.Record(, .Seconds(), metric.WithAttributes(
		attribute.String("kind", .kind),
		attribute.String("result", ),
	))

	if  != nil {
		if  != nil {
			_ = .Close()
		}
		 := .log.Warn
		if  {
			 = .log.Debug
		}
		(, "Pool creation failed",
			log.Int("dc_id", ),
			log.String("kind", .kind),
			log.Int64("max", .max),
			log.Duration("duration", ),
			log.Error(),
		)
		return
	}
	.log.Debug(, "Pool created",
		log.Int("dc_id", ),
		log.String("kind", .kind),
		log.Int64("max", .max),
		log.Duration("duration", ),
	)
}