webmcp
view framework/env/request/handler.lua @ 258:46f0083889a9
Initialize global variable 'app' on every request
| author | jbe | 
|---|---|
| date | Sun Mar 15 01:08:00 2015 +0100 (2015-03-15) | 
| parents | 9e4be058959d | 
| children | c3d539e33710 | 
 line source
     1 --[[--
     2 request.handler(
     3   request         -- HTTP request object
     4 )
     6 Called by mcp.lua to process an HTTP request. Performs some initializations, calls request.router(), and handles the request.
     8 --]]--
    10 local function file_exists(filename)
    11   local file = io.open(filename, "r")
    12   if file then
    13     io.close(file)
    14     return true
    15   else
    16     return false
    17   end
    18 end
    20 -- TODO: function incomplete yet
    21 function request.handler(http_request)
    22   _G.app = {}  -- may be overwritten or modified by request initializers
    23   do
    24     local first = not request._in_progress
    25     request._in_progress = true  -- NOTE: must be set to true before initializer functions are called
    26     for i, func in ipairs(request._initializers) do
    27       func(first)
    28     end
    29   end
    31   request._http_request = http_request
    32   local path = http_request.path
    33   if path then
    34     local relative_baseurl_elements = {}
    35     for match in string.gmatch(path, "/") do
    36       relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
    37     end
    38     request._relative_baseurl = table.concat(relative_baseurl_elements)
    39   else
    40     request._relative_baseurl = nil
    41   end
    42   request._route = request.router() or {}
    44   local success, error_info = xpcall(
    45     function()
    47       if request._route.static then
    48         local f = assert(io.open(WEBMCP_BASE_PATH .. "static/" .. request._route.static, "r"))
    49         local d = f:read("*a")
    50         f:close()
    51         slot.put_into("data", d)
    52         slot.set_layout(nil, "application/octet-stream")  -- TODO
    53         return
    54       end
    56       -- restore slots if coming from http redirect
    57       local tempstore_value = http_request.get_params["_tempstore"]
    58       if tempstore_value then
    59         trace.restore_slots{}
    60         local blob = tempstore.pop(tempstore_value)
    61         if blob then slot.restore_all(blob) end
    62       end
    64       if request.get_action() then
    65         trace.request{
    66           module = request.get_module(),
    67           action = request.get_action()
    68         }
    69         if
    70           request.get_404_route() and
    71           not file_exists(
    72             encode.action_file_path{
    73               module = request.get_module(),
    74               action = request.get_action()
    75             }
    76           )
    77         then
    78           request.set_status("404 Not Found")
    79           request.forward(request.get_404_route())
    80         else
    81           if http_request.method ~= "POST" then
    82             request.set_status("405 Method Not Allowed")
    83             request.add_header("Allow", "POST")
    84             error("Tried to invoke an action with a GET request.")
    85           end
    86           local action_status = execute.filtered_action{
    87             module = request.get_module(),
    88             action = request.get_action(),
    89           }
    90           if not request.is_rerouted() then
    91             local routing_mode, routing_module, routing_view, routing_anchor
    92             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
    93             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
    94             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
    95             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
    96             if not (routing_mode or routing_module or routing_view) then
    97               action_status = "default"
    98               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
    99               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   100               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   101               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   102             end
   103             assert(routing_module, "Routing information has no module.")
   104             assert(routing_view,   "Routing information has no view.")
   105             if routing_mode == "redirect" then
   106               local routing_params = {}
   107               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   108                 local status, stripped_key = string.match(
   109                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   110                 )
   111                 if status == action_status then
   112                   routing_params[stripped_key] = value
   113                 end
   114               end
   115               request.redirect{
   116                 module = routing_module,
   117                 view   = routing_view,
   118                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   119                 params = routing_params,
   120                 anchor = routing_anchor
   121               }
   122             elseif routing_mode == "forward" then
   123               request.forward{ module = routing_module, view = routing_view }
   124             else
   125               error("Missing or unknown routing mode in request parameters.")
   126             end
   127           end
   128         end
   129       else
   130         -- no action
   131         trace.request{
   132           module = request.get_module(),
   133           view   = request.get_view()
   134         }
   135         if
   136           request.get_404_route() and
   137           not file_exists(
   138             encode.view_file_path{
   139               module = request.get_module(),
   140               view   = request.get_view()
   141             }
   142           )
   143         then
   144           request.set_status("404 Not Found")
   145           request.forward(request.get_404_route())
   146         end
   147       end
   149       if not request.get_redirect_data() then
   150         request.process_forward()
   151         local view = request.get_view()
   152         if string.find(view, "^_") then
   153           error("Tried to call a private view (prefixed with underscore).")
   154         end
   155         execute.filtered_view{
   156           module = request.get_module(),
   157           view   = view,
   158         }
   159       end
   161       -- force error due to missing absolute base URL until its too late to display error message
   162       --if request.get_redirect_data() then
   163       --  request.get_absolute_baseurl()
   164       --end
   166     end,
   168     function(errobj)
   169       return {
   170         errobj = errobj,
   171         stacktrace = string.gsub(
   172           debug.traceback('', 2),
   173           "^\r?\n?stack traceback:\r?\n?", ""
   174         )
   175       }
   176     end
   177   )
   179   if not success then trace.error{} end
   181   -- TODO: extend trace system to generally monitor execution time
   182   -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   184   slot.select('trace', trace.render)  -- render trace information
   186   local redirect_data = request.get_redirect_data()
   188   -- log error and switch to error layout, unless success
   189   if not success then
   190     local errobj     = error_info.errobj
   191     local stacktrace = error_info.stacktrace
   192     if not request._status then
   193       request._status = "500 Internal Server Error"
   194     end
   195     slot.set_layout('system_error')
   196     slot.select('system_error', function()
   197       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   198         slot.put(
   199           "<p>Database error of class <b>",
   200           encode.html(errobj.code),
   201           "</b> occured:<br/><b>",
   202           encode.html(errobj.message),
   203           "</b></p>"
   204         )
   205       else
   206         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   207       end
   208       slot.put("<p>Stack trace follows:<br/>")
   209       slot.put(encode.html_newlines(encode.html(stacktrace)))
   210       slot.put("</p>")
   211     end)
   212   elseif redirect_data then
   213     local redirect_params = {}
   214     for key, value in pairs(redirect_data.params) do
   215       redirect_params[key] = value
   216     end
   217     local slot_dump = slot.dump_all()
   218     if slot_dump ~= "" then
   219       redirect_params.tempstore = tempstore.save(slot_dump)
   220     end
   221     http_request:send_status("303 See Other")
   222     http_request:send_header("Connection", "close")  -- TODO: extend moonbridge
   223     http_request:send_header(
   224       "Location",
   225       encode.url{
   226         base   = request.get_absolute_baseurl(),
   227         module = redirect_data.module,
   228         view   = redirect_data.view,
   229         id     = redirect_data.id,
   230         params = redirect_params,
   231         anchor = redirect_data.anchor
   232       }
   233     )
   234     http_request:finish()
   235   end
   237   if not success or not redirect_data then
   239     http_request:send_status(request._status or "200 OK")
   240     http_request:send_header("Connection", "close")  -- TODO: extend moonbridge
   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("Content-Type", slot.get_content_type())
   245     http_request:send_data(slot.render_layout())
   246     http_request:finish()
   247   end
   249 end
   251 --//--
   253 --[[--
   254 app  -- table to store an application state
   256 'app' is a global table for storing any application state data. It will be reset for every request.
   257 --]]--
   259 -- Initialized in request.handler(...).
   261 --//--
