vaegram 0.3.0

Telegram MTProto client library for users and bots
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use std::pin::Pin;
use std::sync::atomic::AtomicI32;
use std::time::Duration;

use tokio::io::{AsyncRead, AsyncReadExt};

use crate::Client;
use crate::crypto::random;
use crate::errors::{Error, Result};
use crate::raw::{base, functions, types};
use crate::session::Session;
use crate::session::pacer::{Direction, Pace, Pacer};
use crate::session::transfer::{Progress, Report, invoke_paced_part, part_timeout, take, try_join_all, workers};
use crate::types::Upload;

// https://core.telegram.org/api/files#uploading-files
const PART_SIZE: u64 = 512 * 1024;
const BIG_FILE_SIZE: u64 = 10 * 1024 * 1024;
const MAX_PARTS: u64 = 4000;
const MAX_PARTS_PREMIUM: u64 = 8000;

#[must_use = "a request does nothing until it is awaited"]
pub(crate) struct SaveFile<'a> {
    client: &'a Client,
    input: Input<'a>,
    progress: Option<Report<'a>>,
}

enum Input<'a> {
    Upload(Upload<'a>),
    Stream { reader: Pin<Box<dyn AsyncRead + Send + 'a>>, size: u64, name: &'a str },
}

impl Client {
    pub(crate) fn save_file<'a>(&'a self, file: impl Into<Upload<'a>>) -> SaveFile<'a> {
        SaveFile { client: self, input: Input::Upload(file.into()), progress: None }
    }

    pub(crate) fn save_stream<'a>(
        &'a self,
        stream: impl AsyncRead + Send + 'a,
        size: u64,
        name: &'a str,
    ) -> SaveFile<'a> {
        let input = Input::Stream { reader: Box::pin(stream), size, name };
        SaveFile { client: self, input, progress: None }
    }
}

impl<'a> SaveFile<'a> {
    pub(crate) fn progress(mut self, progress: Option<Report<'a>>) -> Self {
        self.progress = progress;
        self
    }

    async fn send(self) -> Result<base::InputFile> {
        let (source, size, name) = match self.input {
            Input::Upload(upload @ Upload::Path(path)) => {
                let disk = tokio::fs::File::open(path).await?;
                let size = disk.metadata().await?.len();
                (Source::File(tokio::sync::Mutex::new(disk)), size, upload.name())
            }
            Input::Upload(upload @ Upload::Bytes { data, .. }) => {
                (Source::Bytes(data), data.len() as u64, upload.name())
            }
            Input::Stream { reader, size, name } => (Source::Stream(tokio::sync::Mutex::new(reader)), size, name),
        };
        // Checked before the limits: looking up Premium can cost a request.
        if size == 0 {
            return Err(Error::FileSize { size: 0, limit: MAX_PARTS * PART_SIZE });
        }
        let _slot = self.client.upload_slot().await;
        let (parts, workers, connections) = self.client.upload_limits(size).await?;
        let home = self.client.dc(self.client.session().dc_id())?;
        let lease = self.client.transfer_sessions(home, connections).await?;
        let sessions = &lease.sessions;
        // A connection carries its share of the workers' parts at once, more of them when it opened fewer.
        let timeout = part_timeout(workers.div_ceil(sessions.len()) as u64 * PART_SIZE);
        let (big, id) = (size > BIG_FILE_SIZE, i64::from_le_bytes(random()));
        let upload = Parts { source, size, count: parts, big, id, timeout };
        let (next, progress) = (AtomicI32::new(0), Progress::new(self.progress, size));
        // Premium changes the shape only, which upload_limits already took.
        let plan = self.client.transfer_plan(Direction::Upload, false, Some(size));
        let pacer = self.client.pacer(home.id, Direction::Upload, plan);
        let send = |i: usize| upload.send(&sessions[i % sessions.len()], &next, &progress, pacer.as_deref());
        try_join_all((0..workers).map(send)).await?;
        Ok(upload.input_file(name))
    }
}

into_future!(SaveFile, base::InputFile);

impl Client {
    async fn upload_limits(&self, size: u64) -> Result<(i32, usize, usize)> {
        let premium = match self.is_premium().await {
            Err(e) if size > MAX_PARTS * PART_SIZE => return Err(e),
            premium => premium.unwrap_or(false),
        };
        let parts = part_count(size, premium)?;
        let shape = self.transfer_plan(Direction::Upload, premium, Some(size)).shape;
        let workers = workers(parts, PART_SIZE, shape.in_flight(PART_SIZE));
        Ok((parts, workers, workers.min(shape.connections)))
    }
}

fn part_count(size: u64, premium: bool) -> Result<i32> {
    let limit = if premium { MAX_PARTS_PREMIUM } else { MAX_PARTS } * PART_SIZE;
    if size == 0 || size > limit {
        return Err(Error::FileSize { size, limit });
    }
    Ok(size.div_ceil(PART_SIZE) as i32)
}

enum Source<'a> {
    File(tokio::sync::Mutex<tokio::fs::File>),
    Stream(tokio::sync::Mutex<Pin<Box<dyn AsyncRead + Send + 'a>>>),
    Bytes(&'a [u8]),
}

struct Parts<'a> {
    source: Source<'a>,
    size: u64,
    count: i32,
    big: bool,
    id: i64,
    timeout: Duration,
}

impl Parts<'_> {
    fn len(&self, part: i32) -> usize {
        (self.size - part as u64 * PART_SIZE).min(PART_SIZE) as usize
    }

    async fn read(&self, next: &AtomicI32, buf: &mut Vec<u8>) -> Result<Option<i32>> {
        match &self.source {
            Source::File(file) => self.read_locked(file, next, buf).await,
            Source::Stream(stream) => self.read_locked(stream, next, buf).await,
            Source::Bytes(data) => {
                let Some(part) = take(next, self.count) else { return Ok(None) };
                let start = part as usize * PART_SIZE as usize;
                buf.clear();
                buf.extend_from_slice(&data[start..start + self.len(part)]);
                Ok(Some(part))
            }
        }
    }

    /// The part number is taken under the lock, so parts are read in order.
    async fn read_locked<R: AsyncRead + Unpin + Send>(
        &self,
        reader: &tokio::sync::Mutex<R>,
        next: &AtomicI32,
        buf: &mut Vec<u8>,
    ) -> Result<Option<i32>> {
        let mut reader = reader.lock().await;
        let Some(part) = take(next, self.count) else { return Ok(None) };
        buf.resize(self.len(part), 0);
        reader.read_exact(buf).await?;
        Ok(Some(part))
    }

    async fn send(
        &self,
        session: &Session,
        next: &AtomicI32,
        progress: &Progress<'_>,
        pacer: Option<&Pacer>,
    ) -> Result<()> {
        let (file_id, mut bytes) = (self.id, Vec::with_capacity(PART_SIZE.min(self.size) as usize));
        while let Some(file_part) = self.read(next, &mut bytes).await? {
            let pace = Pace { pacer, bytes: bytes.len() as u64, gated: false };
            let saved = if self.big {
                let total = self.count;
                let request = functions::upload::SaveBigFilePart { file_id, file_part, file_total_parts: total, bytes };
                let saved = invoke_paced_part(session, &request, self.timeout, pace).await;
                bytes = request.bytes;
                saved
            } else {
                let request = functions::upload::SaveFilePart { file_id, file_part, bytes };
                let saved = invoke_paced_part(session, &request, self.timeout, pace).await;
                bytes = request.bytes;
                saved
            };
            if !saved? {
                return Err(Error::Unexpected("upload.saveFilePart returned false"));
            }
            progress.add(bytes.len());
        }
        Ok(())
    }

    fn input_file(&self, name: &str) -> base::InputFile {
        let (id, parts, name) = (self.id, self.count, name.to_owned());
        if self.big {
            base::InputFile::InputFileBig(Box::new(types::InputFileBig { id, parts, name }))
        } else {
            base::InputFile::InputFile(Box::new(types::InputFile { id, parts, name, md5_checksum: String::new() }))
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::AtomicI32;
    use std::time::Duration;

    use super::{BIG_FILE_SIZE, MAX_PARTS, MAX_PARTS_PREMIUM, PART_SIZE, Parts, Source, part_count};
    use crate::Client;
    use crate::client::Transmissions;
    use crate::errors::{Error, RpcError};
    use crate::raw::functions::users::GetUsers;
    use crate::raw::{Identifiable, Serializable, base, types};
    use crate::session::transfer::{MIN_PART_TIMEOUT, try_join_all};
    use crate::types::Upload;

    fn premium_user() -> Vec<u8> {
        let mut user = Vec::new();
        for word in [1u32 << 28, 0] {
            word.serialize(&mut user);
        }
        7i64.serialize(&mut user);
        let user = types::User::deserialize_bare(&mut &user[..]).unwrap();
        let mut reply = Vec::new();
        vec![base::User::User(Box::new(user))].serialize(&mut reply);
        reply
    }

    #[tokio::test]
    async fn uploads_with_regular_limits_when_the_account_lookup_fails() {
        let failed = Err(Error::Rpc(RpcError::parse(500, "INTERNAL")));
        let (client, mut sent) = Client::scripted(vec![failed, Ok(premium_user())]);
        client.0.me.lock().unwrap().is_bot = false;
        let get_users = GetUsers::CONSTRUCTOR_ID.to_le_bytes();
        let mut lookups = || std::iter::from_fn(|| sent.try_recv().ok()).filter(|b| b[..4] == get_users).count();
        let big = MAX_PARTS * PART_SIZE + 1;

        assert_eq!(client.upload_limits(3 << 20).await.unwrap(), (6, 6, 4));
        assert!(matches!(client.upload_limits(big).await, Ok((4001, 8, 8))));
        assert_eq!(lookups(), 2);
        assert_eq!(client.upload_limits(3 << 20).await.unwrap(), (6, 6, 6));
        assert_eq!(lookups(), 0);

        client.0.events.reconnected();
        assert!(matches!(client.upload_limits(big).await, Err(Error::Disconnected)));
        assert_eq!(lookups(), 1);
    }

    #[test]
    fn counts_512k_parts_up_to_the_account_limit() {
        assert!(matches!(part_count(0, false), Err(Error::FileSize { size: 0, .. })));
        let count = |size| part_count(size, false).unwrap();
        assert_eq!(
            (count(1), count(PART_SIZE), count(PART_SIZE + 1), count(BIG_FILE_SIZE), count(BIG_FILE_SIZE + 1)),
            (1, 1, 2, 20, 21)
        );
        assert_eq!(count(MAX_PARTS * PART_SIZE), 4000);
        assert!(matches!(part_count(MAX_PARTS * PART_SIZE + 1, false), Err(Error::FileSize { .. })));
        assert_eq!(part_count(MAX_PARTS * PART_SIZE + 1, true).unwrap(), 4001);
        assert!(matches!(part_count(MAX_PARTS_PREMIUM * PART_SIZE + 1, true), Err(Error::FileSize { .. })));
    }

    fn stream(data: &[u8]) -> Source<'_> {
        Source::Stream(tokio::sync::Mutex::new(Box::pin(data)))
    }

    async fn split(data: &[u8]) -> Vec<usize> {
        split_from(Source::Bytes(data), data).await
    }

    async fn split_from(source: Source<'_>, data: &[u8]) -> Vec<usize> {
        let count = part_count(data.len() as u64, false).unwrap();
        let big = data.len() as u64 > BIG_FILE_SIZE;
        let parts = Parts { source, size: data.len() as u64, count, big, id: 7, timeout: MIN_PART_TIMEOUT };
        let (next, mut sizes, mut joined, mut buf) = (AtomicI32::new(0), Vec::new(), Vec::new(), Vec::new());
        while let Some(n) = parts.read(&next, &mut buf).await.unwrap() {
            assert_eq!(n as usize, sizes.len());
            sizes.push(buf.len());
            joined.extend_from_slice(&buf);
        }
        assert_eq!(joined, data);
        sizes
    }

    #[tokio::test]
    async fn reads_parts_in_order() {
        let part = PART_SIZE as usize;
        assert_eq!(split(b"a").await, [1]);
        assert_eq!(split(&vec![1; part]).await, [part]);
        assert_eq!(split(&vec![1; part + 1]).await, [part, 1]);
        let big = split(&vec![2; BIG_FILE_SIZE as usize + 1]).await;
        assert_eq!((big.len(), big[20]), (21, 1));
    }

    #[tokio::test]
    async fn reads_a_stream_in_part_order() {
        let part = PART_SIZE as usize;
        let data: Vec<u8> = (0..part + 1).map(|i| i as u8).collect();
        assert_eq!(split_from(stream(&data[..1]), &data[..1]).await, [1]);
        assert_eq!(split_from(stream(&data[..part]), &data[..part]).await, [part]);
        assert_eq!(split_from(stream(&data), &data).await, [part, 1]);
    }

    #[tokio::test]
    async fn a_short_stream_fails_with_unexpected_eof() {
        let source = stream(b"hello");
        let parts = Parts { source, size: 10, count: 1, big: false, id: 7, timeout: MIN_PART_TIMEOUT };
        let e = parts.read(&AtomicI32::new(0), &mut Vec::new()).await.err();
        assert!(matches!(&e, Some(Error::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof), "{e:?}");
    }

    #[tokio::test]
    async fn an_empty_upload_is_refused_before_any_request() {
        let (client, mut sent) = Client::recording();
        {
            let mut me = client.0.me.lock().unwrap();
            (me.is_bot, me.premium) = (false, None);
        }
        let empty = [client.save_file(Upload::bytes("a.txt", b"")).await, client.save_stream(&b""[..], 0, "a").await];
        for e in empty {
            assert!(matches!(e, Err(Error::FileSize { size: 0, .. })), "{e:?}");
        }
        assert!(sent.try_recv().is_err());
    }

    #[tokio::test]
    async fn an_upload_waits_for_a_free_slot_but_an_empty_one_does_not() {
        let (mut client, mut sent) = Client::recording();
        Arc::get_mut(&mut client.0).unwrap().transmissions = Some(Transmissions::new(1));
        {
            let mut me = client.0.me.lock().unwrap();
            (me.is_bot, me.premium) = (false, None);
        }
        let held = client.upload_slot().await;
        let waiting = tokio::spawn({
            let client = client.clone();
            async move { client.save_file(Upload::bytes("a.txt", b"x")).await.map(drop) }
        });
        for _ in 0..50 {
            tokio::task::yield_now().await;
        }
        assert!(!waiting.is_finished() && sent.try_recv().is_err(), "the upload ran without a slot");
        let empty = client.save_file(Upload::bytes("a.txt", b"")).await;
        assert!(matches!(empty, Err(Error::FileSize { size: 0, .. })), "{empty:?}");
        drop(held);
        for _ in 0..50 {
            tokio::task::yield_now().await;
        }
        assert!(sent.try_recv().is_ok(), "the upload didn't start once the slot was free");
        waiting.abort();
    }

    #[test]
    fn switches_to_big_files_above_10_mb() {
        let file = |size: u64| {
            let big = size > BIG_FILE_SIZE;
            let count = part_count(size, false).unwrap();
            Parts { source: Source::Bytes(&[]), size, count, big, id: 7, timeout: MIN_PART_TIMEOUT }.input_file("a.bin")
        };
        let base::InputFile::InputFile(small) = file(BIG_FILE_SIZE) else { panic!("10 MB is still a small file") };
        assert_eq!((small.id, small.parts, small.name.as_str(), small.md5_checksum.as_str()), (7, 20, "a.bin", ""));
        assert!(matches!(file(BIG_FILE_SIZE + 1), base::InputFile::InputFileBig(f) if f.parts == 21));
    }

    /// Puts 8 connections to `client`'s home DC in its pool, all its session.
    fn on_eight(client: &Client) {
        let home = client.dc(client.session().dc_id()).unwrap();
        for _ in 0..8 {
            client.0.transfers.insert(home, &client.session());
        }
    }

    /// When each of the first `n` requests reached the session behind `sent`, after `start`.
    async fn sent_after(
        sent: &mut tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>,
        start: tokio::time::Instant,
        n: usize,
    ) -> Vec<Duration> {
        let mut at = Vec::new();
        while at.len() < n && sent.recv().await.is_some() {
            at.push(start.elapsed());
        }
        at
    }

    /// Uploads 16 parts, 8 MiB, from `client` on 8 connections, all its session, and returns when each part went.
    async fn sixteen_parts(client: &Client, sent: &mut tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>) -> Vec<Duration> {
        on_eight(client);
        let (start, data) = (tokio::time::Instant::now(), vec![1; 16 * PART_SIZE as usize]);
        let upload = async { client.save_file(Upload::bytes("a.bin", &data)).await };
        let (file, sent_at) = tokio::join!(upload, sent_after(sent, start, 16));
        assert!(matches!(file, Ok(base::InputFile::InputFile(f)) if f.parts == 16));
        sent_at
    }

    #[tokio::test(start_paused = true)]
    async fn a_bots_parts_go_two_to_a_connection_at_its_pace() {
        let (client, mut sent) = Client::scripted((0..16).map(|_| Ok(true.to_bytes())).collect());
        // 16 parts in flight on 8 connections.
        assert_eq!(client.upload_limits(20 << 20).await.unwrap(), (40, 16, 8));
        // A part's time at 19.5 MiB/s, about 25.6 ms.
        let part_time = Duration::from_nanos(PART_SIZE * 1_000_000_000 / (39 << 19));
        for (k, at) in sixteen_parts(&client, &mut sent).await.into_iter().enumerate() {
            let turn = part_time * k as u32;
            assert!(turn <= at && at <= turn + Duration::from_millis(1), "part {k} went at {at:?}, not {turn:?}");
        }
    }

    #[tokio::test(start_paused = true)]
    async fn a_user_accounts_upload_is_not_paced() {
        let (client, mut sent) = Client::scripted((0..16).map(|_| Ok(true.to_bytes())).collect());
        {
            let mut me = client.0.me.lock().unwrap();
            (me.is_bot, me.premium) = (false, Some(false));
        }
        assert_eq!(sixteen_parts(&client, &mut sent).await, [Duration::ZERO; 16]);
    }

    #[tokio::test(start_paused = true)]
    async fn a_bots_small_uploads_at_once_all_go_at_once() {
        let (client, mut sent) = Client::scripted((0..20).map(|_| Ok(true.to_bytes())).collect());
        on_eight(&client);
        // Under 8 MiB a bot's upload goes as a user's: 2 parts each on 2 connections, unpaced.
        assert_eq!(client.upload_limits(1 << 20).await.unwrap(), (2, 2, 2));
        let (start, data) = (tokio::time::Instant::now(), vec![1u8; 1 << 20]);
        let (client, data) = (&client, &data[..]);
        let upload = |_| async move { client.save_file(Upload::bytes("a.jpg", data)).await };
        let uploads = try_join_all((0..10).map(upload));
        let (files, sent_at) = tokio::join!(uploads, sent_after(&mut sent, start, 20));
        assert_eq!(files.unwrap().len(), 10);
        assert_eq!(sent_at, [Duration::ZERO; 20]);
    }
}