webmcp

diff framework/env/request/handler.lua @ 255:9e4be058959d

New functions request.add_initializer(...) and request.add_variable(...) to allow per-request initialization; Merged request.process() with request.handler(...)
author jbe
date Sat Mar 14 23:39:47 2015 +0100 (2015-03-14)
parents 3db6f3ad0703
children 46f0083889a9
line diff
     1.1 --- a/framework/env/request/handler.lua	Mon Mar 02 01:15:34 2015 +0100
     1.2 +++ b/framework/env/request/handler.lua	Sat Mar 14 23:39:47 2015 +0100
     1.3 @@ -3,11 +3,30 @@
     1.4    request         -- HTTP request object
     1.5  )
     1.6  
     1.7 -Called by mcp.lua to process an HTTP request. Performs some initializations, then calls request.router().
     1.8 +Called by mcp.lua to process an HTTP request. Performs some initializations, calls request.router(), and handles the request.
     1.9  
    1.10  --]]--
    1.11  
    1.12 +local function file_exists(filename)
    1.13 +  local file = io.open(filename, "r")
    1.14 +  if file then
    1.15 +    io.close(file)
    1.16 +    return true
    1.17 +  else
    1.18 +    return false
    1.19 +  end
    1.20 +end
    1.21 +
    1.22 +-- TODO: function incomplete yet
    1.23  function request.handler(http_request)
    1.24 +  do
    1.25 +    local first = not request._in_progress
    1.26 +    request._in_progress = true  -- NOTE: must be set to true before initializer functions are called
    1.27 +    for i, func in ipairs(request._initializers) do
    1.28 +      func(first)
    1.29 +    end
    1.30 +  end
    1.31 +
    1.32    request._http_request = http_request
    1.33    local path = http_request.path
    1.34    if path then
    1.35 @@ -20,7 +39,210 @@
    1.36      request._relative_baseurl = nil
    1.37    end
    1.38    request._route = request.router() or {}
    1.39 -  request.process()
    1.40 +
    1.41 +  local success, error_info = xpcall(
    1.42 +    function()
    1.43 +
    1.44 +      if request._route.static then
    1.45 +        local f = assert(io.open(WEBMCP_BASE_PATH .. "static/" .. request._route.static, "r"))
    1.46 +        local d = f:read("*a")
    1.47 +        f:close()
    1.48 +        slot.put_into("data", d)
    1.49 +        slot.set_layout(nil, "application/octet-stream")  -- TODO
    1.50 +        return
    1.51 +      end
    1.52 +
    1.53 +      -- restore slots if coming from http redirect
    1.54 +      local tempstore_value = http_request.get_params["_tempstore"]
    1.55 +      if tempstore_value then
    1.56 +        trace.restore_slots{}
    1.57 +        local blob = tempstore.pop(tempstore_value)
    1.58 +        if blob then slot.restore_all(blob) end
    1.59 +      end
    1.60 +
    1.61 +      if request.get_action() then
    1.62 +        trace.request{
    1.63 +          module = request.get_module(),
    1.64 +          action = request.get_action()
    1.65 +        }
    1.66 +        if
    1.67 +          request.get_404_route() and
    1.68 +          not file_exists(
    1.69 +            encode.action_file_path{
    1.70 +              module = request.get_module(),
    1.71 +              action = request.get_action()
    1.72 +            }
    1.73 +          )
    1.74 +        then
    1.75 +          request.set_status("404 Not Found")
    1.76 +          request.forward(request.get_404_route())
    1.77 +        else
    1.78 +          if http_request.method ~= "POST" then
    1.79 +            request.set_status("405 Method Not Allowed")
    1.80 +            request.add_header("Allow", "POST")
    1.81 +            error("Tried to invoke an action with a GET request.")
    1.82 +          end
    1.83 +          local action_status = execute.filtered_action{
    1.84 +            module = request.get_module(),
    1.85 +            action = request.get_action(),
    1.86 +          }
    1.87 +          if not request.is_rerouted() then
    1.88 +            local routing_mode, routing_module, routing_view, routing_anchor
    1.89 +            routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
    1.90 +            routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
    1.91 +            routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
    1.92 +            routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
    1.93 +            if not (routing_mode or routing_module or routing_view) then
    1.94 +              action_status = "default"
    1.95 +              routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
    1.96 +              routing_module = http_request.post_params["_webmcp_routing.default.module"]
    1.97 +              routing_view   = http_request.post_params["_webmcp_routing.default.view"]
    1.98 +              routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
    1.99 +            end
   1.100 +            assert(routing_module, "Routing information has no module.")
   1.101 +            assert(routing_view,   "Routing information has no view.")
   1.102 +            if routing_mode == "redirect" then
   1.103 +              local routing_params = {}
   1.104 +              for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   1.105 +                local status, stripped_key = string.match(
   1.106 +                  key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   1.107 +                )
   1.108 +                if status == action_status then
   1.109 +                  routing_params[stripped_key] = value
   1.110 +                end
   1.111 +              end
   1.112 +              request.redirect{
   1.113 +                module = routing_module,
   1.114 +                view   = routing_view,
   1.115 +                id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   1.116 +                params = routing_params,
   1.117 +                anchor = routing_anchor
   1.118 +              }
   1.119 +            elseif routing_mode == "forward" then
   1.120 +              request.forward{ module = routing_module, view = routing_view }
   1.121 +            else
   1.122 +              error("Missing or unknown routing mode in request parameters.")
   1.123 +            end
   1.124 +          end
   1.125 +        end
   1.126 +      else
   1.127 +        -- no action
   1.128 +        trace.request{
   1.129 +          module = request.get_module(),
   1.130 +          view   = request.get_view()
   1.131 +        }
   1.132 +        if
   1.133 +          request.get_404_route() and
   1.134 +          not file_exists(
   1.135 +            encode.view_file_path{
   1.136 +              module = request.get_module(),
   1.137 +              view   = request.get_view()
   1.138 +            }
   1.139 +          )
   1.140 +        then
   1.141 +          request.set_status("404 Not Found")
   1.142 +          request.forward(request.get_404_route())
   1.143 +        end
   1.144 +      end
   1.145 +
   1.146 +      if not request.get_redirect_data() then
   1.147 +        request.process_forward()
   1.148 +        local view = request.get_view()
   1.149 +        if string.find(view, "^_") then
   1.150 +          error("Tried to call a private view (prefixed with underscore).")
   1.151 +        end
   1.152 +        execute.filtered_view{
   1.153 +          module = request.get_module(),
   1.154 +          view   = view,
   1.155 +        }
   1.156 +      end
   1.157 +
   1.158 +      -- force error due to missing absolute base URL until its too late to display error message
   1.159 +      --if request.get_redirect_data() then
   1.160 +      --  request.get_absolute_baseurl()
   1.161 +      --end
   1.162 +
   1.163 +    end,
   1.164 +
   1.165 +    function(errobj)
   1.166 +      return {
   1.167 +        errobj = errobj,
   1.168 +        stacktrace = string.gsub(
   1.169 +          debug.traceback('', 2),
   1.170 +          "^\r?\n?stack traceback:\r?\n?", ""
   1.171 +        )
   1.172 +      }
   1.173 +    end
   1.174 +  )
   1.175 +
   1.176 +  if not success then trace.error{} end
   1.177 +
   1.178 +  -- TODO: extend trace system to generally monitor execution time
   1.179 +  -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   1.180 +
   1.181 +  slot.select('trace', trace.render)  -- render trace information
   1.182 +
   1.183 +  local redirect_data = request.get_redirect_data()
   1.184 +
   1.185 +  -- log error and switch to error layout, unless success
   1.186 +  if not success then
   1.187 +    local errobj     = error_info.errobj
   1.188 +    local stacktrace = error_info.stacktrace
   1.189 +    if not request._status then
   1.190 +      request._status = "500 Internal Server Error"
   1.191 +    end
   1.192 +    slot.set_layout('system_error')
   1.193 +    slot.select('system_error', function()
   1.194 +      if getmetatable(errobj) == mondelefant.errorobject_metatable then
   1.195 +        slot.put(
   1.196 +          "<p>Database error of class <b>",
   1.197 +          encode.html(errobj.code),
   1.198 +          "</b> occured:<br/><b>",
   1.199 +          encode.html(errobj.message),
   1.200 +          "</b></p>"
   1.201 +        )
   1.202 +      else
   1.203 +        slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   1.204 +      end
   1.205 +      slot.put("<p>Stack trace follows:<br/>")
   1.206 +      slot.put(encode.html_newlines(encode.html(stacktrace)))
   1.207 +      slot.put("</p>")
   1.208 +    end)
   1.209 +  elseif redirect_data then
   1.210 +    local redirect_params = {}
   1.211 +    for key, value in pairs(redirect_data.params) do
   1.212 +      redirect_params[key] = value
   1.213 +    end
   1.214 +    local slot_dump = slot.dump_all()
   1.215 +    if slot_dump ~= "" then
   1.216 +      redirect_params.tempstore = tempstore.save(slot_dump)
   1.217 +    end
   1.218 +    http_request:send_status("303 See Other")
   1.219 +    http_request:send_header("Connection", "close")  -- TODO: extend moonbridge
   1.220 +    http_request:send_header(
   1.221 +      "Location",
   1.222 +      encode.url{
   1.223 +        base   = request.get_absolute_baseurl(),
   1.224 +        module = redirect_data.module,
   1.225 +        view   = redirect_data.view,
   1.226 +        id     = redirect_data.id,
   1.227 +        params = redirect_params,
   1.228 +        anchor = redirect_data.anchor
   1.229 +      }
   1.230 +    )
   1.231 +    http_request:finish()
   1.232 +  end
   1.233 +
   1.234 +  if not success or not redirect_data then
   1.235 +
   1.236 +    http_request:send_status(request._status or "200 OK")
   1.237 +    http_request:send_header("Connection", "close")  -- TODO: extend moonbridge
   1.238 +    for i, header in ipairs(request._response_headers) do
   1.239 +      http_request:send_header(header[1], header[2])
   1.240 +    end
   1.241 +    http_request:send_header("Content-Type", slot.get_content_type())
   1.242 +    http_request:send_data(slot.render_layout())
   1.243 +    http_request:finish()
   1.244 +  end
   1.245 +
   1.246  end
   1.247 -
   1.248 ---//--

Impressum / About Us