Using Rmagick with eventmachine

99 views Asked by At

I am trying to create a very simple web service with Goliath and Grape. All that my service would do is that given an image path and a target dimension it would return the new geometry of the image. The images are stored in the same server as the host of the web service.

So I have this code within Grape:

# some Grape code omitted
get "/" do
  EM.defer {
    image = Magick::Image.read('path to image').first
    image.change_geometry('3000x3900') do |cols, row, img|
      return {width: cols, height: row}
    end
  }
end

When I visit the endpoint in the browser all I get is this string

"#<ConditionVariable:0x007ffd9de1f6e8>"

Without EM.defer it returns the following json but with very low requests/secs (about 4 reqs/sec):

{width: 'new width', height: 'new heigth'}

How could I make the Rmagick operations non blocking and make it return the results?

1

There are 1 answers

3
Aleksei Matiushkin On

It looks like you mixed things up a bit.

Call to RMagick is always blocking, since it requires the image to be processed. The good news is the call to grape itself is non-blocking. It means, that while your single clients must wait for claimed 1/3 secs to complete, another clients are still able to queue requests.

I guess your testing environment simply calls the respective service one-by-one, waiting for requests to complete. Instead of that you are to call the service from separate threads, getting results as they are ready.

Hope it helps.