package downloader

import (
	
	

	
)

// SchedulerOptions configures Scheduler.
type SchedulerOptions struct {
	// Min is the minimum window (in-flight part requests). Defaults to 1.
	Min int
	// Start is the initial window. Defaults to 4.
	Start int
	// Max is the maximum window. Defaults to 16.
	Max int
}

func ( *SchedulerOptions) () {
	if .Min <= 0 {
		.Min = 1
	}
	if .Max <= 0 {
		.Max = 16
	}
	if .Max < .Min {
		.Max = .Min
	}
	if .Start <= 0 {
		.Start = 4
	}
	if .Start < .Min {
		.Start = .Min
	}
	if .Start > .Max {
		.Start = .Max
	}
}

// SchedulerSnapshot is a snapshot of Scheduler state, e.g. for metrics.
type SchedulerSnapshot struct {
	// Window is the current limit of in-flight part requests.
	Window int
	// InFlight is the number of in-flight part requests.
	InFlight int
	// Waiting is the number of workers waiting for a slot.
	Waiting int
	// Decreases is the total number of window decreases (flood waits and
	// timeouts).
	Decreases int64
}

// Scheduler is an adaptive limit of in-flight part requests shared by
// downloads, like the per-DC download window of Telegram Desktop.
//
// The window grows by one after each window of successful requests and is
// halved on flood wait or timeout, at most once per window of requests in
// flight: concurrent requests failing together halve it once.
//
// Flood waits and timeouts that the CDN download path retries internally,
// e.g. when refreshing an expired redirect via master DC, decrease the window
// too, while the request keeps its slot. Repeated timeouts of one request
// decrease it at most once.
//
// Use one Scheduler per DC (or per connection pool), and pass it to downloads
// via Downloader.WithScheduler or Builder.WithScheduler; Builder.WithThreads
// still limits workers of one download, so set it high enough to fill the
// window.
type Scheduler struct {
	mux       sync.Mutex
	opts      SchedulerOptions
	window    int
	inFlight  int
	waiting   int
	successes int
	decreases int64
	// epoch is incremented on each window decrease: a request acquired
	// before the last decrease does not decrease the window again, so a
	// burst of failures of concurrent requests halves it once.
	epoch uint64
	// wake is closed and replaced when a slot may become available.
	wake chan struct{}
}

// NewScheduler creates new Scheduler.
func ( SchedulerOptions) *Scheduler {
	.setDefaults()
	return &Scheduler{
		opts:   ,
		window: .Start,
		wake:   make(chan struct{}),
	}
}

// Snapshot returns current state.
func ( *Scheduler) () SchedulerSnapshot {
	.mux.Lock()
	defer .mux.Unlock()
	return SchedulerSnapshot{
		Window:    .window,
		InFlight:  .inFlight,
		Waiting:   .waiting,
		Decreases: .decreases,
	}
}

func ( *Scheduler) () {
	close(.wake)
	.wake = make(chan struct{})
}

// acquire takes a slot, returning the epoch to pass to release.
func ( *Scheduler) ( context.Context) (uint64, error) {
	.mux.Lock()
	for .inFlight >= .window {
		 := .wake
		.waiting++
		.mux.Unlock()
		select {
		case <-:
		case <-.Done():
			.mux.Lock()
			.waiting--
			.mux.Unlock()
			return 0, .Err()
		}
		.mux.Lock()
		.waiting--
	}
	.inFlight++
	 := .epoch
	.mux.Unlock()
	return , nil
}

// release releases slot taken by acquire, adapting window by request result.
func ( *Scheduler) ( context.Context,  uint64,  error) {
	.mux.Lock()
	defer .mux.Unlock()
	.inFlight--

	switch {
	case  == nil:
		.successes++
		if .successes >= .window && .window < .opts.Max {
			.window++
			.successes = 0
		}
	case isSchedulerBackoff(, ):
		.decrease()
	}
	.notify()
}

// backoff decreases window on flood wait or timeout of a request that is
// retried internally while holding its slot, e.g. by the CDN download path.
//
// Returns the epoch to use for further reports and release of this request.
// A flood wait is an explicit signal of the server, so each one of a request
// retried for a long time can decrease the window again. A timeout is not:
// repeated timeouts of one stuck request decrease the window at most once.
func ( *Scheduler) ( context.Context,  uint64,  error) uint64 {
	if !isSchedulerBackoff(, ) {
		return 
	}
	.mux.Lock()
	defer .mux.Unlock()
	.decrease()
	if ,  := tgerr.AsFloodWait(); ! {
		return 
	}
	return .epoch
}

// decrease halves window, unless it was already decreased after the request
// with given epoch was sent. Must be called with mux held.
func ( *Scheduler) ( uint64) {
	.successes = 0
	if  != .epoch {
		// Window was already decreased after this request was sent.
		return
	}
	.epoch++
	.decreases++
	.window /= 2
	if .window < .opts.Min {
		.window = .opts.Min
	}
}

// backoffReporter reports flood waits and timeouts retried inside a request
// to Scheduler, see withBackoffReporter.
type backoffReporter struct {
	mux   sync.Mutex
	sch   *Scheduler
	epoch uint64
}

func ( *backoffReporter) ( context.Context,  error) {
	if isSchedulerBackoff(, ) {
		observerFrom().backoff(, )
	}
	.mux.Lock()
	defer .mux.Unlock()
	.epoch = .sch.backoff(, .epoch, )
}

func ( *backoffReporter) ( context.Context,  error) {
	.mux.Lock()
	 := .epoch
	.mux.Unlock()
	.sch.release(, , )
}

type backoffReporterKey struct{}

func ( context.Context,  *backoffReporter) context.Context {
	return context.WithValue(, backoffReporterKey{}, )
}

// reportBackoff reports flood wait or timeout that is retried internally to
// Scheduler of the request, if any.
func ( context.Context,  error) {
	if ,  := .Value(backoffReporterKey{}).(*backoffReporter);  {
		.report(, )
	}
}

func ( context.Context,  error) bool {
	if ,  := tgerr.AsFloodWait();  {
		return true
	}
	return isRetryableTimeout(, )
}

// WithScheduler sets Scheduler shared by downloads of this Downloader.
func ( *Downloader) ( *Scheduler) *Downloader {
	.scheduler = 
	return 
}

// WithScheduler sets Scheduler for this download, overriding the one set via
// Downloader.WithScheduler.
func ( *Builder) ( *Scheduler) *Builder {
	.scheduler = 
	return 
}