webmcp
view framework/env/request/handler.lua @ 301:216cd6ca6bc8
Removed CPU string from trace output
| author | jbe | 
|---|---|
| date | Sun Mar 22 19:28:07 2015 +0100 (2015-03-22) | 
| parents | c1b561ee56c1 | 
| children | 3181d410437c | 
 line source
     1 --[[--
     2 request.handler(
     3   http_request,   -- HTTP request object
     4   close           -- boolean indicating whether the server should announce to close the connection
     5 )
     7 Called by mcp.lua to process an HTTP request. Performs some initializations, calls request.router(), and handles the request.
     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   _G.app = {}  -- may be overwritten or modified by request initializers
    23   do
    24     request._in_progress = true  -- NOTE: must be set to true before initializer functions are called
    25     for i, func in ipairs(request._initializers) do
    26       func()
    27     end
    28   end
    30   request._http_request = http_request
    31   local path = http_request.path
    32   if path then
    33     local relative_baseurl_elements = {}
    34     for match in string.gmatch(path, "/") do
    35       relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
    36     end
    37     if #relative_baseurl_elements > 0 then
    38       request._relative_baseurl = table.concat(relative_baseurl_elements)
    39     else
    40       request._relative_baseurl = "./"
    41     end
    42   else
    43     request._relative_baseurl = nil
    44   end
    45   request._route = request.router() or {}
    46   do
    47     local post_id = http_request.post_params["_webmcp_id"]
    48     if post_id then
    49       request._route.id = post_id
    50     end
    51   end
    53   if close then
    54     request.add_header("Connection", "close")
    55   end
    57   local success, error_info = xpcall(
    58     function()
    60       if request._route.static then
    61         local f, errmsg = io.open(WEBMCP_BASE_PATH .. "static/" .. request._route.static, "r")
    62         if not f then
    63           if request.get_404_route() then
    64             request.set_status("404 Not Found")
    65             request.forward(request.get_404_route())
    66             return
    67           else
    68             error('Could not open static file "' .. request._route.static .. '": ' .. errmsg)
    69           end
    70         end
    71         local d = assert(f:read("*a"))
    72         f:close()
    73         slot.put_into("data", d)
    74         local filename_extension = string.match(request._route.static, "%.([^.]+)$")
    75         slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
    76         request.allow_caching()
    77         return
    78       end
    80       -- restore slots if coming from http redirect
    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
    88       if request.get_action() then
    89         trace.request{
    90           module = request.get_module(),
    91           action = request.get_action()
    92         }
    93         if
    94           request.get_404_route() and
    95           not file_exists(
    96             encode.action_file_path{
    97               module = request.get_module(),
    98               action = request.get_action()
    99             }
   100           )
   101         then
   102           request.set_status("404 Not Found")
   103           request.forward(request.get_404_route())
   104         else
   105           if http_request.method ~= "POST" then
   106             request.set_status("405 Method Not Allowed")
   107             request.add_header("Allow", "POST")
   108             error("Tried to invoke an action with a GET request.")
   109           end
   110           local action_status = execute.filtered_action{
   111             module = request.get_module(),
   112             action = request.get_action(),
   113           }
   114           if not request.is_rerouted() then
   115             local routing_mode, routing_module, routing_view, routing_anchor
   116             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
   117             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
   118             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
   119             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
   120             if not (routing_mode or routing_module or routing_view) then
   121               action_status = "default"
   122               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
   123               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   124               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   125               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   126             end
   127             assert(routing_module, "Routing information has no module.")
   128             assert(routing_view,   "Routing information has no view.")
   129             if routing_mode == "redirect" then
   130               local routing_params = {}
   131               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   132                 local status, stripped_key = string.match(
   133                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   134                 )
   135                 if status == action_status then
   136                   routing_params[stripped_key] = value
   137                 end
   138               end
   139               request.redirect{
   140                 module = routing_module,
   141                 view   = routing_view,
   142                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   143                 params = routing_params,
   144                 anchor = routing_anchor
   145               }
   146             elseif routing_mode == "forward" then
   147               request.forward{ module = routing_module, view = routing_view }
   148             else
   149               error("Missing or unknown routing mode in request parameters.")
   150             end
   151           end
   152         end
   153       else
   154         -- no action
   155         trace.request{
   156           module = request.get_module(),
   157           view   = request.get_view()
   158         }
   159         if
   160           request.get_404_route() and
   161           not file_exists(
   162             encode.view_file_path{
   163               module = request.get_module(),
   164               view   = request.get_view()
   165             }
   166           )
   167         then
   168           request.set_status("404 Not Found")
   169           request.forward(request.get_404_route())
   170         end
   171       end
   173       if not request.get_redirect_data() then
   174         request.process_forward()
   175         local view = request.get_view()
   176         if string.find(view, "^_") then
   177           error("Tried to call a private view (prefixed with underscore).")
   178         end
   179         execute.filtered_view{
   180           module = request.get_module(),
   181           view   = view,
   182         }
   183       end
   185     end,
   187     function(errobj)
   188       return {
   189         errobj = errobj,
   190         stacktrace = string.gsub(
   191           debug.traceback('', 2),
   192           "^\r?\n?stack traceback:\r?\n?", ""
   193         )
   194       }
   195     end
   196   )
   198   if not success then trace.error{} end
   200   -- TODO: extend trace system to generally monitor execution time
   201   -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   203   slot.select('trace', trace.render)  -- render trace information
   205   local redirect_data = request.get_redirect_data()
   207   -- log error and switch to error layout, unless success
   208   if not success then
   209     local errobj     = error_info.errobj
   210     local stacktrace = error_info.stacktrace
   211     if not request._status then
   212       request._status = "500 Internal Server Error"
   213     end
   214     slot.set_layout('system_error')
   215     slot.select('system_error', function()
   216       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   217         slot.put(
   218           "<p>Database error of class <b>",
   219           encode.html(errobj.code),
   220           "</b> occured:<br/><b>",
   221           encode.html(errobj.message),
   222           "</b></p>"
   223         )
   224       else
   225         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   226       end
   227       slot.put("<p>Stack trace follows:<br/>")
   228       slot.put(encode.html_newlines(encode.html(stacktrace)))
   229       slot.put("</p>")
   230     end)
   231   elseif redirect_data then
   232     redirect_data = table.new(redirect_data)
   233     redirect_data.params = table.new(redirect_data.params)
   234     local slot_dump = slot.dump_all()
   235     if slot_dump ~= "" then
   236       redirect_data.params.tempstore = tempstore.save(slot_dump)
   237     end
   238     http_request:send_status("303 See Other")
   239     for i, header in ipairs(request._response_headers) do
   240       http_request:send_header(header[1], header[2])
   241     end
   242     http_request:send_header("Location", encode.url(redirect_data))
   243     http_request:finish()
   244   end
   246   if not success or not redirect_data then
   248     http_request:send_status(request._status or "200 OK")
   249     for i, header in ipairs(request._response_headers) do
   250       http_request:send_header(header[1], header[2])
   251     end
   252     if not request._cache_manual then
   253       local cache_time = request._cache_time
   254       if request._cache and cache_time and cache_time > 0 then
   255         http_request:send_header("Cache-Control", "max-age=" .. cache_time)
   256       else
   257         http_request:send_header("Cache-Control", "no-cache")
   258       end
   259     end
   260     http_request:send_header("Content-Type", slot.get_content_type())
   261     http_request:send_data(slot.render_layout())
   262     http_request:finish()
   263   end
   265 end
   267 --//--
   269 --[[--
   270 app  -- table to store an application state
   272 'app' is a global table for storing any application state data. It will be reset for every request.
   273 --]]--
   275 -- Initialized in request.handler(...).
   277 --//--
