Search code examples
ruby-on-railstimeoutdelaystatic-html

Strange timeout when reloading static HTML page in Rails app


I have a small static HTML page in public folder of a Rails application. This page performs AJAX requests on input keyup. Everything is fine except when I reload the page rails gets stuck for several seconds and browser has to wait. Finally Rails logs request time out and brrowser loads the page. There are no onload handlers on the page so no delay in any Rails controller may make browser to wait. What may be the cause of a delay?

Here is a code of this page:

<!DOCTYPE html>
<html>
<head>
    <title>Prompt test</title>
    <script src="/assets/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#searchbox").keyup(function(){
                if ($("#searchbox").val().length<2) {
                    $('#autocomplete').hide();
                    return;
                }
                $.ajax(
                        {
                            type: "POST",
                            url: "/prompts",
                            data: {
                                request_str: $("#searchbox").val()
                            },
                            success: function(data) {
                                $('#autocomplete').find('option').remove();
                                $('#autocomplete').attr('size', data.length);
                                console.log(data);
                                if (data.length==0) $('#autocomplete').hide(); else $('#autocomplete').show();
                                for (var i=0; i<data.length; i++) {
                                    $('#autocomplete').append($("<option></option>")
                                            .attr("value", data[i])
                                            .text(data[i]));
                                }
                            },
                            error: function(){
                                $('#autocomplete').find('option').remove();
                                $('#autocomplete').hide();
                            }
                        }
                );
            });
        });
    </script>
    <style type="text/css">
        #autocomplete{
            position: absolute;
            background: transparent;
            z-index: 10;
            width: 200px;
            display: none;
        }
    </style>
</head>
<body>
<input type="text" id="searchbox" /><br>
<select id="autocomplete" size="10" multiple="multiple">
</select>
</body>
</html>

This is the route:

match '/prompts', to: 'prompts#get_data', :via => :post

This is the controller:

require 'uri'
require 'net/http'
require 'json'

class PromptsController < ApplicationController
  skip_before_action :verify_authenticity_token

  def get_data
    uri = URI.parse("http://192.168.0.200:12345/prompts")

    data = {
        count: 10,
        text: params[:request_str],
    }

    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Post.new(uri.request_uri, { 'Content-Type' => 'text/json' })
    request.body = data.to_json

    response = http.request(request)
    if response.code=='200'
      results = JSON.parse(response.body)['results']
      render :json => results.map { |res| res['text'] }
    else
      render :json => { error: response.code }
    end
  end
end

The presence of delay depends in some way on whether AJAX requests were performed or not. If yes, there will be 70% probability of delays.

Rails log contains:

Started POST "/prompts" for 127.0.0.1 at 2014-04-02 14:19:58 +0400
Processing by PromptsController#get_data as */*
      Parameters: {"request_str"=>"gh"}
Completed 500 Internal Server Error in 60009ms

Net::ReadTimeout (Net::ReadTimeout):
  app/controllers/prompts_controller.rb:23:in `get_data'

Solution

  • All the delays were gone in a magic way when I replaced Net::HTTP with HTTPClient.