in kong/kong/plugins/proxy-cache/handler.lua [259:363]
function ProxyCacheHandler:access(conf)
local cc = req_cc()
if not cacheable_request(conf, cc) then
kong.response.set_header("X-Cache-Status", "Bypass")
return
end
local consumer = kong.client.get_consumer()
local route = kong.router.get_route()
local uri = ngx_re_sub(ngx.var.request, "\\?.*", "", "oj")
local cache_key = cache_key.build_cache_key(consumer and consumer.id,
route and route.id,
kong.request.get_method(),
uri,
kong.request.get_query(),
kong.request.get_headers(),
conf)
kong.response.set_header("X-Cache-Key", cache_key)
local strategy = require(STRATEGY_PATH)({
strategy_name = conf.strategy,
strategy_opts = conf[conf.strategy],
})
local ctx = kong.ctx.plugin
local res, err = strategy:fetch(cache_key)
if err == "request object not in cache" then
if conf.cache_control and cc["only-if-cached"] then
return kong.response.exit(ngx.HTTP_GATEWAY_TIMEOUT)
end
ctx.req_body = kong.request.get_raw_body()
return signal_cache_req(ctx, cache_key)
elseif err then
kong.log.err(err)
return
end
if res.version ~= CACHE_VERSION then
kong.log.notice("cache format mismatch, purging ", cache_key)
strategy:purge(cache_key)
return signal_cache_req(ctx, cache_key, "Bypass")
end
if conf.cache_control then
if cc["max-age"] and time() - res.timestamp > cc["max-age"] then
return signal_cache_req(ctx, cache_key, "Refresh")
end
if cc["max-stale"] and time() - res.timestamp - res.ttl > cc["max-stale"]
then
return signal_cache_req(ctx, cache_key, "Refresh")
end
if cc["min-fresh"] and res.ttl - (time() - res.timestamp) < cc["min-fresh"]
then
return signal_cache_req(ctx, cache_key, "Refresh")
end
else
if time() - res.timestamp > conf.cache_ttl then
return signal_cache_req(ctx, cache_key, "Refresh")
end
end
local response_data = {
res = res,
req = {
body = res.req_body,
},
server_addr = ngx.var.server_addr,
}
kong.ctx.shared.proxy_cache_hit = response_data
local nctx = ngx.ctx
nctx.KONG_PROXIED = true
for k in pairs(res.headers) do
if not overwritable_header(k) then
res.headers[k] = nil
end
end
res.headers["Age"] = floor(time() - res.timestamp)
res.headers["X-Cache-Status"] = "Hit"
return kong.response.exit(res.status, res.body, res.headers)
end