Upload handler

upload_handler is a bit complex, because it takes POST requests with a form that contains the uploaded image:

fn upload_handler(req: HttpRequest<State>) -> impl Future<Item = HttpResponse, Error = WebError> {
req.multipart()
.map(handle_multipart_item)
.flatten()
.into_future()
.and_then(|(bytes, stream)| {
if let Some(bytes) = bytes {
Ok(bytes)
} else {
Err((MultipartError::Incomplete, stream))
}
})
.map_err(|(err, _)| WebError::from(err))
.and_then(move |image| {
debug!("Image: {:?}", image);
let request = QrRequest { image };
req.state()
.addr
.send(SendMessage(request))
.from_err()
.map(move |task_id| {
let record = Record {
task_id: task_id.clone(),
timestamp: Utc::now(),
status: Status::InProgress,
};
req.state().tasks.lock().unwrap().insert(task_id, record);
req
})
})
.map(|req| {
HttpResponse::build_from(&req)
.status(StatusCode::FOUND)
.header(header::LOCATION, "/tasks")
.finish()
})
}

The implementation gets a Stream of MultipartItem, the value of which could be either Filed or Nested. We use the following function to collect all items in a single uniform Stream of Vec<u8> objects:

pub fn handle_multipart_item(
item: MultipartItem<Payload>,
) -> Box<Stream<Item = Vec<u8>, Error = MultipartError>> {
match item {
MultipartItem::Field(field) => {
Box::new(field.concat2().map(|bytes| bytes.to_vec()).into_stream())
}
MultipartItem::Nested(mp) => Box::new(mp.map(handle_multipart_item).flatten()),
}
}

Then, we extract the first item with the into_future method. If the value exists, we map it to QrRequest and use the address of QueueActor to send a request to a worker.

You may ask whether it is possible if a worker returns a result if the ID of task wasn't set. Potentially, it's possible. If you want to have a reliable changing of State, you should implement an actor that works with the State instance exclusively.

Finally, the handler constructs a HttpResponse value that redirects the client to the /tasks path.

Now, we can connect each part in a single function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.232