diff --git a/gateway/src/apicast/proxy.lua b/gateway/src/apicast/proxy.lua index 0c86fa1be..24272c419 100644 --- a/gateway/src/apicast/proxy.lua +++ b/gateway/src/apicast/proxy.lua @@ -21,6 +21,7 @@ local concat = table.concat local gsub = string.gsub local tonumber = tonumber local setmetatable = setmetatable +local ipairs = ipairs local encode_args = ngx.encode_args local resty_resolver = require 'resty.resolver' local semaphore = require('ngx.semaphore') @@ -126,6 +127,31 @@ local function output_debug_headers(service, usage, credentials) end end +-- Converts a usage to the format expected by the 3scale backend client. +local function parse_usage(usage) + local parsed_usage = {} + + local usage_metrics = usage.metrics + local usage_deltas = usage.deltas + + for _, metric in ipairs(usage_metrics) do + local delta = usage_deltas[metric] + parsed_usage['usage[' .. metric .. ']'] = delta + end + + return parsed_usage +end + +local function matched_patterns(matched_rules) + local patterns = {} + + for _, rule in ipairs(matched_rules) do + insert(patterns, rule.pattern) + end + + return patterns +end + function _M:authorize(service, usage, credentials, ttl) if not usage or not credentials then return nil, 'missing usage or credentials' end @@ -243,7 +269,7 @@ function _M:rewrite(service) return error_no_credentials(service) end - local _, matched_patterns, usage_params = service:get_usage(ngx.req.get_method(), ngx.var.uri) + local usage, matched_rules = service:get_usage(ngx.req.get_method(), ngx.var.uri) local cached_key = { service.id } -- remove integer keys for serialization @@ -263,16 +289,22 @@ function _M:rewrite(service) local ctx = ngx.ctx local var = ngx.var + local parsed_usage = parse_usage(usage) + -- save those tables in context so they can be used in the backend client - ctx.usage = usage_params + ctx.usage = parsed_usage ctx.credentials = credentials - ctx.matched_patterns = matched_patterns self.credentials = credentials - self.usage = usage_params + self.usage = parsed_usage var.cached_key = concat(cached_key, ':') + if debug_header_enabled then + local patterns = matched_patterns(matched_rules) + ctx.matched_patterns = concat(patterns, ', ') + end + local ttl if self.oauth then