local exit = require "sm.utils.exit" local config_fetcher = require "sm.utils.config_fetcher" local string_utils = require "sm.utils.string_utils" local cjson = require "cjson" local _M = {} function _M.resolve(redis, host) local remote_addr = ngx.var.remote_addr local request_id = ngx.var.request_id if ngx.ctx.hostname and ngx.ctx.zone_id then return ngx.ctx.hostname, ngx.ctx.zone_id, nil end local hostname, _, err = config_fetcher.hostname(redis, host) if not hostname then if string_utils.is_root_domain(host) then ngx.log(ngx.ERR, "hostname not found: " .. host) return nil, nil, exit.config(remote_addr, request_id) end local root_domain = string_utils.get_root_domain(host) hostname, _, err = config_fetcher.hostname(redis, "*." .. root_domain) if not hostname then ngx.log(ngx.ERR, "hostname not found: " .. host) return nil, nil, exit.config(remote_addr, request_id) end end local zone_id = hostname["key"] local site_json = cjson.encode(hostname) ngx.ctx.hostname = hostname ngx.ctx.zone_id = zone_id ngx.var.site = site_json ngx.var.zone_id = zone_id return hostname, zone_id, nil end function _M.restore_from_vars() if ngx.ctx.hostname and ngx.ctx.zone_id then return ngx.ctx.hostname, ngx.ctx.zone_id, nil end local site_json = ngx.var.site local zone_id = ngx.var.zone_id if not site_json or site_json == "" or not zone_id or zone_id == "" then return nil, nil, nil end local ok, hostname = pcall(cjson.decode, site_json) if not ok or not hostname then return nil, nil, nil end ngx.ctx.hostname = hostname ngx.ctx.zone_id = zone_id return hostname, zone_id, nil end return _M