'Ratelimit users and add ratelimit headers to the response.
Headers added are:
X-Ratelimit-Used: Number of requests used in this period
X-Ratelimit-Remaining: Number of requests left to use
X-Ratelimit-Reset: Approximate number of seconds to end of period
This function only has an effect if one of
g.RL_SITEWIDE_ENABLED or g.RL_OAUTH_SITEWIDE_ENABLED
are set to \'true\' in the app configuration
If the ratelimit is exceeded, a 429 response will be sent,
unless the app configuration has g.ENFORCE_RATELIMIT off.
Headers will be sent even on aborted requests.'

def run_sitewide_ratelimits(self):

    if c.error_page:
        return
    if (c.oauth_user and g.RL_OAUTH_SITEWIDE_ENABLED):
        type_ = 'oauth'
        period = g.RL_OAUTH_RESET_SECONDS
        max_reqs = c.oauth2_client._max_reqs
        client_id = c.oauth2_access_token.client_id.encode('ascii')
        key = ((('siterl-oauth-' + c.user._id36) + ':') + client_id)
    elif c.cdn_cacheable:
        type_ = 'cdn'
    elif (not is_api()):
        type_ = 'web'
    elif g.RL_SITEWIDE_ENABLED:
        type_ = 'api'
        max_reqs = g.RL_MAX_REQS
        period = g.RL_RESET_SECONDS
        key = ('siterl-api-' + request.ip)
    else:
        type_ = 'none'
    g.stats.event_count('ratelimit.type', type_, sample_rate=0.01)
    if (type_ in ('cdn', 'web', 'none')):
        return
    time_slice = ratelimit.get_timeslice(period)
    try:
        recent_reqs = ratelimit.record_usage(key, time_slice)
    except ratelimit.RatelimitError as e:
        g.log.info('ratelimit    error:    %s', e)
        return
    reqs_remaining = max(0, (max_reqs - recent_reqs))
    c.ratelimit_headers = {'X-Ratelimit-Used': str(recent_reqs), 'X-Ratelimit-Reset': str(time_slice.remaining), 'X-Ratelimit-Remaining': str(reqs_remaining)}
    event_type = None
    if (reqs_remaining <= 0):
        if (recent_reqs > (2 * max_reqs)):
            event_type = 'hyperbolic'
        else:
            event_type = 'over'
        if g.ENFORCE_RATELIMIT:
            request.environ['retry_after'] = time_slice.remaining
            response.headers.update(c.ratelimit_headers)
            abort(429)
    elif (reqs_remaining < (0.1 * max_reqs)):
        event_type = 'close'
    if (event_type is not None):
        g.stats.event_count('ratelimit.exceeded', event_type)
        if (type_ == 'oauth'):
            g.stats.count_string('oauth.{}'.format(event_type), client_id)
