downloader

package
v0.166.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 28 Imported by: 39

Documentation

Overview

Package downloader contains downloading files helpers.

Index

Constants

View Source
const (
	RetryOperationGetFile         = "cdn.get_file"
	RetryOperationGetFileHashes   = "cdn.get_file_hashes"
	RetryOperationReupload        = "cdn.reupload"
	RetryOperationRefreshRedirect = "cdn.refresh_redirect"
	RetryOperationCreateClient    = "cdn.create_client"
	RetryOperationReaderChunk     = "reader.chunk"
	RetryOperationReaderHashes    = "reader.hashes"
	// RetryOperationFileReference is a refresh of expired file reference
	// (see Builder.WithRefresh).
	RetryOperationFileReference = "master.file_reference"
)

Variables

View Source
var ErrFileNotFound = errors.New("file not found")

ErrFileNotFound means that a file reference can't be refreshed because the object that contains the file (message, story, photo) or the file itself is not found anymore.

RefreshFunc should return an error that wraps it in this case, see package fileref.

View Source
var ErrHashMismatch = errors.New("file hash mismatch")

ErrHashMismatch means that download hash verification was failed.

Functions

func IsFileReferenceError

func IsFileReferenceError(err error) bool

IsFileReferenceError reports whether err means that the file reference of the location is expired or invalid, e.g. FILE_REFERENCE_EXPIRED, FILE_REFERENCE_INVALID or FILE_REFERENCE_<n>_EXPIRED.

Types

type Builder added in v0.24.0

type Builder struct {
	// contains filtered or unexported fields
}

Builder is a download builder.

func (*Builder) Parallel added in v0.24.0

func (b *Builder) Parallel(ctx context.Context, output io.WriterAt) (_ tg.StorageFileTypeClass, err error)

Parallel downloads file to given io.WriterAt.

func (*Builder) Stream added in v0.24.0

func (b *Builder) Stream(ctx context.Context, output io.Writer) (_ tg.StorageFileTypeClass, err error)

Stream downloads file to given io.Writer. NB: in this mode download can't be parallel.

func (*Builder) ToPath added in v0.24.0

func (b *Builder) ToPath(ctx context.Context, path string) (_ tg.StorageFileTypeClass, err error)

ToPath downloads file to given path.

If offset is set (see WithOffset), existing file is not truncated, so data before offset is kept. If size is set (see WithSize), the file is truncated to it after a successful download.

func (*Builder) Verify

func (b *Builder) Verify(ctx context.Context, r io.ReaderAt, size int64) (verified int64, err error)

Verify checks local file data (e.g. a partially downloaded .part file) against file hashes from the server (upload.getFileHashes) and returns the length of the longest verified prefix.

The r must contain the first size bytes of the file. A trailing part shorter than a hash window can be verified only if it is the end of the file, otherwise it is not counted.

If the result equals the file size (e.g. Document.Size), the local file is complete: do not resume. Otherwise the result ends at a hash window border, which is 4KB-aligned, and can be passed to WithOffset to resume a download safely together with WithVerify(true). Without verification, WithOffset requires the offset to be divisible by the part size, so round the result down to it:

off -= off % partSize

func (*Builder) WithOffset

func (b *Builder) WithOffset(offset int64) *Builder

WithOffset sets offset to start download from, e.g. to resume a partially downloaded file. Data before offset is not downloaded.

Offset must be divisible by the part size (see Downloader.WithPartSize), unless verification is enabled via WithVerify(true), which only requires 4KB alignment: the hash window containing offset is downloaded whole to verify it, and data before offset is dropped.

Stream writes data from offset to the start of io.Writer, Parallel writes it at the same offsets of io.WriterAt, and ToPath keeps existing file content before offset.

func (*Builder) WithProgress

func (b *Builder) WithProgress(progress ProgressFunc) *Builder

WithProgress sets callback called after each written part.

func (*Builder) WithRefresh

func (b *Builder) WithRefresh(refresh RefreshFunc) *Builder

WithRefresh sets callback to refresh file location on file reference errors (FILE_REFERENCE_*), so download continues from the same offset instead of failing.

Concurrent workers share one refresh, and a request is retried at most three times. Has no effect for web files.

func (*Builder) WithRetryHandler added in v0.142.0

func (b *Builder) WithRetryHandler(handler RetryHandler) *Builder

WithRetryHandler sets callback for transient download errors that are retried internally.

Handler can be called concurrently from download workers.

func (*Builder) WithScheduler

func (b *Builder) WithScheduler(s *Scheduler) *Builder

WithScheduler sets Scheduler for this download, overriding the one set via Downloader.WithScheduler.

func (*Builder) WithSize

func (b *Builder) WithSize(size int64) *Builder

WithSize sets known file size (e.g. Document.Size), so download stops requesting parts at the end of file instead of probing past it, and progress reports the total.

func (*Builder) WithThreads added in v0.24.0

func (b *Builder) WithThreads(threads int) *Builder

WithThreads sets downloading goroutines limit.

func (*Builder) WithVerify added in v0.24.0

func (b *Builder) WithVerify(verify bool) *Builder

WithVerify controls global hash verification behavior.

`true` enables classic verifier reader (preloads hash queue and validates all chunks, both legacy and CDN). `false` disables classic verifier reader.

If not called explicitly: - non-CDN path preserves old behavior (no upfront hash requests); - CDN path enables strict inline CDN verification after redirect.

Use WithVerify(true) to force verifier-queue mode on all paths.

type CDN added in v0.24.0

type CDN interface {
	UploadGetCDNFile(ctx context.Context, request *tg.UploadGetCDNFileRequest) (tg.UploadCDNFileClass, error)
}

CDN represents Telegram RPC client to CDN server.

type CDNProvider added in v0.142.0

type CDNProvider interface {
	CDN(ctx context.Context, dc int, max int64) (CDN, io.Closer, error)
}

CDNProvider creates client bound to requested CDN DC. Returned closer is schema-scoped; for shared client-level pool adapters this can be a no-op closer.

type Client added in v0.24.0

type Client interface {
	UploadGetFile(ctx context.Context, request *tg.UploadGetFileRequest) (tg.UploadFileClass, error)
	UploadGetFileHashes(ctx context.Context, request *tg.UploadGetFileHashesRequest) ([]tg.FileHash, error)

	UploadReuploadCDNFile(ctx context.Context, request *tg.UploadReuploadCDNFileRequest) ([]tg.FileHash, error)
	UploadGetCDNFileHashes(ctx context.Context, request *tg.UploadGetCDNFileHashesRequest) ([]tg.FileHash, error)

	UploadGetWebFile(ctx context.Context, request *tg.UploadGetWebFileRequest) (*tg.UploadWebFile, error)
}

Client represents Telegram RPC client.

func WithCDNProvider

func WithCDNProvider(client Client, provider CDNProvider) Client

WithCDNProvider returns Client that serves CDN redirects through given provider, e.g. telegram.Client.CDNProvider.

Without CDNProvider, downloads through plain clients (like tg.NewClient(pool)) silently fall back to master DC, even with Downloader.WithAllowCDN(true).

type Downloader

type Downloader struct {
	// contains filtered or unexported fields
}

Downloader is Telegram file downloader.

func NewDownloader

func NewDownloader() *Downloader

NewDownloader creates new Downloader.

func (*Downloader) Clone

func (d *Downloader) Clone() *Downloader

Clone returns a copy of the Downloader, sharing its instruments (metrics and logger), so that With* methods of the copy don't change the original.

Use it to configure a shared, instrumented Downloader per download without creating instruments again.

func (*Downloader) Download

func (d *Downloader) Download(rpc Client, location tg.InputFileLocationClass) *Builder

Download creates Builder for plain downloads.

func (*Downloader) Web added in v0.24.0

func (d *Downloader) Web(rpc Client, location tg.InputWebFileLocationClass) *Builder

Web creates Builder for web files downloads.

func (*Downloader) WithAllowCDN added in v0.142.0

func (d *Downloader) WithAllowCDN(allow bool) *Downloader

WithAllowCDN explicitly enables or disables CDN redirect flow.

This flag is explicit: if it is not set, downloader keeps legacy master-DC-only behavior and does not attempt CDN redirect handling. Client integration (`telegram.Client.Downloader`) sets this option from `telegram.Options.AllowCDN`.

func (*Downloader) WithLogger

func (d *Downloader) WithLogger(l log.Logger) *Downloader

WithLogger sets logger for downloader debug logs. No logs by default.

func (*Downloader) WithMeterProvider

func (d *Downloader) WithMeterProvider(mp metric.MeterProvider) *Downloader

WithMeterProvider sets meter provider for downloader metrics. Metrics are not collected by default.

func (*Downloader) WithPartSize

func (d *Downloader) WithPartSize(partSize int) *Downloader

WithPartSize sets chunk size. Must be divisible by 4KB.

See https://core.telegram.org/api/files#downloading-files.

func (*Downloader) WithRetryHandler added in v0.142.0

func (d *Downloader) WithRetryHandler(handler RetryHandler) *Downloader

WithRetryHandler sets callback for transient download errors that are retried internally by downloader.

Handler can be called concurrently from download workers.

func (*Downloader) WithScheduler

func (d *Downloader) WithScheduler(s *Scheduler) *Downloader

WithScheduler sets Scheduler shared by downloads of this Downloader.

type ProgressFunc

type ProgressFunc func(done, total int64)

ProgressFunc is called after each written part with the offset of the end of downloaded data, counting from the start of the file (including the offset set by Builder.WithOffset), and the file size if known (see Builder.WithSize), zero otherwise.

Calls are not concurrent.

type RedirectError

type RedirectError struct {
	Redirect *tg.UploadFileCDNRedirect
}

RedirectError error is returned when Downloader get CDN redirect. See https://core.telegram.org/constructor/upload.fileCdnRedirect.

func (*RedirectError) Error

func (r *RedirectError) Error() string

Error implements error interface.

type RefreshFunc

type RefreshFunc func(ctx context.Context) (tg.InputFileLocationClass, error)

RefreshFunc returns file location with fresh file reference, e.g. by fetching the message, story or profile photo that contains the file again.

See https://core.telegram.org/api/file_reference and package fileref.

type RetryEvent added in v0.142.0

type RetryEvent struct {
	// Operation identifies retry source.
	Operation string
	// Attempt is 1-based counter inside current retry loop.
	Attempt int
	// Err is the error that triggered retry.
	Err error
}

RetryEvent describes retried transient downloader error.

type RetryHandler added in v0.142.0

type RetryHandler func(event RetryEvent)

RetryHandler is called for every downloader error that is retried internally.

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

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.

func NewScheduler

func NewScheduler(opts SchedulerOptions) *Scheduler

NewScheduler creates new Scheduler.

func (*Scheduler) Instrument

func (s *Scheduler) Instrument(m metric.Meter, attrs ...attribute.KeyValue) (metric.Registration, error)

Instrument registers observable instruments of Scheduler state on m: gotd.downloader.scheduler.window, .in_flight and .waiting gauges and the .decreases counter, with given attributes (e.g. DC).

Unregister the returned registration when the Scheduler is not used anymore.

func (*Scheduler) Snapshot

func (s *Scheduler) Snapshot() SchedulerSnapshot

Snapshot returns current state.

type SchedulerOptions

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
}

SchedulerOptions configures Scheduler.

type SchedulerSnapshot

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
}

SchedulerSnapshot is a snapshot of Scheduler state, e.g. for metrics.

Directories

Path Synopsis
Package fileref contains helpers to refresh file references of file locations for downloader.Builder.WithRefresh.
Package fileref contains helpers to refresh file references of file locations for downloader.Builder.WithRefresh.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL