H12 在 heroku 上请求超时 503 然后 200 成功

H12 Request timeout 503 on heroku then 200 success

我是 运行 一个小 docker 图像,启动了 ruby Sinatra API。 API 的要点是接收图像,使用脚本对其进行预处理,然后使用 Tesseract OCR 对图像中的文本进行 return。

我遇到的问题是我收到 503 错误,然后收到文本 300 成功,但这没有用,因为我的 ios 应用程序已经收到 503 错误并继续顺其自然。

require 'sinatra'
require "json"
require 'sinatra/base'
require 'sinatra'
require 'json'
require 'fileutils'
require 'tempfile'
require "base64"
require 'puma_worker_killer'

PumaWorkerKiller.enable_rolling_restart

set :protection, except: [ :json_csrf ]
port = ENV['PORT'] || 8080
set :port, port
set :bind, '0.0.0.0'

post '/extractText' do
  begin
    bas64Image = Base64.decode64(params[:image])
    imageFile = Tempfile.new(['image', '.png'])
    imageFile.write(bas64Image)
    imageFile.close
    `textcleaner #{imageFile.path} #{imageFile.path}`
    # `textdeskew #{imageFile.path} #{imageFile.path}`
    output = `tesseract #{imageFile.path} --psm 6 --oem 2 stdout`
    p output
  rescue
    status 402
    return "Error reading image"
  end
  status 200
  return output
end

这是我读出的 heroku:

2017-10-23T20:22:00.548029+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/extractText" host=tesseractimageserver.herokuapp.com request_id=7b179829-ef1f-4e18-844b-42b90a5c5c69 fwd="82.32.79.208" dyno=web.1 connect=1ms service=30945ms status=503 bytes=0 protocol=https
2017-10-23T20:22:42.864098+00:00 app[web.1]: "Returned text from reading image using tesseract"
2017-10-23T20:22:42.872633+00:00 app[web.1]: 82.32.79.208 - - [23/Oct/2017:20:22:42 +0000] "POST /extractText HTTP/1.1" 200 467 72.2921

有办法解决这个问题吗?

这是它的工作原理。 Heroku 对任何 Web 请求都有 30 秒的超时时间。当新请求路由到您的应用程序 dyno 并且在这 30 秒的时间限制内没有响应时,Heroku 将断开连接并报告 H12 错误。但是你的 dyno 仍在处理网络请求,甚至没有人会使用它的响应。客户已经走了。由于这种行为,建议对 long-运行 操作设置某种超时机制。如果您向此类端点发送许多请求,您可以轻松地使整个应用程序停止。

解决此问题的方法是在后台作业中处理您的图像。所以第一个请求将注册一个新工作和 return 它的 id 或某种标识符。然后,您的 ios 应用程序可以使用此 ID 定期 ping 服务器以检查作业是否已完成。