3

I have a TCP file server in Rust / Tokio stack.

When a client is uploading a file, the data is being read from a tokio::net::TcpStream and written to a futures_fs::FsWriteSink, which has been started on a separate futures_fs::FsPool.

When the file is completely uploaded, I need to check its consistency by checking its checksum against the one sent by the client.

What is the easiest way to asynchronously calculate the checksum, especially if the file does not fit into RAM?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
hedgar2017
  • 1,425
  • 3
  • 21
  • 40
  • Using a [`BufReader`](https://doc.rust-lang.org/std/io/struct.BufReader.html)? – hellow Nov 21 '18 at 13:19
  • 2
    You might also want to explore calculating the checksum for the actual data uploaded as it's being uploaded. You already have the data passing through your processing at that point, so calculating the checksum then is almost a free operation. This is especially true if you have performance considerations, because by calculating the checksum off the data after it's been saved to disk you're effectively doubling the IO operations you need to do to support file uploading. – Andrew Henle Nov 21 '18 at 13:49
  • Yeah, I totally agree. But it seems that I need to implement such thing myself, doesn't it? I'd like to have something like another `Sink`, where I could feed the chunks so the `Sink` could calculate the checksum on the fly. – hedgar2017 Nov 21 '18 at 14:47
  • What checksum? Is the implementation of the checksum naturally asynchronous? If so, just use it. If it's not, then this is a duplicate of [What is the best approach to encapsulate blocking I/O in future-rs?](https://stackoverflow.com/q/41932137/155423). – Shepmaster Nov 21 '18 at 17:59

2 Answers2

1

It depends on what checksum algorithm you want to use, but using the md5 crate as an example, you can compute the checksum on the fly. Something like this should do it:

// When starting the file transfer
let mut md5_context = md5::Context::new();

// ...

// as part of your existing processing for each block of data
md5_context.consume (&block);

// ...

// once the last block has been processed
return md5_context.compute();
Jmb
  • 18,893
  • 2
  • 28
  • 55
  • 1
    This appears to be completely synchronous. The OP has explicitly requested an asynchronous solution. – Shepmaster Nov 21 '18 at 15:11
  • 2
    @Shepmaster I don't see how you can tell whether this is synchronous or asynchronous: I only said that for each block of data he should call `md5_context.consume`, I never said that he should do it in a synchronous loop. – Jmb Nov 21 '18 at 15:46
1

Actually, making simple hashing algorithms asynchronous is in such cases somewhat redundant, as long as one MD5 calculation takes less then 1 us (about 500 ns).

But, a new blocking API is now available in tokio. It allows executing blocking or CPU heavy operations using internal threading mechanisms.

hedgar2017
  • 1,425
  • 3
  • 21
  • 40