Handler

We need to create an empty struct, because our worker doesn't have a state and will only transform incoming messages:

struct WokerHandler {}

We use the WorkerHandler struct as the handler for the queue and use it with QueueActor later. Implement the QueueHandler trait, which is required by QueueActor:

impl QueueHandler for WokerHandler {
type Incoming = QrRequest;
type Outgoing = QrResponse;

fn incoming(&self) -> &str {
REQUESTS
}
fn outgoing(&self) -> &str {
RESPONSES
}
fn handle(
&self,
_: &TaskId,
incoming: Self::Incoming,
) -> Result<Option<Self::Outgoing>, Error> {
debug!("In: {:?}", incoming);
let outgoing = self.scan(&incoming.image).into();
debug!("Out: {:?}", outgoing);
Ok(Some(outgoing))
}
}

Since this handler takes requests and prepares responses, we set QrRequest as the Incoming type and QrResponse as the Outgoing type. The incoming method returns the value of the REQUESTS constant that we will use as a name for incoming queues. The outgoing method returns the RESPONSES constant, which is used as the name for the queue of outgoing messages.

The handle method of QueueHandler takes a request and calls the scan method with data. Then, it converts the Result into a QrResponse and returns it. Let's implement the scan method, which decodes images:

impl WokerHandler {
fn scan(&self, data: &[u8]) -> Result<String, Error> {
let image = image::load_from_memory(data)?;
let luma = image.to_luma().into_vec();
let scanner = Scanner::new(
luma.as_ref(),
image.width() as usize,
image.height() as usize,
);
scanner
.scan()
.extract(0)
.ok_or_else(|| format_err!("can't extract"))
.and_then(|code| code.decode().map_err(|_| format_err!("can't decode")))
.and_then(|data| {
data.try_string()
.map_err(|_| format_err!("can't convert to a string"))
})
}
}

The implementation of the function is not important from a microservices point of view, and I will describe it shortly—it loads an Image from the provided bytes, converts the Image to grayscale with the to_luma method, and provides the returned value as an argument for a Scanner. Then, it uses the scan method to decode the QR code and extracts the first Code converted to a String.

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

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