package downloader

Import Path
	github.com/gotd/td/telegram/downloader (on go.dev)

Dependency Relation
	imports 28 packages, and imported by one package


Package-Level Type Names (total 31, in which 13 are exported)
/* sort exporteds by: | */
Builder is a download builder. Parallel downloads file to given io.WriterAt. Stream downloads file to given io.Writer. NB: in this mode download can't be parallel. 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. 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 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. WithProgress sets callback called after each written part. 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. WithRetryHandler sets callback for transient download errors that are retried internally. Handler can be called concurrently from download workers. WithScheduler sets Scheduler for this download, overriding the one set via Downloader.WithScheduler. 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. WithThreads sets downloading goroutines limit. 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. func (*Builder).WithOffset(offset int64) *Builder func (*Builder).WithProgress(progress ProgressFunc) *Builder func (*Builder).WithRefresh(refresh RefreshFunc) *Builder func (*Builder).WithRetryHandler(handler RetryHandler) *Builder func (*Builder).WithScheduler(s *Scheduler) *Builder func (*Builder).WithSize(size int64) *Builder func (*Builder).WithThreads(threads int) *Builder func (*Builder).WithVerify(verify bool) *Builder func (*Downloader).Download(rpc Client, location tg.InputFileLocationClass) *Builder func (*Downloader).Web(rpc Client, location tg.InputWebFileLocationClass) *Builder func github.com/gotd/td/telegram.(*Client).Download(location tg.InputFileLocationClass) *Builder func github.com/gotd/td/telegram.(*Client).DownloadVia(invoker tg.Invoker, location tg.InputFileLocationClass) *Builder func github.com/gotd/td/telegram.(*Client).DownloadWeb(location tg.InputWebFileLocationClass) *Builder func github.com/gotd/td/telegram.(*Client).DownloadWebVia(invoker tg.Invoker, location tg.InputWebFileLocationClass) *Builder
CDN represents Telegram RPC client to CDN server. ( CDN) UploadGetCDNFile(ctx context.Context, request *tg.UploadGetCDNFileRequest) (tg.UploadCDNFileClass, error) *github.com/gotd/td/tg.Client func CDNProvider.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. ( CDNProvider) CDN(ctx context.Context, dc int, max int64) (CDN, io.Closer, error) func github.com/gotd/td/telegram.(*Client).CDNProvider() CDNProvider func WithCDNProvider(client Client, provider CDNProvider) Client
Client represents Telegram RPC client. ( Client) UploadGetCDNFileHashes(ctx context.Context, request *tg.UploadGetCDNFileHashesRequest) ([]tg.FileHash, error) ( Client) UploadGetFile(ctx context.Context, request *tg.UploadGetFileRequest) (tg.UploadFileClass, error) ( Client) UploadGetFileHashes(ctx context.Context, request *tg.UploadGetFileHashesRequest) ([]tg.FileHash, error) ( Client) UploadGetWebFile(ctx context.Context, request *tg.UploadGetWebFileRequest) (*tg.UploadWebFile, error) ( Client) UploadReuploadCDNFile(ctx context.Context, request *tg.UploadReuploadCDNFileRequest) ([]tg.FileHash, error) *github.com/gotd/td/tg.Client func WithCDNProvider(client Client, provider CDNProvider) Client func WithCDNProvider(client Client, provider CDNProvider) Client func (*Downloader).Download(rpc Client, location tg.InputFileLocationClass) *Builder func (*Downloader).Web(rpc Client, location tg.InputWebFileLocationClass) *Builder
Downloader is Telegram file 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. Download creates Builder for plain downloads. Web creates Builder for web files downloads. 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`. WithLogger sets logger for downloader debug logs. No logs by default. WithMeterProvider sets meter provider for downloader metrics. Metrics are not collected by default. WithPartSize sets chunk size. Must be divisible by 4KB. See https://core.telegram.org/api/files#downloading-files. WithRetryHandler sets callback for transient download errors that are retried internally by downloader. Handler can be called concurrently from download workers. WithScheduler sets Scheduler shared by downloads of this Downloader. func NewDownloader() *Downloader func (*Downloader).Clone() *Downloader func (*Downloader).WithAllowCDN(allow bool) *Downloader func (*Downloader).WithLogger(l log.Logger) *Downloader func (*Downloader).WithMeterProvider(mp metric.MeterProvider) *Downloader func (*Downloader).WithPartSize(partSize int) *Downloader func (*Downloader).WithRetryHandler(handler RetryHandler) *Downloader func (*Downloader).WithScheduler(s *Scheduler) *Downloader func github.com/gotd/td/telegram.(*Client).Downloader() *Downloader
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. func (*Builder).WithProgress(progress ProgressFunc) *Builder
RedirectError error is returned when Downloader get CDN redirect. See https://core.telegram.org/constructor/upload.fileCdnRedirect. Redirect *tg.UploadFileCDNRedirect Error implements error interface. *RedirectError : 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. func (*Builder).WithRefresh(refresh RefreshFunc) *Builder
RetryEvent describes retried transient downloader error. Attempt is 1-based counter inside current retry loop. Err is the error that triggered retry. Operation identifies retry source.
RetryHandler is called for every downloader error that is retried internally. func (*Builder).WithRetryHandler(handler RetryHandler) *Builder func (*Downloader).WithRetryHandler(handler RetryHandler) *Downloader
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. 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. Snapshot returns current state. func NewScheduler(opts SchedulerOptions) *Scheduler func github.com/gotd/td/telegram.(*Client).DownloadScheduler(dc int) *Scheduler func (*Builder).WithScheduler(s *Scheduler) *Builder func (*Downloader).WithScheduler(s *Scheduler) *Downloader
SchedulerOptions configures Scheduler. Max is the maximum window. Defaults to 16. Min is the minimum window (in-flight part requests). Defaults to 1. Start is the initial window. Defaults to 4. func NewScheduler(opts SchedulerOptions) *Scheduler
SchedulerSnapshot is a snapshot of Scheduler state, e.g. for metrics. Decreases is the total number of window decreases (flood waits and timeouts). InFlight is the number of in-flight part requests. Waiting is the number of workers waiting for a slot. Window is the current limit of in-flight part requests. func (*Scheduler).Snapshot() SchedulerSnapshot
Package-Level Functions (total 32, in which 4 are exported)
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.
NewDownloader creates new Downloader.
NewScheduler creates new Scheduler.
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).
Package-Level Variables (total 6, in which 2 are exported)
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.
ErrHashMismatch means that download hash verification was failed.
Package-Level Constants (total 37, in which 8 are exported)
const RetryOperationCreateClient = "cdn.create_client"
RetryOperationFileReference is a refresh of expired file reference (see Builder.WithRefresh).
const RetryOperationGetFile = "cdn.get_file"
const RetryOperationGetFileHashes = "cdn.get_file_hashes"
const RetryOperationRefreshRedirect = "cdn.refresh_redirect"
const RetryOperationReupload = "cdn.reupload"