COMPUTING INFRASTRUCTURE AND HARDWARE
The State of Allocators in 2026 - Finally Stabilised!
It's only been a couple of months since the last article, and I am pleased to see that, after 10 years of limbo, allocators have finally been stabilised! While it feels like the never type did steal a bit of thunder, rust
1.100 was nonetheless a monumental release. Congratulations on the team that shepherded this through. So, now we have an MVP of the allocator API, what can we do with it? What does it get us besides closer feature parity with other system languages like C++ & Zig? In this article I'll step through a few use cases that might be handy to the layman rust programmer, so hopefully you can see the benefit. ## Allocators can adjust when memory is freed This was one of the leading cases for custom allocation. Dropping in rust is not free. There has been prior art in actually moving memory to a dedicated thread to Drop highly nested structures. This is actually only half a solution. You're still paying for the deallocation call costs, just it's not in the hot path anymore. Instead, what if we knew that we would have a period of time in our code, where we're going to allocate a lot of stuff, do something with it, and then free everything? A good example of this is a web request, or a database query. A request comes in, fills in some data structures, and then when the request finishes, the memory isn't needed anymore so it's dropped. This sort of "burst" pattern of allocation, where you allocate a lot up front, and then tear things down all at once at the end, is quite common. For this we can use a bump allocator: reserve a big block of memory, and allocate from that, rather than paying the cost of talking to the system allocator for every allocation. Think of it like the BufReader and BufWriter of std io, rather than make repeated syscalls to fetch data, we can buffer that data in a big block, so that we can reduce the overhead considerably. You want more memory? Just check if the size fits in our block, return that slice, increment our counter (bump!), and we're done. We can add more blocks as well, if we run out. This makes allocations very cheap, we don't need to keep much state around besides from a counter. The downsides of this approach is when we come to deallocate memory. We don't keep track around where individual allocations are made. However, this actually solves our drop takes a long time problem, since we can just deallocate everything all at once. Essentially if the impl of the bump allocator is: const SIZE: usize = 32 * 1024 * 1024; struct Bump { // one big 32MiB block on the heap data: Box<Cell<[u8; SIZE]>>, // how much of it we've handed out used: Cell<usize>, } impl Bump { fn new() -> Self { Bump { data: unsafe { Box::new_zeroed().assume_init() }, used: Cell::new(0) } } } unsafe impl Allocator for &Bump { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { // where we are in memory let data = self.data.as_ptr() as *mut u8; // how much we've used of `data` already let used = self.used.get(); // given the requested alignment, how many bytes do we need past `data` + `used` let alignment_padding = data.wrapping_add(used).align_offset(layout.align()); let start = used + alignment_padding; let end = start + layout.size(); if end <= SIZE { // bump! self.used.set(end); let ptr = unsafe { NonNull::new_unchecked(data.add(start)) }; return Ok(NonNull::slice_from_raw_parts(ptr, layout.size())); } // an actual bump allocator would grab another block here Err(AllocError) } unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) { // deliberately a no-op! } } Then we can use it like so: struct Node<'a> { value: u64, parent: Option<&'a Node<'a>>, } // our bump allocator let bump = Bump::new(); // leak here gives us a ref tied to the arena, the memory still goes when we drop our allocator let mut leaf: &Node = Box::leak(Box::new_in(Node { value: 0, parent: None }, &bump)); for i in 1..1_000_000 { leaf = Box::leak(Box::new_in(Node { value: i, parent: Some(leaf) }, &bump)); } // this takes virtually no time at all! drop(bump); There are a few tradeoffs for doing things like this in a bump allocator, and not every allocation is going to benefit. Hence why it's important to be able to adjust our allocation strategy locally rather than just globally. However, an astute reader might notice that, if we are bumping large swathes of memory, this is going to possibly cause our memory usage to increase considerably. Well, that brings us to our next section: memory accounting. ## Allocators can let us know how much memory they're using The next challenge that can be solved by custom allocators is knowing how much memory particular sections of code is being used. I.e, memory accounting. The key here is that, we can use existing allocators, and sprinkle in some extra bookkeeping to keep a pretty accurate ledger. There are a number of use cases that accounting can shape the behaviour of code. Say you have a cache of objects, and you want to set a threshold above which, we start evicting entries. Or say you want to do an external sort, but you don't know how big your data structures are at the start, but you want to use up as much memory as possible. Or maybe you are wanting to place a limit on a code sandbox, because it's sharing resources with other sandboxes. What you can do is wrap an allocator, with a custom accounting layer, and use this to drive your decisions. I.e, here is a very trivial example: struct AccountedAllocator<A: Allocator> { inner: A, allocated: AtomicUsize, } impl<A: Allocator> AccountedAllocator<A> { fn new(inner: A) -> Self { Self { inner, allocated: AtomicUsize::new(0) } } fn allocated(&self) -> usize { self.allocated.load(Ordering::Relaxed) } } unsafe impl<A: Allocator> Allocator for &AccountedAllocator<A> { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { // pass the allocation through, and count it if it succeeded let ptr = self.inner.allocate(layout)?; self.allocated.fetch_add(layout.size(), Ordering::Relaxed); Ok(ptr) } unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { unsafe { self.inner.deallocate(ptr, layout) }; self.allocated.fetch_sub(layout.size(), Ordering::Relaxed); } } Then we can wrap the global allocator, and see how much our cache is using: let accounted = AccountedAllocator::new(Global); let mut cache: Vec<u8, _> = Vec::new_in(&accounted); cache.extend_from_slice(&[0; 1024]); // cache is using 1024 bytes println!("cache is using {} bytes", accounted.allocated()); cache.extend_from_slice(&[0; 4096]); // cache is using 5120 bytes println!("cache is using {} bytes", accounted.allocated()); drop(cache); // cache is using 0 bytes println!("cache is using {} bytes", accounted.allocated()); ### Shameless Plug: the Thresher crate Now, a single atomic, while is great for an example, does have some perf overhead. So, one of the crates that I have created, while keeping in mind performance, is thresher: an accounting allocator with a callback on threshold. It uses a combined "local" task/thread and "global" counter to avoid atomic contention, feeding back in every 64KiB of allocation. thresher gets its name from the cutest shark: the Thresher Shark. Now, what you can do with thresher is, use it to trigger callbacks when allocations are hit: let thresher = Thresher::new(); thresher.set_callback_threshold(100 * 1024 * 1024); thresher.set_callback(|allocation| { println!("Threshold reached! Allocated: {} bytes", allocation); }); // This is what we're adding to our vec each loop let bytes = vec![0u8; 10 * 1024 * 1024]; // The vec allocates through the handle, so its buffer counts towards the // threshold. `bytes` above uses the global allocator and is not counted let mut vec = Vec::<u8, _>::new_in(thresher.handle()); for i in 0..10 { println!("Loop {i}, Vec Capacity: {}", vec.capacity()); vec.extend(&bytes); } This prints out what you'd expect: Loop 0, Vec Capacity: 0 Loop 1, Vec Capacity: 10485760 Loop 2, Vec Capacity: 20971520 Loop 3, Vec Capacity: 41943040 Loop 4, Vec Capacity: 41943040 Loop 5, Vec Capacity: 83886080 Loop 6, Vec Capacity: 83886080 Loop 7, Vec Capacity: 83886080 Loop 8, Vec Capacity: 83886080 Threshold reached! Allocated: 167772160 bytes Loop 9, Vec Capacity: 167772160 One production use case, is that we're using thresher on logfire to provide us heap profiles of our rust services when memory hits a configured threshold. I did a deep dive into heap profiles and why they are extremely useful in an older blog: a tale of two lengths. In thresher you can find a jemalloc example where you can instrument this yourself! OK so we can control memory when it is dropped, we can use memory accounting to know how much memory we're using, what's left? How about where it goes? ## Allocators can control where memory lives This is probably the more esoteric of the 3 examples I wanted to give. There are some situations where you actually need to control where the memory lives, and sometimes by doing some allocation tricks you can get better performance out. ### Allocating on the stack One example would be what smallvec and friends do. Instead of going straight to the heap to allocate things, they have a small amount that lives on the stack, and only if allocations go above a certain size, then do they write to the heap. While smallvec is more battle tested, here is some example code about how you could do this with the allocator API: struct SmallStack { // store the first 8KiB on the stack data: Cell<[u8; 8192]>, // how much we've already allocated on our stack used: Cell<usize>, } impl SmallStack { fn new() -> Self { Self { data: Cell::new([0u8; 8192]), used: Cell::new(0), } } } unsafe impl Allocator for &SmallStack { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { // where we are in memory let data = self.data.as_ptr() as *mut u8; // how much we've used of `data` already let used = self.used.get(); // given the requested alignment, how many bytes do we need past `data` + `used` let alignment_padding = data.wrapping_add(used).align_offset(layout.align()); let start = used + alignment_padding; let end = start + layout.size(); // if we have enough on our local stack: if end <= 8192 { self.used.set(end); let ptr = unsafe { NonNull::new_unchecked(data.add(start)) }; Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) } else { // otherwise allocate on the standard heap Global.allocate(layout) } } unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { let data = self.data.as_ptr().addr(); // if this isn't an address in our data if !(data..data + 8192).contains(&ptr.as_ptr().addr()) { unsafe { Global.deallocate(ptr, layout) }; } } } Then we can use our toy stack first allocator: // needs to live longer than our vec let stack = SmallStack::new(); let mut vec: Vec<u32, _> = Vec::new_in(&stack); // fits in our stack data buffer for i in 0..32 { vec.push(i); } // will eventually spill to the heap for i in 32..10_000 { vec.push(i); } Et voila! We have smaller allocations on the stack and then push to the heap as needed. This can give some good performance boosts. ### Allocating with stronger alignment Normally when you align memory allocations, this is based upon the thing that is being allocated for. I.e, is it a u64? align to 8 bytes or a u32? align to 4. If it's not correctly aligned, this can cause undefined behaviour and all sorts. You notice in both the bump and small stack example I had to do some shenanigans to find the next appropriately aligned address. However, there is some scenarios where the alignment of memory is external to what is being allocated. In linux, when you read anything from disk via standard syscalls, you are usually reading from the kernel's page cache. I.e, the spare memory the kernel has around to make things transparently fast. Most of the time that is fine, but there are some times when you want to bypass it. I.e, there is a long standing bug in kubernetes that can cause pod eviction if you are using the page cache. Or: if you are doing your own caching layer, sometimes it doesn't make sense to double up on memory devoted to caching files. So, there is a bailout provided, in the guise of O_DIRECT that allows you to directly access files from the file system. However: one of the requirements of using this flag is that you are reading or writing into memory that is aligned to the device's logical block size. This is usually a multiple of 512, but can be less or more depending on the hardware. The implementation of a block aligned allocator is pretty simple, here's one where we just hardset it to 4096: #[derive(Clone, Copy)] struct BlockAligned; // hard set here, but we could make this derived from the device itself! const BLOCK_SIZE: usize = 4096; unsafe impl Allocator for BlockAligned { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let layout = layout.align_to(BLOCK_SIZE).map_err(|_| AllocError)?; Global.allocate(layout) } unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { let layout = layout.align_to(BLOCK_SIZE).expect("layout must come from BlockAligned"); unsafe { Global.deallocate(ptr, layout) } } } With this, we can now write simple code to read directly using O_DIRECT: let mut buf: Vec<u8, BlockAligned> = Vec::new_in(BlockAligned); buf.resize(BLOCK_SIZE, 0); let mut file = OpenOptions::new() .read(true) .custom_flags(libc::O_DIRECT) .open(path)?; file.read_exact(&mut buf)?; Here, the read_exact call can fail on some devices if we're not using block size aligned allocations. Like with the stack first allocation, there are libraries that allow you do this already, such as the aligned-vec crate, with their own data types to work nicely. But here's the rub: say you had an application where you wanted to blend and mix in different allocation strategies: some vecs you want to be block aligned, some you want allocated on the stack, but you want to be able to use shared methods for both. Do we want to use smallvec and aligned-vec in order to deal with a data structure that is essentially the same thing, just allocated differently? std allocators allows you to be generic over the collections, regardless of allocator used: fn do_something<A: Allocator>(my_vec: &mut Vec<u32, A>) {} And I think that's pretty powerful. ## Conclusion and wrapping up It's going to take a bit of time for the ecosystem to catch up to custom allocators. A lot of popular crates have an MSRV policy that precludes them from using even new standard features, and some existing crates, which I would think are a shoe in for the new allocator API, as of writing do not yet have support. The libs team isn't done yet. This is the MVP of allocators, and, like I mentiond in the the last article, this is the beginning of custom allocator support. There is still work to go to support other collection types like maps etc.. so much to be done. I think that what we have is useful enough to start using it now, and also to start adapting and allowing library consumers the ability to provide their own allocators with their API. I'm excited to see what people build, and what other use cases are unlocked with it!LOGISTICS AND SUPPLY CHAINS
My Wishes for Rust 2019
2018 was a massive year for rust, and it's great to reflect back on how far we've all come. My main wish for the new year is to put on the breaks a little bit, and finish off what has been started without taking on anything majorly new. There are a couple of areas that I feel need more attention than most (purely for selfish reasons of course!): ## Compiler Times, IDE Support and RLS I think RLS is great. I think
cargo check is great too. Sometimes when I am waiting for RLS to finish in VSCode, I run cargo check in a terminal to see who wins the race. Sometimes I get results faster from the cargo check than I do in RLS. I'm not sure why that is, it might be that I'm making a lot of small edits, and RLS is constantly restarting. I am assuming that the plumbing for both methods is rather similar. On average, if I just adjust whitespace on one of my projects, it takes at least 10 seconds to recompile. If I change any trivial bit of code, this doubles to 20 seconds. I would love to have dynamic loading in rust as a first class citizen, but I fear the ABI stabilisation is a far way off (I know you can cheat by using the C ABI and libloading but there is a fair amount of unsafe code, which I'm not comfortable with). This would alleviate some of the issues around compilation times, by allowing compilation to be broken up into smaller chunks. For instance: I implemented a WebDAV handler with actix-web. This added a significant portion of time to compilation after the implementation was finished, and the code is mostly decoupled from the rest of the app and sits in its own little route (XML instead of JSON, etc..). I'd love to be able to just hot-load this as a module, rather than compile it in each time if I'm not even touching this part. Incremental compilation does help a little bit here. ### Better IDE Support I have been using VSCode as my primary rust IDE for a while now, which is great, but I'd love to be able to use IntelliJ as well. Each time there is an update, I do give it another shot, and find that there are a couple of problems with it: Weeeeeeeeeeeeeeeeeeeeeee Admittedly, each release of the IntelliJ rust plugin is better than the last, but it is not even close to the support that Java has. I am hoping that this changes in the future. I'd also love to be able to give Oni a go, but currently it's in limbo until I, or someone else, has enough time to work out what is wrong with the Language Server Integration. ## Async/Await I would really love to see the async/await story come to a close in 2019. The rust team has laid the groundwork with the 2018 edition, and together with the new pinning API I feel like it's just around the corner. This has the opportunity to really change the landscape and make rust a much more productive language. I've had a crack at writing both a multipart client & ZeroMQ library, but I can see that when the async stuff reaches stable, it's going to make life a lot easier. Kudos to the team for moving this forward (I also happen to think the logo for futures-rs is pretty rad!) ### Documentation Churn With these changes to async, there is going to be some challenges around documentation. I feel in tokio-land there is a high degree of tribal knowledge that, if you don't keep up with things, you are left behind. There is the new futures 0.3 crate, which is not currently in use by tokio crate, you have to use futures 0.1. No-one knows what happened to 0.2, it's a mystery left for future rust historians, and 0.3 is still very much in alpha. Earlier on in the year if you went straight to the docs.rs page for futures, this would direct you to the 0.3 version, which isn't helpful if you are using this in conjunction with tokio (this appears to be resolved now, by some clever use of yanking). Another example is the move away from tokio-core into the standard tokio crate. This is something that is a great evolution for tokio, but has left a number of libraries outdated. A lot of the great blogs by pioneering devs have also become outdated when dealing with this, which increases the frustration for any newcomers. I am hoping that now things are more settled that this won't be much of an issue. All of these changes adds to a high level of fatigue for developers. If you're not lucky enough to be working in this space day-to-day, coming back after 6 months would be daunting. There is a push to help modernise the documentation, but this hasn't seen much activity in a couple of months. I'm hoping to find some time in the new year to help out with this, as I think there is a lot of work to be done. ## Conclusion I think rust has come a long way and still has a long way to go. I focused a lot of energy on writing apps in rust this year, and will undoubtably accelerate the usage as time goes on. I hope that the rust team has time to put on the breaks, and apply a bit of polish before doing anything major. I also hope I have more time to contribute some bits and pieces here and there to make the community better.MUSIC AND PERFORMING ARTS
TMQ 0.1.0 Release: ZeroMQ bindings for Tokio
TMQ is a rust library to use ZeroMQ within the Tokio ecosystem. ZeroMQ is a distributed messaging queue written in C supporting a number of different messaging patterns. While there are other options out there (including gRPC, etc..), I settled on ZeroMQ due to its cross-language support, great documentation and battle-tested nature. Version
0.1.0 is an alpha release which implements request, response, publish and subscribe style sockets. ## Usage Example This example uses tmq to subscribe to messages, and then prints them out via pretty-env-logger: extern crate failure; extern crate futures; #[macro_use] extern crate log; extern crate pretty_env_logger; extern crate tmq; extern crate tokio; use futures::{Future, Stream}; use tmq::*; use std::env; fn main() { if let Err(_) = env::var("RUST_LOG") { env::set_var("RUST_LOG", "subscribe=DEBUG"); } pretty_env_logger::init(); let request = subscribe(&Context::new()) .connect("tcp://127.0.0.1:7899") .expect("Couldn't connect") .subscribe("") .for_each(|val| { info!("Subscribe: {}", val.as_str().unwrap_or("")); Ok(()) }) .map_err(|e| { error!("Error Subscribing: {}", e); }); tokio::run(request); } Other examples of usage can be found in the project itself: https://github.com/cetra3/tmq/tree/master/examples ## Existing Rust Crates To find out where tmq sits within the rust ecosystem, it makes sense to discuss this in terms of other ZeroMQ crates. ### zmq - Rust ZeroMQ Bindings This library has bindings to the C API and provides a great way to use ZeroMQ within rust. You still need a copy of ZeroMQ on your system and need it compiled in, but that difficulty is pretty much on par with using OpenSSL. I have managed to use this library in OSX, CentOS and Ubuntu with not many issues. The only downside of this library is the lack of bindings to tokio, and is one of the primary motivators for creating tmq. ### zmq.rs - A Native Implementation of ZeroMQ in Rust This library was a Rewrite in Rust attempt at a full ZeroMQ reimplementation, which hasn't seen any changes since 2015 and can probably be considered abandoned. Regardless: this API is still the old blocking style, which would still predicate a need for tmq ### zmq-tokio - Run ØMQ sockets using tokio reactors, futures, etc. Not even published on crates.io but a great initial attempt at bridging the async gap. This crate used the historic tokio-core library which is a bit of a pain to adapt to the new tokio crate. Unfortunately it looks like it's since been abandoned. ### tokio-zmq - ZeroMQ Concepts with futures on Tokio's runtime This library is probably the most polished version for tokio and one that would be compared mostly to tmq. I would have chosen this library, but the one major roadblock is the GPL license. The GPL within a rust project is viral. You can't use this library without making the rest of your project GPL or GPL Compatible. If this doesn't concern you, then I would consider using this library. ### Comparison between tmq In comparison to tokio-zmq, tmq has less boilerplate to acheive the same thing, but does use a couple of custom traits to speed things along. This makes tmq a bit more opinionated, but less verbose. Both styles have their merits, tokio-zmq does give you more control over things wheras tmq is, in my opinion, easier to write and reason about, but more restrictive in how you use it. To do a direct comparison of both libraries we're using the response example. This example is a simple echo response, which when it receives a message, it echos it back verbatim to the requester. #### tokio-zmq Here is the excerpt from tokio-zmq: let ctx = Arc::new(zmq::Context::new()); let req_fut = Req::builder(ctx).connect("tcp://localhost:5560").build(); let runner = req_fut.and_then(|req| { req.send(build_multipart(0)).and_then(|req| { let (sink, stream) = req.sink_stream(25).split(); stream .zip(iter_ok(1..10_000)) .map(|(multipart, i)| { for msg in multipart { if let Some(msg) = msg.as_str() { println!("Received: {}", msg); } } build_multipart(i) }) .forward(sink) }) }); On of the things you will notice is there is a lot of standard futures and tokio types used here: sink, stream, etc.. While this does make it more verbose, you are using constructs that you are familiar with in the futures style. ### tmq Here's a similar example (although not using multipart messages) from tmq: let responder = respond(&Context::new()) .bind("tcp://127.0.0.1:7899")? .with(|msg: Message| { info!("Request: {}", msg.as_str().unwrap_or("")); Ok(msg) }); You'll notice that the library has a bit less boilerplate, but is more opinionated on how you structure a response. Instead of a sink/stream approach, the responder is a stream but has a with method. The with method takes anything that implements the Responder trait, of which there is a blanket implemenation for closures and functions that take a message and return a message. ## Future Changes While currently usable, the tmq library is far from finished and requires some work to bring it out of an alpha state. In no particular order here are the plans for the library: #### Testing Unit tests and integration tests need to be added in order to confirm and wire up connections. As the library is rather lightweight now the need for integration tests hasn't really arisen, but this will become more complicated in the future as more socket types are added. #### Benchmarking Benchmarks need to be added to the library in order to show the performance of using this over standard zmq. Running up some dummy benchmarks show that it is perfomant enough for my current use case, and provides less overhead than your standard REST API calls. #### Windows Support I cheated a little by using the Evented trait for mio, which makes it dead easy to use in tokio via PollEvented2. Unfortunately the async story on windows is a bit different, and I haven't had a need to deploy on windows just yet. But it is something that has been considered. #### Documentation The library is mostly undocumented besides from the examples. Documentation should be pretty easy to do at this stage and won't take too long. #### More Socket Types Implementing more socket types, to make this feature complete with the standard zmq library. There a plethora of different socket types for different use cases that give different guarantees. The 4 standard ones implemented are enough for me to start using this library today, but could easily be expanded. #### Multipart messages Multipart support for messages. Currently this is not supported, but should be mostly easy to implement ## Further thoughts I'm currently using tmq within an actix-web application to bridge some messages and audit logs between a polyglot backend (including Java & Python). It has been quite solid so far, and I have plans to remove an existing ActiveMQ service to be replaced with tmq where appropriate. Version 0.1.0 is the first real release, with previous releases having to vendor in the zmq library in order to publish. While it is alpha, I don't plan to change what is there currently unless there is a compelling reason to do so. Please give tmq a try and let me know your thoughts!VISUAL ARTS AND DESIGN
Face Detection with Tensorflow Rust
One of the promises of machine learning is to be able to use it for object recognition in photos. This includes being able to pick out features such as animals, buildings and even faces. This article will step you through using some existing models to accomplish face detection using rust and tensorflow. For the impatient among you, you can find the source code here: https://github.com/cetra3/mtcnn We will be using a pre-trained model called mtcnn for face detection (Note: training a new model is not something we'll be concerned with in this article). ## The Challenge We want to read the photo, have the faces detected, and then return an image with the bounding boxes drawn in. In other words, we want to convert this (Image used with permission of RustFest, taken by Fiona Castiñeira): Into this: ## Tensorflow and MTCNN The original MTCNN model was written using Caffe, but luckily there is a number of tensorflow python implementations for mtcnn. I'm going to pick the following as it is a straight conversion into a single graph model file. Firstly we want to add tensorflow rust as a dependency. Here's a Cargo.toml to start:
[package] name = "mtcnn" version = "0.1.0" edition = "2018" [dependencies] tensorflow = "0.12.0" What we're going to do is load a Graph which is the pre-trained MTCNN, and run a session. The gist is that a Graph is the model used for computation, and a Session is one run of the Graph. A lot more information about these concepts can be found here. I like to think of the Graph as an artificial brain in a vat, just to get some great imagery when you start plugging in inputs and outputs. So let's start by grabbing the existing mtcnn.pb model and trying to load it up. Tensorflow graphs are serialised out in protobuf format and can be loaded in using Graph::import_graph_def. use std::error::Error; use tensorflow::Graph; use tensorflow::ImportGraphDefOptions; fn main() -> Result<(), Box<dyn Error>> { //First, we load up the graph as a byte array let model = include_bytes!("mtcnn.pb"); //Then we create a tensorflow graph from the model let mut graph = Graph::new(); graph.import_graph_def(&*model, &ImportGraphDefOptions::new())? Ok(()) } Running cargo run we should see no errors: $ cargo run Compiling mtcnn v0.1.0 (~/mtcnn) Finished dev [unoptimized + debuginfo] target(s) in 0.89s Running `target/debug/mtcnn` Great! Looks like we can load the graph! ## StructOpt and the Command Line We're going to want to test out image generation, so let's use structopt to take two arguments: input and output. If you haven't used structopt before: structopt is like combining clap with serde. The input argument will be the path of an image file. The output will be where we save the output image. So our struct looks like this: use std::path::PathBuf; use structopt::StructOpt #[derive(StructOpt)] struct Opt { #[structopt(parse(from_os_str))] input: PathBuf, #[structopt(parse(from_os_str))] output: PathBuf } The parse(from_os_str) attribute will convert a string argument directly into a PathBuf to save us some boiler plate We can then use this to get a struct with our command line arguments fn main() -> Result<(), Box<dyn Error>> { let opt = Opt::from_args(); .... } ## Loading Image Data We need to provide the tensorflow graph with our image data. So how do we do that? We use a Tensor! Tensors represent data within our graph, it sort of reminds me of sending vertices to a GPU. You have a big slice of data, and send it in a format that tensorflow is expecting. The input tensor in this graph is an array of floats, with dimensions: height x width x 3 (for 3 colour channels). Let's use the image crate to load the image: let input_image = image::open(&opt.input)?; Next we want to convert this image into its raw pixels by using the GenericImage::pixels function and send that to our graph. All multi-dimensional Tensor arrays are flat, and stored in row major order. The model uses BGR instead of the traditional RGB for colours, so we'll need to reverse the pixel values when we iterate through. Putting it all together: let mut flattened: Vec<f32> = Vec::new(); for (_x, _y, rgb) in input_image.pixels() { flattened.push(rgb[2] as f32); flattened.push(rgb[1] as f32); flattened.push(rgb[0] as f32); } This simply iterates through the pixels, adding them to a flattened Vec. We can then load this into a tensor, specifying the image height and width as arguments: let input = Tensor::new(&[input_image.height() as u64, input_image.width() as u64, 3]) .with_values(&flattened)? Great! we have loaded our image into a format that the graph understands. Let's run a session! ### Creating a tensorflow session Ok, we have a graph, the input image, but now we need a session for the graph. We'll just use the defaults for this: let session = Session::new(&SessionOptions::new(), &graph)?; ## Running a session Before we run a session, we have a few other inputs the mtcnn model is expecting. We're gonna use the same defaults the mtcnn library for these values: let min_size = Tensor::new(&[]).with_values(&[40f32])?; let thresholds = Tensor::new(&[3]).with_values(&[0.6f32, 0.7f32, 0.7f32])?; let factor = Tensor::new(&[]).with_values(&[0.709f32])?; The graph can define multiple inputs/outputs that are required before running and it depends on the specific neural net as to what these are. For MTCNN, these are all described in the original implementation. Probably the most important one is the min_size which describes the minimum size to find faces. Now we build the session arguments for the inputs: let mut args = SessionRunArgs::new(); //Load our parameters for the model args.add_feed(&graph.operation_by_name_required("min_size")?, 0, &min_size); args.add_feed(&graph.operation_by_name_required("thresholds")?, 0, &thresholds); args.add_feed(&graph.operation_by_name_required("factor")?, 0, &factor); //Load our input image args.add_feed(&graph.operation_by_name_required("input")?, 0, &input); Ok, what about outputs? There are two that we are going to request when the session is finished: bounding boxes and probabilities: let bbox = args.request_fetch(&graph.operation_by_name_required("box")?, 0); let prob = args.request_fetch(&graph.operation_by_name_required("prob")?, 0); Ok cool, we have our inputs, and our outputs, let's run it! session.run(&mut args)?; ### The BBox struct The model outputs the following values: - Bounding box of the faces - Landmarks of the faces - Probability that it's a face from 0 to 1 In order to make it a bit more easy to work with, we'll define a bounding box struct which encodes those values back in a more easy to read fashion: #[derive(Copy, Clone, Debug)] pub struct BBox { pub x1: f32, pub y1: f32, pub x2: f32, pub y2: f32, pub prob: f32, } We'll omit landmarks for simplicity, but can always add them back if we need. Our job is to convert the arrays we get back from the tensorflow session into this struct so it's more meaningful. ### Saving the Output Right, now let's grab back the outputs. Just like inputs, outputs are Tensors too: let bbox_res: Tensor<f32> = args.fetch(bbox)?; let prob_res: Tensor<f32> = args.fetch(prob)?; What is the shape of bbox? Well, it's a multi-dimensional flattened array that includes 4 floats per bounding box representing the bounding box extents. The prob is an array with a single float value per face: the probability from 0 to 1. So we should expect the bbox_res length to be the number of faces x 4, and prob_res to be equal to the number of faces. Let's do some basic iteration and store our results into a Vec: //Let's store the results as a Vec<BBox> let mut bboxes = Vec::new(); let mut i = 0; let mut j = 0; //While we have responses, iterate through while i < bbox_res.len() { //Add in the 4 floats from the `bbox_res` array. //Notice the y1, x1, etc.. is ordered differently to our struct definition. bboxes.push(BBox { y1: bbox_res[i], x1: bbox_res[i + 1], y2: bbox_res[i + 2], x2: bbox_res[i + 3], prob: prob_res[j], // Add in the facial probability }); //Step `i` ahead by 4. i += 4; //Step `i` ahead by 1. j += 1; } ##### Combinators Alternatively, we could use combinators to replace the one above. let bboxes: Vec<_> = bbox_res .chunks_exact(4) // Split into chunks of 4 .zip(prob_res.iter()) // Combine it with prob_res .map(|(bbox, &prob)| BBox { y1: bbox[0], x1: bbox[1], y2: bbox[2], x2: bbox[3], prob, }) .collect(); ### Printing out the bounding boxes Ok, we haven't encoded the bounding boxes into an image, yet. but let's debug to make sure we're getting back something: println!("BBox Length: {}, Bboxes:{:#?}", bboxes.len(), bboxes); Running this, what do we get back: BBox Length: 120, BBoxes:[ BBox { x1: 471.4591, y1: 287.59888, x2: 495.3053, y2: 317.25327, prob: 0.9999908 }, .... Whoa! 120 faces! Awesome! ## Drawing the Bounding Boxes Great, we have some bounding boxes. Let's draw them on the image, and save the output into a file. To draw bounding boxes, we can use the imageproc library to draw simple borders around the bounding boxes. Firstly, we'll make the line colour constant green outside of our main() function: const LINE_COLOUR: Rgba<u8> = Rgba { data: [0, 255, 0, 0], }; Now stepping back into it. We are feeding in the input image read only, so let's use the first image to draw onto: let mut output_image = input_image; Then we iterate through our bounding boxes: for bbox in bboxes { //Drawing Happens Here! } Next, we use the draw_hollow_rect_mut function. This will take a mutable image reference, and draw a hollow rectangle (outline) specified by the input Rect, overwriting any existing pixels. The Rect takes an x and y coordinate with the at function, and then a width and height with the of_size function. We use a bit of geometry to convert our bounding box to this format: let rect = Rect::at(bbox.x1 as i32, bbox.y1 as i32) .of_size((bbox.x2 - bbox.x1) as u32, (bbox.y2 - bbox.y1) as u32); Then draw the rect: draw_hollow_rect_mut(&mut output_image, rect, LINE_COLOUR); Once the for loop is done, we save it in the output file: output_image.save(&opt.output)?; And we're done. Let's run it! $ cargo run rustfest.jpg output.jpg Compiling mtcnn v0.1.0 (~/mtcnn) Finished dev [unoptimized + debuginfo] target(s) in 5.12s Running `target/debug/mtcnn rustfest.jpg output.jpg` 2019-03-28 16:15:48.194933: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.2 AVX AVX2 FMA BBox Length: 154, BBoxes:[ BBox { x1: 951.46875, y1: 274.00577, x2: 973.68304, y2: 301.93915, prob: 0.9999999 }, .... Looks good, no errors! ## Wrapping up Let's step through what we've done in this little application: - Loaded a pre-trained tensorflow graph - Parse the command line arguments - Read in image data - Extracted faces by running a tensorflow session - Saved the results of that session back to the image - Wrote out the file If you got stuck at any point, have a look at the repository here: https://github.com/cetra3/mtcnn Hopefully this gives you a good introduction to using tensorflow in rustLOGISTICS AND SUPPLY CHAINS
Face Detection with Actix Web
Last article I wrote about how to use tensorflow with rust. This time we're going to take what we've built on, and serve it as an HTTP API call. As Actix Web is nearing its inevitable 1.0 release, I thought it would be a great time to build something with it. This article assumes you have some knowledge about Futures and how they work. I will do my best to explain in simpler terms, but understanding the futures ecosystem would be quite handy to help work through this article. For this, I suggest you start with tokio. (Some people have suggested waiting for async/await and friends to land before diving into Futures. I think you should get your hands dirty now: async programming will always be challenging and the changes being introduced only affect ergonomics, not fundamentals) Once again for the impatient, you can find the reference code here on the
actix-web branch: https://github.com/cetra3/mtcnn/tree/actix-web ## API Shape The API shape here is rather simple. We want to emulate what we've done on the command line: Submit a picture, have a picture returned. To make things interesting, we'll provide a way to return the bounding boxes as a JSON array too. For submitting binary data via HTTP, there are a few options off the top of my head: - Simply submit the raw data as it stands - Use multipart/form-data - Encode it as a JSON submission I think the easiest would be just the raw data so let's do that! Multipart could possibly also work, but what about the case when you have to handle multiple images? JSON Submission seems a bit wasteful, as you would inevitably have to convert binary data using base64 or similar. So our API looks like this: - Submit POST request as a raw file submission - Run a session against mtcnn to extract faces - Either return Bounding Boxes as JSON, or an Image Overlay as a JPEG like the command line example ## MTCNN as a struct In our last blog we just simply used the main function to perform everything, but it's not going to fly with actix until we do a bit of a refactor. We want to encapsulate the mtcnn behaviour as a struct, something that can be passed around and moved. The end goal is to use it in the application state. ### Struct Shape Let's make our struct include everything we need: - The Graph - The Session - Some of the Tensor input params that don't change from request to request. We'll start by creating a new file mtcnn.rs and adding in the struct definition. use tensorflow::{Graph, Session, Tensor}; pub struct Mtcnn { graph: Graph, session: Session, min_size: Tensor<f32>, thresholds: Tensor<f32>, factor: Tensor<f32> } Ok, now we're just going to plop in the initiation stuff in a new() method. As the creation of some of these values is not infallible, we'll return a Result: pub fn new() -> Result<Self, Box<dyn Error>> { let model = include_bytes!("mtcnn.pb"); let mut graph = Graph::new(); graph.import_graph_def(&*model, &ImportGraphDefOptions::new())?; let session = Session::new(&SessionOptions::new(), &graph)?; let min_size = Tensor::new(&[]).with_values(&[40f32])?; let thresholds = Tensor::new(&[3]).with_values(&[0.6f32, 0.7f32, 0.7f32])?; let factor = Tensor::new(&[]).with_values(&[0.709f32])?; Ok(Self { graph, session, min_size, thresholds, factor }) } ### The Run Function (I'm going to race along here to get to the good parts, so if you get stuck or are unsure about what's going on, have a look at the original article for an explanation of what's happening here.) We've added all the bits we need to run our session Let's create a method that does what we're asking the API to do: submit an image, return some bounding boxes: pub fn run(&self, img: &DynamicImage) -> Result<Vec<BBoxes>, Status> { ... } Once again, we are returning a Result as the type, as there are some parts of the run that can fail. We're going to use the Status type as that is normally the error type returned Like our previous main function, we'll need to flatten the image input: let input = { let mut flattened: Vec<f32> = Vec::new(); for (_x, _y, rgb) in img.pixels() { flattened.push(rgb[2] as f32); flattened.push(rgb[1] as f32); flattened.push(rgb[0] as f32); } Tensor::new(&[img.height() as u64, img.width() as u64, 3]) .with_values(&flattened)? }; Then we'll feed in all the relevant inputs. This is just the same as our previous main function, but we're going to just borrow values from self rather than create them for each run: let mut args = SessionRunArgs::new(); args.add_feed( &self.graph.operation_by_name_required("min_size")?, 0, &self.min_size, ); args.add_feed( &self.graph.operation_by_name_required("thresholds")?, 0, &self.thresholds, ); args.add_feed( &self.graph.operation_by_name_required("factor")?, 0, &self.factor, ); args.add_feed(&self.graph.operation_by_name_required("input")?, 0, &input); Next, let's grab the outputs we want: let bbox = args.request_fetch(&self.graph.operation_by_name_required("box")?, 0); let prob = args.request_fetch(&self.graph.operation_by_name_required("prob")?, 0); ### Running The Session Now we have all our args set up, we can run the session: &self.session.run(&mut args)?; Uh oh. We're getting a compiler error here... error[E0596]: cannot borrow `self.session` as mutable, as it is behind a `&` reference --> src/mtcnn.rs:68:10 | 36 | pub fn run(&self, img: &DynamicImage) -> Result<DynamicImage, Box<dyn Error>> { | ----- help: consider changing this to be a mutable reference: `&mut self` ... 68 | &self.session.run(&mut args)?; | ^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable Turns out that the Session::run() function takes &mut self. What can we do to resolve this: - Make our run function take &mut self so we can mutate the field - Do some tricky interior mutability - Submit an issue on the tensorflow-rust crate to see whether Session really needs to take &mut self. We'll go with option 3! Update your Cargo.toml to point to the git master, rather than the cargo version: tensorflow = { git = "https://github.com/tensorflow/rust"} ### Getting the Bounding Boxes This has not changed at all since our main method. We grab the bounding boxes, put them in our handy dandy BBox struct: //Our bounding box extents let bbox_res: Tensor<f32> = args.fetch(bbox)?; //Our facial probability let prob_res: Tensor<f32> = args.fetch(prob)?; //Let's store the results as a Vec<BBox> let mut bboxes = Vec::new(); let mut i = 0; let mut j = 0; //While we have responses, iterate through while i < bbox_res.len() { //Add in the 4 floats from the `bbox_res` array. //Notice the y1, x1, etc.. is ordered differently to our struct definition. bboxes.push(BBox { y1: bbox_res[i], x1: bbox_res[i + 1], y2: bbox_res[i + 2], x2: bbox_res[i + 3], prob: prob_res[j], // Add in the facial probability }); //Step `i` ahead by 4. i += 4; //Step `i` ahead by 1. j += 1; } debug!("BBox Length: {}, BBoxes:{:#?}", bboxes.len(), bboxes); Ok(bboxes) And that's our run function finished. ### BBox Struct as JSON We're gonna want to return a JSON representation of the BBox struct. So let's add in serde_derive: use serde_derive::Serialize; #[derive(Copy, Clone, Debug, Serialize)] pub struct BBox { pub x1: f32, pub y1: f32, pub x2: f32, pub y2: f32, pub prob: f32, } ### Drawing the Output Image We'll create a function that will take a list of bounding boxes and an input image, returning the output image: pub fn overlay(img: &DynamicImage, bboxes: &Vec<BBox>) -> DynamicImage This hasn't changed much either, but we are returning the image, rather than saving it to a file: //Let's clone the input image let mut output_image = img.clone(); //Iterate through all bounding boxes for bbox in bboxes { //Create a `Rect` from the bounding box. let rect = Rect::at(bbox.x1 as i32, bbox.y1 as i32) .of_size((bbox.x2 - bbox.x1) as u32, (bbox.y2 - bbox.y1) as u32); //Draw a green line around the bounding box draw_hollow_rect_mut(&mut output_image, rect, LINE_COLOUR); } output_image Ok, we're pretty much done with our Mtcnn struct and functions! Could we break this down even further? Yeah definitely! But for now, I think this is all we need. We've encapsulated the behaviour and created a nice to use couple of functions. ## Our New Main Function Ok, so we're no longer using it as a CLI, but as a self-hosted web app. We're going to need to change the arguments our application takes since we no longer have input and output files. I think the only argument we should be taking initially is the listen address, and even then we should use a sensible default. So let's use the help of structopt to make this pretty minimal boilerplate: #[derive(StructOpt)] struct Opt { #[structopt( short = "l", long = "listen", help = "Listen Address", default_value = "127.0.0.1:8000" )] listen: String, } ### Logging Framework Actix Web uses the log crate to display errors and debug messages. Let's move on from using println! and instead use log. I like using pretty_env_logger as it prints different levels as a different colour, and we can have timestamps which is useful. pretty_env_logger still uses environment vars. Let's cheat and set our RUST_LOG var if none is provided then initiate our logger //Set the `RUST_LOG` var if none is provided if env::var("RUST_LOG").is_err() { env::set_var("RUST_LOG", "mtcnn=DEBUG,actix_web=DEBUG"); } //Create a timestamped logger pretty_env_logger::init_timed(); This sets up DEBUG level logs for our app and actix web, but allows us to change the log levels via environment variables still. ## Actix and State We have some state we need to pass to actix to use: our Mtcnn struct and the run method. There are a number of ways you can give State to actix, but probably the easiest way is the App::data method. As we are now entering a multithreaded world, we're going to have to think about what things are Send and Sync. Ok, so how do we share something between threads? Well, as a first step I would look to std::sync to see what we need. Since we know that mtcnn's run function does not need to mutate it, only requiring a reference to immutable self, we can probably wrap it in an Arc. If we had to mutate it, then it would probably require a Mutex as well, but we can avoid this if we use the master branch of tensorflow-rust as above. So let's create our Arc: let mtcnn = Arc::new(Mtcnn::new()?); Now, to instantiate the server: HttpServer::new(move || { App::new() //Add in our mtcnn struct, we clone the reference for each worker thread .data(mtcnn.clone()) //Add in a logger to see the requests coming through .wrap(middleware::Logger::default()) // Add in some routes here .service( ... ) }) .bind(&opt.listen)? // Use the listener from the command arguments .run() Ok, let's step through what we're doing: - We first build a HttpServer - This takes a closure which should return an App. This App is instantiated for each thread the http server is running - We add our Arc<Mtcnn> using the data method, and clone it for each thread listener. - We add a logger middleware. - We set up some routes with the service function - Then we bind to a listen address and run ## Handling a Request Actix Web is an Async framework and uses tokio. Our function is Synchronous and takes some time to complete. In other words, our request is blocking. Can we mix and match sync and async? Absolutely, but it is a little more cumbersome as you'll see. ### Function Signature and Extractors Actix 1.0 makes heavy use of Extractors, which is a way of providing functions of quite different shapes. You basically specify what you want your web function to receive, and actix will wire it up for you. Take care though: This does mean that some things won't be discovered wrong until runtime. A perfect example I had when I used the wrong type signature for the web::Data argument. So what do we need to extract from our request? The bytes of the request body, and and also our mtcnn: fn handle_request( stream: web::Payload, mtcnn: web::Data<Arc<Mtcnn>>, ) -> impl Future<Item = HttpResponse, Error = ActixError> { ... } We will use this type signature for mtcnn a fair bit, so let's make a type alias for it: type WebMtcnn = web::Data<Arc<Mtcnn>>; ## Getting the Image from a Payload Ok, so we need a way of retrieving the image from a payload and returning a Future. The web::Payload struct implements Stream with Item set to Bytes. Well, we don't really care about the individual bytes we get from a stream, we want the whole lot to decode the image! So let's convert the Stream into a Future, and merge all the individual bytes we'll be getting into one big bucket of bytes. Sounds complicated, but luckily Stream has a method: concat2. This is a pretty powerful combinator which allows us to join the results of individual Stream polls into one if the item implements Extend (and some other traits) which Bytes happens to. So this looks like: stream.concat2().and_then(....) ### Image Decoding and web::block Ok, second thing we need to sort out, if we're going to be decoding an image, that is probably going to block the thread until it's done. How long? Well if it's a huge image, it might take milliseconds! So we want to ensure that we're not blocking the http workers while this is happening. Luckily, actix web has a way of taking a blocking portion of code, and wrapping that as a future. Enter web::block. We'll do our decoding in a cpu pool, bridging sync and async together: stream.concat2().and_then(move |bytes| { web::block(move || { image::load_from_memory(&bytes) }) }) Ok, that is pretty succint: we take a stream, convert it into a future and a bundle of bytes, then use web::block to decode the bytes into an image in a background thread and return the result. the load_from_memory function already returns a Result, which means we can just use that as the return type. ### Balancing the Error Type So, our Item is converted to Bytes to DynamicImage, but we still haven't dealt with the error types yet and it won't compile. What should our error type be? Let's use actix_web::Error as ActixError: use actix_web::{Error as ActixError} fn get_image(stream: web::Payload) -> impl Future<Item = DynamicImage, Error = ActixError> { stream.concat2().and_then(move |bytes| { web::block(move || { image::load_from_memory(&bytes) }) }) } Ok, that is giving us few really gnarly errors when we try and compile it: error[E0271]: type mismatch resolving `<impl futures::future::Future as futures::future::IntoFuture>::Error == actix_http::error::PayloadError` --> src/main.rs:67:22 | 67 | stream.concat2().and_then(move |bytes| { | ^^^^^^^^ expected enum `actix_threadpool::BlockingError`, found enum `actix_http::error::PayloadError` | = note: expected type `actix_threadpool::BlockingError<image::image::ImageError>` found type `actix_http::error::PayloadError` There's a couple more that aren't listed. When you are combining streams, mapping them as futures, and otherwise trying to get some output from these combinators you are actually dealing with both the Item type, and the Error type. The ergonomics of this are not as advanced as the Result type, where we can use the ? operator to automatically adjust to the right error (if a conversion is available). When both ops::Try and async/await syntax stabilises, this might be a different story, but for now, we need to deal with error types. What we have instead is the magic™️ from_err() method. This is basically the same as the ? operator but for futures. We have two futures we're dealing with: our bundle of bytes from the stream, and the image from the blocking closure. We have 3 error types we're dealing with: the Payload error, the Image load from memory error, and the blocking error. Let's start by putting from_err() on both of the futures: fn get_image(stream: web::Payload) -> impl Future<Item = DynamicImage, Error = ActixError> { stream.concat2().from_err().and_then(move |bytes| { web::block(move || { image::load_from_memory(&bytes) }).from_err() }) } That worked! There is enough conversions for our error types to get to where we need to get it. The ActixError type has a few blanket conversions from common error types enough to be able to make this magic happen. ## Getting the bounding boxes from the image At the core of it, we need to run the following: mtcnn.run(&img) But we want this to run in a threadpool too: web::block(|| mtcnn.run(&img)) Let's work through the function signature we'll need. At a minimum we're gonna need the image, and the mtcnn struct. Then we want to return a Vec of BBoxes. We should try and keep our error types the same, so we'll use the ActixError type. The function signature looks like this: fn get_bboxes(img: DynamicImage, mtcnn: WebMtcnn) -> impl Future<Item = Vec<BBox>, Error = ActixError> We know that we'll need a from_err() on the web::block to convert the error type, and we'll have to use a move to give the image to the closure: fn get_bboxes(img: DynamicImage, mtcnn: WebMtcnn) -> impl Future<Item = Vec<BBox>, Error = ActixError> { web::block(move || mtcnn.run(&img)).from_err() } But does this compile? Not yet: error[E0277]: `*mut tensorflow_sys::TF_Status` cannot be sent between threads safely --> src/main.rs:75:5 | 75 | web::block(move || mtcnn.run(&img)).from_err() | ^^^^^^^^^^ `*mut tensorflow_sys::TF_Status` cannot be sent between threads safely | = help: within `tensorflow::Status`, the trait `std::marker::Send` is not implemented for `*mut tensorflow_sys::TF_Status` = note: required because it appears within the type `tensorflow::Status` = note: required by `actix_web::web::block` tensorflow::Status, which is the error type, can't be sent between threads. Let's just shortcut here, and convert the error to a String: fn get_bboxes(img: DynamicImage, mtcnn: WebMtcnn) -> impl Future<Item = Vec<BBox>, Error = ActixError> { web::block(move || mtcnn.run(&img).map_err(|e| e.to_string())).from_err() } This allows us to move the Result across thread boundaries, as String does implement Send ## Returning JSON BBoxes Ok, so we have 2 functions, one to get the image from the request, and one to get the bounding boxes. We're gonna want to return json HttpResponse: fn return_bboxes( stream: web::Payload, mtcnn: WebMtcnn, ) -> impl Future<Item = HttpResponse, Error = ActixError> { // Get the image from the input stream get_image(stream) // Get the bounding boxes from the image .and_then(move |img| get_bboxes(img, mtcnn)) // Map the bounding boxes to a json HttpResponse .map(|bboxes| HttpResponse::Ok().json(bboxes)) } Cool! Let's put this in our App definition: HttpServer::new(move || { App::new() .data(mtcnn.clone()) .wrap(middleware::Logger::default()) // our new API service .service(web::resource("/api/v1/bboxes").to_async(return_bboxes)) }) .bind(&opt.listen)? .run() And let's run it, using curl to submit a query to get some results back $ curl --data-binary @rustfest.jpg http://localhost:8000/api/v1/bboxes [{"x1":471.4591,"y1":287.59888,"x2":495.3053,"y2":317.25327,"prob":0.9999908}.... Awesome! Using jmespath to see we get our 120 faces back: $ curl -s --data-binary @rustfest.jpg http://localhost:8000/api/v1/bboxes | jp "length(@)" 120 ## Returning an Overlay Image The other API call we want is to return an image with the bounding boxes overlayed. This is not much of a stretch, but the act of drawing boxes on an image is definitely a blocking action, so we'll need to do the same thing and send it to a thread pool. Let's wrap our overlay function, converting it into a Future: fn get_overlay(img: DynamicImage, bboxes: Vec<BBox>) -> impl Future<Item = Vec<u8>, Error = ActixError> { web::block(move || { let output_img = overlay(&img, &bboxes); ... }).from_err() } We're going to want to return a Vec of u8 bytes so we can use this in the return body. So we'll need to allocate some buffer and instruct image to write out a JPEG from the image: let mut buffer = vec![]; output_img.write_to(&mut buffer, JPEG)?; // write out our buffer Ok(buffer) Ok, so let's put our little function together and see if it compiles: fn get_overlay(img: DynamicImage, bboxes: Vec<BBox>) -> impl Future<Item = Vec<u8>, Error = ActixError> { web::block(move || { let output_img = overlay(&img, &bboxes); let mut buffer = Vec::new(); output_img.write_to(&mut buffer, JPEG)?; // write out our buffer Ok(buffer) }).from_err() } Not quite yet: we're missing a type annotation: error[E0282]: type annotations needed --> src/main.rs:82:5 | 82 | web::block(move || { | ^^^^^^^^^^ cannot infer type for `E` Why is there an issue with the type? Well, it relates to this line here: Ok(buffer) // What's the `Error` type here? At the moment, the only error type is from the write_to method which is ImageError. But this line here doesn't have an error type, and could be anything. There are 3 ways I can immediately think to handle this: Way Number 1: Declare the error type in web::block web::block::<_,_,ImageError> This looks more like a turbosubmarine than a turbofish! But it compiles! Way Number 2: Declare the Result type with as Ok(buffer) as Result<_, ImageError> Way Number 3: Use map to return the buffer on success: output_img.write_to(&mut buffer, JPEG).map(|_| buffer) I think for readability, #2 is probably easiest. The web::block function takes 3 type arguments which can be confusing on first read of the code. #3 is good too but I think it looks a bit strange. Our final method looks like: fn get_overlay(img: DynamicImage, bboxes: Vec<BBox>) -> impl Future<Item = Vec<u8>, Error = ActixError> { web::block(move || { let output_img = overlay(&img, &bboxes); let mut buffer = Vec::new(); output_img.write_to(&mut buffer, JPEG)?; // Type annotations required for the `web::block` Ok(buffer) as Result<_, ImageError> }).from_err() } ### The API call Ok, we have our little futures that we need to return bounding boxes and image overlays. Let's stitch this together and return a HttpResponse: fn return_overlay( stream: web::Payload, mtcnn: WebMtcnn, ) -> impl Future<Item = HttpResponse, Error = ActixError> { //... magic happens here } Ok, first step is to get the image from the stream: get_image(stream) And Then once the future has resolved, we want to get the bounding boxes: get_image(stream).and_then(move |img| { get_bboxes(img, mtcnn) }) ### Moving Images Around Now we want to get the image overlay. We have an issue though! we give the get_bboxes future our image, and it returns a Vec of bboxes, consuming the image. There are a couple of options here. We could clone() the image when we give it to bboxes, but that is duplicating memory. We could wait for Pin and async/await to be finished and probably deal with it in an easier way then. Or we could adjust our get_bboxes method to return a tuple of both the image and bounding boxes: fn get_bboxes( img: DynamicImage, mtcnn: WebMtcnn, ) -> impl Future<Item = (DynamicImage, Vec<BBox>), Error = ActixError> { web::block(move || { mtcnn .run(&img) .map_err(|e| e.to_string()) //Return both the image and the bounding boxes .map(|bboxes| (img, bboxes)) }) .from_err() } Making sure to update our return_bboxes function too: fn return_bboxes( stream: web::Payload, mtcnn: WebMtcnn, ) -> impl Future<Item = HttpResponse, Error = ActixError> { get_image(stream) .and_then(move |img| get_bboxes(img, mtcnn)) .map(|(_img, bboxes)| HttpResponse::Ok().json(bboxes)) } ### Getting the Overlay It would be great if rust could desugar a tuple into command arguments. Unfortunately not for us, so we will need to create a small closure: //Create our image overlay .and_then(|(img, bbox)| get_overlay(img, bbox)) .map(|buffer| { // Return a `HttpResponse` here }) ### Generating the Response Our HttpResponse needs to wrap the buffer into a Http Request with the buffer as the body: HttpResponse::with_body(StatusCode::OK, buffer.into()) Is that it? Well no, we have to set the content type header to be a jpeg: let mut response = HttpResponse::with_body(StatusCode::OK, buffer.into()); response .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("image/jpeg")); Ok now we can return the result: fn return_overlay( stream: web::Payload, mtcnn: WebMtcnn, ) -> impl Future<Item = HttpResponse, Error = ActixError> { get_image(stream) .and_then(move |img| { get_bboxes(img, mtcnn) }) .and_then(|(img, bbox) | get_overlay(img, bbox)) .map(|buffer| { let mut response = HttpResponse::with_body(StatusCode::OK, buffer.into()); response .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("image/jpeg")); response }) } And add that to our App builder: HttpServer::new(move || { App::new() .data(mtcnn.clone()) //Add in our data handler //Add in a logger to see the requets coming through .wrap(middleware::Logger::default()) //JSON bounding boxes .service(web::resource("/api/v1/bboxes").to_async(return_bboxes)) //Image overlay .service(web::resource("/api/v1/overlay").to_async(return_overlay)) } Great! Let's run it: $ curl --data-binary @rustfest.jpg http://localhost:8000/api/v1/bboxes > output.jpg And we have our original overlay! ## Conclusions We stepped through converting a CLI app into a HTTP service, dipping our toes into the brave new async world. As you can see, actix web is a very versatile web framework. My interest in it was borne out of having all the features I need to build up web apps: multipart, thread pools, great efficiency. While it is hard to bridge the sync and async gap, it's not impossible. It would be great if there were some more ergonomic ways to do so, as I think a lot of developers struggle with this: I have seen a lot of questions around integrating with diesel and friends. If you are looking for more actix web examples, the evergrowing examples repo is your best bet: https://github.com/actix/examples I look forward to seeing what the community builds in the future!