include /etc/nginx/conf.d/include/cors;
include /etc/nginx/conf.d/include/sia-auth;

limit_req zone=registry_access_by_ip burst=600 nodelay;
limit_req zone=registry_access_by_ip_throttled burst=200 nodelay;

proxy_set_header User-Agent: Sia-Agent;
proxy_read_timeout 600; # siad should timeout with 404 after 5 minutes
proxy_pass http://sia:9980/skynet/registry;

access_by_lua_block {
    if require("skynet.account").accounts_enabled() then
        -- check if portal is in authenticated only mode
        if require("skynet.account").is_access_unauthorized() then
            return require("skynet.account").exit_access_unauthorized()
        end

        -- check if portal is in subscription only mode
        if require("skynet.account").is_access_forbidden() then
            return require("skynet.account").exit_access_forbidden()
        end

        -- get account limits of currently authenticated user
        local limits = require("skynet.account").get_account_limits()
        
        -- apply registry rate limits (forced delay)
        if limits.registry > 0 then
            ngx.sleep(limits.registry / 1000)
        end
    end
}

log_by_lua_block {
    local skynet_account = require("skynet.account")
    local skynet_tracker = require("skynet.tracker")

    skynet_tracker.track_registry(ngx.status, skynet_account.get_auth_headers(), ngx.req.get_method())
}