# Proxy nginx configuration.

upstream backend_drain {
    server localhost:<%= @data["proxy"]["drain_port"] %> max_fails=3;
}

server {
    server_name localhost;
    listen <%= @data["proxy"]["port"] %>;
    # Reference https://devcenter.heroku.com/articles/private-space-logging#requests
    # > the maximum Private Space Logging request could be as large as 5000 KB
    # Add a little for good measure.
    client_body_buffer_size 6m;
    client_max_body_size 6m;

    location / {
        mirror /mirror;

        proxy_connect_timeout 12s;
        proxy_read_timeout 6s;
        proxy_next_upstream_tries 3;

        proxy_pass http://backend_drain;

        # Inform clients that we want them to re-open connections.
        # Otherwise, the Heroku router likes to keep very long-running sessions.
        # Note that this requires an internal Heroku feature flag at the time of writing:
        #   spaces-forward-connection-close
        # If the flag is not set, the Heroku router will *not* forward this header to clients.
        add_header Connection close always;
    }

    # Expect mirror location as query argument.
    location = /mirror {
        internal;
        resolver <%= @data["proxy"]["mirror_resolver"] %>;
        if ($arg_mirror = "") {
            return 200;
        }
        # Default to HTTPS.
        # HTTP is useful for local testing and must be explicitly set.
        set $mirror_scheme "https";
        if ($arg_mirror_scheme != "") {
            set $mirror_scheme $arg_mirror_scheme;
        }

        proxy_set_header Authorization "";

        proxy_pass $mirror_scheme://$arg_mirror;
    }
}