Leases a number of message handler requests up to the indicated limit.
333874
def _LeaseMessageHandlerRequests(self, lease_time, limit, cursor=None):
    """"""

    now = rdfvalue.RDFDatetime.Now()
    now_str = mysql_utils.RDFDatetimeToTimestamp(now)

    expiry = now + lease_time
    expiry_str = mysql_utils.RDFDatetimeToTimestamp(expiry)

    query = ("UPDATE message_handler_requests "
             "SET leased_until=FROM_UNIXTIME(%s), leased_by=%s "
             "WHERE leased_until IS NULL OR leased_until < FROM_UNIXTIME(%s) "
             "LIMIT %s")

    id_str = utils.ProcessIdString()
    args = (expiry_str, id_str, now_str, limit)
    updated = cursor.execute(query, args)

    if updated == 0:
      return []

    cursor.execute(
        "SELECT UNIX_TIMESTAMP(timestamp), request "
        "FROM message_handler_requests "
        "WHERE leased_by=%s AND leased_until=FROM_UNIXTIME(%s) LIMIT %s",
        (id_str, expiry_str, updated))
    res = []
    for timestamp, request in cursor.fetchall():
      req = rdf_objects.MessageHandlerRequest.FromSerializedString(request)
      req.timestamp = mysql_utils.TimestampToRDFDatetime(timestamp)
      req.leased_until = expiry
      req.leased_by = id_str
      res.append(req)

    return res
654949
def rate_limit(self, rate_limit):
        
        self._rate_limit = bool(rate_limit)
        self._rate_limit_last_call = None
        self.clear_memoized()
489039
def ReadMessageHandlerRequests(self, cursor=None):
    """"""

    query = ("SELECT UNIX_TIMESTAMP(timestamp), request,"
             "       UNIX_TIMESTAMP(leased_until), leased_by "
             "FROM message_handler_requests "
             "ORDER BY timestamp DESC")

    cursor.execute(query)

    res = []
    for timestamp, request, leased_until, leased_by in cursor.fetchall():
      req = rdf_objects.MessageHandlerRequest.FromSerializedString(request)
      req.timestamp = mysql_utils.TimestampToRDFDatetime(timestamp)
      req.leased_by = leased_by
      req.leased_until = mysql_utils.TimestampToRDFDatetime(leased_until)
      res.append(req)
    return res
439855
private void enforceTimeLimits()
    {
        for (T query : queries.values()) {
            if (query.isDone()) {
                continue;
            }
            Duration queryMaxRunTime = getQueryMaxRunTime(query.getSession());
            Duration queryMaxExecutionTime = getQueryMaxExecutionTime(query.getSession());
            Optional<DateTime> executionStartTime = query.getExecutionStartTime();
            DateTime createTime = query.getCreateTime();
            if (executionStartTime.isPresent() && executionStartTime.get().plus(queryMaxExecutionTime.toMillis()).isBeforeNow()) {
                query.fail(new PrestoException(EXCEEDED_TIME_LIMIT, "Query exceeded the maximum execution time limit of " + queryMaxExecutionTime));
            }
            if (createTime.plus(queryMaxRunTime.toMillis()).isBeforeNow()) {
                query.fail(new PrestoException(EXCEEDED_TIME_LIMIT, "Query exceeded maximum time limit of " + queryMaxRunTime));
            }
        }
    }
51406
def _enforce_size_limit(self, capacity):
        """"""
        while len(self._cache) > capacity:
            key, value = self._cache.popitem(last=False)
            if self._on_evict is not None:
                self._on_evict(key, value)
1291834
function setupReqCounter() {

    reqCounter = reqCounter || new ReqCounter();

    process.monitor.getRequestCount = function () {
        return reqCounter._requests;
    };

    process.monitor.getTotalRequestCount = function () {
        return reqCounter._totalRequests;
    };

    process.monitor.getTransferred = function () {
        return reqCounter._transferred;
    };

    process.monitor.getOpenConnections = function () {
        return reqCounter._connections;
    };
}
1282305
private void onLimit(StringBuilder builder) {
        if (Integer.MAX_VALUE != maxResult) {
            builder.append(CQLTranslator.LIMIT);
            builder.append(isSingleResult ? 1 : this.maxResult);
        }
    }
341668
function limit() {
  const args = Array.from(arguments);
  const onChange = get(args, isFunction, noop);
  const error = new Error('Too Many Requests');
  error.status = 429;
  const options = Object.assign({
    err: error,
    mid: 100,
    high: 500,
  }, get(args, isObject));
  debug('limit options:', options);
  const mid = parseInt(options.mid, 10);
  const high = parseInt(options.high, 10);
  if (isNaN(mid) || isNaN((high))) {
    throw new Error('mid and high must be a number');
  }
  if (mid <= 0 || high <= 0) {
    throw new Error('mid and high must gt 0');
  }
  if (mid >= high) {
    throw new Error('high must be gt mid');
  }
  let handlingReqTotal = 0;
  let status = '';
  let throwError = options.throwError;
  /* istanbul ignore else */
  if (isUndefined(throwError)) {
    throwError = true;
  }
  const pass = options.pass || noop;
  return (ctx, next) => {
    function checkStatus() {
      if (handlingReqTotal > high) {
        /* istanbul ignore else */
        if (status !== 'high') {
          status = 'high';
          onChange(status);
        }
        /* istanbul ignore else */
        if (throwError) {
          throw options.err;
        }
      } else if (handlingReqTotal > mid) {
        /* istanbul ignore else */
        if (status !== 'mid') {
          status = 'mid';
          onChange(status);
        }
      } /* istanbul ignore else */ else if (status !== 'low') {
        status = 'low';
        onChange(status);
      }
    }

    function done(err) {
      handlingReqTotal -= 1;
      checkStatus();
      if (err) {
        throw err;
      }
    }
    if (pass(ctx)) {
      return next();
    }

    handlingReqTotal += 1;
    checkStatus();
    return next().then(done, done);
  };
}
653835
def _limit_call_handler(self):
        
        # acquire a lock on our threading.Lock() object
        with self.limit_lock:
            # if we have no configured limit, exit.  the lock releases based on scope
            if self.limit_per_min <= 0:
                return

            now = time.time()
            # self.limits is a list of query times + 60 seconds.  In essence it is a list of times
            # that queries time out of the 60 second query window.

            # this check expires any limits that have passed
            self.limits = [l for l in self.limits if l > now]
            # and we tack on the current query
            self.limits.append(now + 60)

            # if we have more than our limit of queries (and remember, we call this before we actually
            # execute a query) we sleep until the oldest query on the list (element 0 because we append
            # new queries) times out.  We don't worry about cleanup because next time this routine runs
            # it will clean itself up.
            if len(self.limits) >= self.limit_per_min:
                time.sleep(self.limits[0] - now)
96871
async def serviceNodeMsgs(self, limit: int) -> int:
        
        with self.metrics.measure_time(MetricsName.SERVICE_NODE_STACK_TIME):
            n = await self.nodestack.service(limit, self.quota_control.node_quota)

        self.metrics.add_event(MetricsName.NODE_STACK_MESSAGES_PROCESSED, n)

        await self.processNodeInBox()
        return n
1200346
def handle_message(self, msg):
        
        if msg.msg_id in self.messagesAllowed:
            super(LimitedReporter, self).handle_message(msg)
185907
@Override
    protected void checkIncomingMessageLimit(long addition) throws MessageTooLargeException {
        super.addToIncomingMsgSize(addition);
        // check if we even need to bother comparing sizes against limits
        if (HttpConfigConstants.UNLIMITED == getHttpConfig().getMessageSizeLimit()) {
            return;
        }
        if (queryIncomingMsgSize() > getHttpConfig().getMessageSizeLimit()) {
            // over channel limit, see if the factory has a system wide "large" limit
            HttpInboundChannelFactory factory = this.myLink.getChannel().getFactory();
            if (factory.getConfig().areMessagesLimited() && factory.allowLargeMessage(queryIncomingMsgSize())) {
                this.bContainsLargeMessage = true;
            } else {
                throw new MessageTooLargeException("Size=" + queryIncomingMsgSize());
            }
        }
    }
825307
protected void throttleUpdated ()
    {
        int messagesPerSec;
        synchronized(_pendingThrottles) {
            if (_pendingThrottles.size() == 0) {
                log.warning("Received throttleUpdated but have no pending throttles",
                            "client", this);
                return;
            }
            messagesPerSec = _pendingThrottles.remove(0);
        }

        // log.info("Applying updated throttle", "client", this, "msgsPerSec", messagesPerSec);
        // We set our hard throttle over a 10 second period instead of a 1 second period to
        // account for periods of network congestion that might cause otherwise properly
        // throttled messages to bunch up while they're "on the wire"; we also add a one
        // message buffer so that if the client is right up against the limit, we don't end
        // up quibbling over a couple of milliseconds
        _throttle.reinit(10*messagesPerSec+1, 10*1000L);
    }
460489
def limit(num)
      relation = __new_relation__(all.take(num))
      relation.send(:set_from_limit)
      relation
    end
192115
def limit(value = nil, &block)
      chain { criteria.update_request_options size: block || Integer(value) }
    end
474053
function(newData, limit) {
            if ((this.buffer.length + newData.length) > options.limit) {
                this.buffer = this.buffer.concat(newData.slice(0, options.limit - this.buffer.length));
                self._sendDisplayLimitReachedMessage(limit);
            }
            else {
                this.buffer = this.buffer.concat(newData);
            }
        }
1131750
def __buildLimit(self, query ,limitResMax):
        """"""
        limit = query._getParameters()['limit']
        if limitResMax>0 and limitResMax < limit:
            query = UpdateParameter(query, 'limit', limitResMax)
            query = UpdateParameter(query, 'nocount', 'true')        
        elif  limitResMax>0 and  limitResMax >= limit:
            query = UpdateParameter(query, 'nocount', 'true')
        return query