webmcp
view framework/env/request/handler.lua @ 335:75be5e3f3581
Set default value of max requests per fork to 200 instead of 100
| author | jbe | 
|---|---|
| date | Tue Mar 24 17:38:50 2015 +0100 (2015-03-24) | 
| parents | 3db9b672ee73 | 
| children | 169dfbd0246a | 
 line source
     1 --[[--
     2 success =         -- false if an error occurred, true otherwise
     3 request.handler(
     4   http_request,   -- HTTP request object
     5 )
     7 Called by mcp.lua to process an HTTP request. Calls request.router(), and handles the request. Note: request initializers will have to be (automatically) executed before this function is invoked by mcp.lua.
     9 --]]--
    11 local function file_exists(filename)
    12   local file = io.open(filename, "r")
    13   if file then
    14     io.close(file)
    15     return true
    16   else
    17     return false
    18   end
    19 end
    21 function request.handler(http_request, close)
    22   request._http_request = http_request
    23   local path = http_request.path
    24   if path then
    25     local relative_baseurl_elements = {}
    26     for match in string.gmatch(path, "/") do
    27       relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
    28     end
    29     if #relative_baseurl_elements > 0 then
    30       request._relative_baseurl = table.concat(relative_baseurl_elements)
    31     else
    32       request._relative_baseurl = "./"
    33     end
    34   else
    35     request._relative_baseurl = nil
    36   end
    37   request._route = request.router()
    38   do
    39     local post_id = http_request.post_params["_webmcp_id"]
    40     if post_id then
    41       request._route.id = post_id
    42     end
    43   end
    45   local success, error_info = xpcall(
    46     function()
    48       if not request._route then
    49         request._route = {}
    50         if request.get_404_route() then
    51           request.set_status("404 Not Found")
    52           request.forward(request.get_404_route())
    53         else
    54           error("Could not route request URL")
    55         end
    56       end
    58       if request._route.static then
    59         local f, errmsg = io.open(WEBMCP_BASE_PATH .. "static/" .. request._route.static, "r")
    60         if not f then
    61           request.set_status("404 Not Found")
    62           if request.get_404_route() then
    63             request.set_status("404 Not Found")
    64             request.forward(request.get_404_route())
    65           else
    66             error('Could not open static file "' .. request._route.static .. '": ' .. errmsg)
    67           end
    68         else
    69           local d = assert(f:read("*a"))
    70           f:close()
    71           slot.put_into("data", d)
    72           local filename_extension = string.match(request._route.static, "%.([^.]+)$")
    73           slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
    74           request.allow_caching()
    75           return
    76         end
    77       end
    79       -- restore slots if coming from http redirect
    80       do
    81         local tempstore_value = http_request.get_params["_tempstore"]
    82         if tempstore_value then
    83           trace.restore_slots{}
    84           local blob = tempstore.pop(tempstore_value)
    85           if blob then slot.restore_all(blob) end
    86         end
    87       end
    89       if request.get_action() then
    90         trace.request{
    91           module = request.get_module(),
    92           action = request.get_action()
    93         }
    94         if
    95           request.get_404_route() and
    96           not file_exists(
    97             encode.action_file_path{
    98               module = request.get_module(),
    99               action = request.get_action()
   100             }
   101           )
   102         then
   103           request.set_status("404 Not Found")
   104           request.forward(request.get_404_route())
   105         else
   106           if http_request.method ~= "POST" then
   107             request.set_status("405 Method Not Allowed")
   108             request.add_header("Allow", "POST")
   109             error("Tried to invoke an action with a GET request.")
   110           end
   111           local action_status = execute.filtered_action{
   112             module = request.get_module(),
   113             action = request.get_action(),
   114           }
   115           if not request.is_rerouted() then
   116             local routing_mode, routing_module, routing_view, routing_anchor
   117             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
   118             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
   119             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
   120             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
   121             if not (routing_mode or routing_module or routing_view) then
   122               action_status = "default"
   123               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
   124               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   125               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   126               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   127             end
   128             assert(routing_module, "Routing information has no module.")
   129             assert(routing_view,   "Routing information has no view.")
   130             if routing_mode == "redirect" then
   131               local routing_params = {}
   132               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   133                 local status, stripped_key = string.match(
   134                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   135                 )
   136                 if status == action_status then
   137                   routing_params[stripped_key] = value
   138                 end
   139               end
   140               request.redirect{
   141                 module = routing_module,
   142                 view   = routing_view,
   143                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   144                 params = routing_params,
   145                 anchor = routing_anchor
   146               }
   147             elseif routing_mode == "forward" then
   148               request.forward{ module = routing_module, view = routing_view }
   149             else
   150               error("Missing or unknown routing mode in request parameters.")
   151             end
   152           end
   153         end
   154       else
   155         -- no action
   156         trace.request{
   157           module = request.get_module(),
   158           view   = request.get_view()
   159         }
   160         if
   161           request.get_404_route() and
   162           not file_exists(
   163             encode.view_file_path{
   164               module = request.get_module(),
   165               view   = request.get_view()
   166             }
   167           )
   168         then
   169           request.set_status("404 Not Found")
   170           request.forward(request.get_404_route())
   171         end
   172       end
   174       if not request.get_redirect_data() then
   175         request.process_forward()
   176         local view = request.get_view()
   177         if string.find(view, "^_") then
   178           error("Tried to call a private view (prefixed with underscore).")
   179         end
   180         execute.filtered_view{
   181           module = request.get_module(),
   182           view   = view,
   183         }
   184       end
   186     end,
   188     function(errobj)
   189       return {
   190         errobj = errobj,
   191         stacktrace = string.gsub(
   192           debug.traceback('', 2),
   193           "^\r?\n?stack traceback:\r?\n?", ""
   194         )
   195       }
   196     end
   197   )
   199   if not success then trace.error{} end
   201   -- TODO: extend trace system to generally monitor execution time
   202   -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   204   slot.select('trace', trace.render)  -- render trace information
   206   local redirect_data = request.get_redirect_data()
   208   -- log error and switch to error layout, unless success
   209   if not success then
   210     local errobj     = error_info.errobj
   211     local stacktrace = error_info.stacktrace
   212     if not request._status then
   213       request._status = "500 Internal Server Error"
   214     end
   215     http_request:close_after_finish()
   216     slot.set_layout('system_error')
   217     slot.select('system_error', function()
   218       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   219         slot.put(
   220           "<p>Database error of class <b>",
   221           encode.html(errobj.code),
   222           "</b> occured:<br/><b>",
   223           encode.html(errobj.message),
   224           "</b></p>"
   225         )
   226       else
   227         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   228       end
   229       slot.put("<p>Stack trace follows:<br/>")
   230       slot.put(encode.html_newlines(encode.html(stacktrace)))
   231       slot.put("</p>")
   232     end)
   233   elseif redirect_data then
   234     redirect_data = table.new(redirect_data)
   235     redirect_data.params = table.new(redirect_data.params)
   236     local slot_dump = slot.dump_all()
   237     if slot_dump ~= "" then
   238       redirect_data.params._tempstore = tempstore.save(slot_dump)
   239     end
   240     http_request:send_status("303 See Other")
   241     for i, header in ipairs(request._response_headers) do
   242       http_request:send_header(header[1], header[2])
   243     end
   244     http_request:send_header("Location", encode.url(redirect_data))
   245     http_request:finish()
   246   end
   248   if not success or not redirect_data then
   250     http_request:send_status(request._status or "200 OK")
   251     for i, header in ipairs(request._response_headers) do
   252       http_request:send_header(header[1], header[2])
   253     end
   254     if not request._cache_manual then
   255       local cache_time = request._cache_time
   256       if request._cache and cache_time and cache_time > 0 then
   257         http_request:send_header("Cache-Control", "max-age=" .. cache_time)
   258       else
   259         http_request:send_header("Cache-Control", "no-cache")
   260       end
   261     end
   262     http_request:send_header("Content-Type", slot.get_content_type())
   263     http_request:send_data(slot.render_layout())
   264     http_request:finish()
   265   end
   267   return success
   269 end
