Package-Level Type Names (total 31, in which 13 are exported)
/* sort exporteds by: | */
Builder is a download builder.downloader*Downloaderhashes[]tg.FileHash offset is the offset to start download from (WithOffset). progress is called after each written part (WithProgress). scheduler overrides Downloader scheduler, if set.schemaschema size is the known file size, zero if unknown (WithSize).threadsint verify controls legacy outer verifier (reader + verifier queue).
CDN redirect path has mandatory protocol-level verification in cdn schema,
independent from this flag. 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.(*Builder) prepare() (_ *Builder, closeCDN func() error, err error)(*Builder) prepareCDNPath(m master, provider CDNProvider) *Builder(*Builder) prepareMaster(m master, allowCDN bool) *Builder(*Builder) reader() *reader(*Builder) shouldAllowCDN() bool(*Builder) sink() sink start returns context of a download, reporting its start.(*Builder) validate() error
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
func newBuilder(downloader *Downloader, schema schema) *Builder
func (*Builder).prepare() (_ *Builder, closeCDN func() error, err error)
func (*Builder).prepareCDNPath(m master, provider CDNProvider) *Builder
func (*Builder).prepareMaster(m master, allowCDN bool) *Builder
Downloader is Telegram file downloader. allowCDN is tri-state:
nil -> keep default downloader behavior (CDN disabled),
true -> allow redirect flow,
false-> force legacy master-only flow.loggerlog.Logger meterProvider and logger are set by WithMeterProvider and WithLogger. obs reports metrics and logs, nil if neither is set.partSizeintpool*bin.Pool retryHandler observes transient downloader errors that are retried. scheduler limits in-flight part requests, nil means no limit. 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. nolint:gocognit(*Downloader) stream(ctx context.Context, r *reader, s sink, w io.Writer) (tg.StorageFileTypeClass, error)
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
func github.com/gotd/td/telegram.newClientDownloader(allowCDN bool, mp metric.MeterProvider, lg log.Logger) *Downloader
func github.com/gotd/td/telegram.(*Client).homeDownloader() *Downloader
func newBuilder(downloader *Downloader, schema schema) *Builder
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.
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.decreasesint64 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.inFlightintmuxsync.MutexoptsSchedulerOptionssuccessesintwaitingint wake is closed and replaced when a slot may become available.windowint 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. acquire takes a slot, returning the epoch to pass to release. 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. decrease halves window, unless it was already decreased after the request
with given epoch was sent. Must be called with mux held.(*Scheduler) notify() release releases slot taken by acquire, adapting window by request result.
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.(*SchedulerOptions) setDefaults()
func NewScheduler(opts SchedulerOptions) *Scheduler
func github.com/gotd/td/telegram.newDownloadSchedulers(opts *SchedulerOptions, mp metric.MeterProvider) *telegram.downloadSchedulers
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
locationRef is a file location shared by download workers, which can be
refreshed on file reference errors.locationtg.InputFileLocationClassmuxsync.MutexrefreshRefreshFunc(*locationRef) get() tg.InputFileLocationClass update refreshes location if it is still the failed one: concurrent
workers that failed with the same location do one refresh.
Reports whether this call ran the refresh.
clientschema fetched is set once the server returned hashes, so the location is
valid and VOLUME_LOC_NOT_FOUND at offset means the end of the file. hashes is ordered queue consumed by reader.muxsync.Mutex offset points to next hash window to request from server. skip is the offset to start from: hash windows before it are skipped.(*verifier) next(ctx context.Context) (tg.FileHash, bool, error)(*verifier) pop() (tg.FileHash, bool) start makes verifier skip hashes before offset, i.e. start download from
offset.(*verifier) update(hashes ...tg.FileHash) (tg.FileHash, bool)(*verifier) verify(hash tg.FileHash, data []byte) bool
func newVerifier(client schema, hashes ...tg.FileHash) *verifier
func verifiedReader(sch schema, verifier *verifier) *reader
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).
needPrecise reports whether a part needs the precise flag of upload.getFile:
without it, offset and limit must be divisible by 4 KiB, 1 MiB must be
divisible by limit, and the part must not cross a 1 MiB boundary.
Telegram Desktop and TDLib never set precise, as their parts are aligned;
gotd's default parts are too, so the flag is only sent for unaligned
parts, e.g. a resume from an arbitrary offset.
See https://core.telegram.org/api/files#downloading-files.
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.
observer reports downloader metrics and debug logs.
A nil observer reports nothing: downloads without metrics and logger pay
nothing for it.
durationBuckets are histogram buckets in seconds, the same as of the
telegram client: the SDK defaults are meant for milliseconds.
maxVerifiedWindowCache bounds memory used by split-window verification.
Split windows are needed only when downloader part size does not align with
Telegram CDN hash window size (typically 128KB). In that case we may fetch a
full hash window once, verify it, and reuse verified bytes for neighboring
chunks. A small bounded cache is enough because sequential/parallel readers
usually work on nearby offsets.
meterName is the name of the meter of downloader metrics.
modeCDN means active redirect exists and chunks should be fetched from CDN.
modeMaster means request master first and switch only on redirect.
partAlign is the alignment of offset and limit of upload.getFile
without the precise flag.
partWindow is the window a part must stay within without the precise
flag.
File reference refresh results.
File reference refresh results.
File reference refresh results.
File reference refresh results.
Request results.
Request results.
Request results.
Request results.
Request results.
Builder.Verify results.
Builder.Verify results.
Builder.Verify results.
Builder.Verify results.
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.