Audit the private sequence

@param nextPublicSequnceNumber
972846
private void auditPrivateSequence(final long nextPrivateSequnceNumber) {
		if(privateSequence == -1) {
			privateSequence = nextPrivateSequnceNumber;
			return;
		}
		
		if(privateSequence + 1 != nextPrivateSequnceNumber) {
			final String errorMessage = String.format(
					"Got %d as next private sequence number, expected %d", 
					privateSequence + 1, nextPrivateSequnceNumber);
			
			handleError(errorMessage);
			return;
		}
		
		privateSequence++;
	}
776038
@Override
	public T visitPSeq(PSeqContext ctx) {
//		on(ctx);
		appendAst(ctx, tok(PARAM_SEQUENCE));
		return super.visitPSeq(ctx);
	}
608561
public FastqBuilder withSequence(final String sequence)
	{
		if (sequence == null)
		{
			throw new IllegalArgumentException("sequence must not be null");
		}
		if (this.sequence == null)
		{
			this.sequence = new StringBuilder(sequence.length());
		}
		this.sequence.replace(0, this.sequence.length(), sequence);
		return this;
	}
630084
private void sequenceQuery(
      long index,
      long sequence,
      long timestamp,
      RaftSession session,
      PrimitiveOperation operation,
      CompletableFuture<OperationResult> future) {
    // If the query's sequence number is greater than the session's current sequence number, queue the request for
    // handling once the state machine is caught up.
    long commandSequence = session.getCommandSequence();
    if (sequence > commandSequence) {
      log.trace("Registering query with sequence number " + sequence + " > " + commandSequence);
      session.registerSequenceQuery(sequence, () -> indexQuery(index, timestamp, session, operation, future));
    } else {
      indexQuery(index, timestamp, session, operation, future);
    }
  }
786656
private <T> Sequence<T> run(
      final QueryPlus<T> queryPlus,
      final Map<String, Object> responseContext,
      final UnaryOperator<TimelineLookup<String, ServerSelector>> timelineConverter
  )
  {
    return new SpecificQueryRunnable<>(queryPlus, responseContext).run(timelineConverter);
  }
524419
private CompletableFuture<QueryResponse> sequenceAndApply(QueryEntry entry) {
    // Get the client's server session. If the session doesn't exist, return an unknown session error.
    ServerSessionContext session = context.getStateMachine().executor().context().sessions().getSession(entry.getSession());
    if (session == null) {
      return CompletableFuture.completedFuture(logResponse(QueryResponse.builder()
        .withStatus(Response.Status.ERROR)
        .withError(CopycatError.Type.UNKNOWN_SESSION_ERROR)
        .build()));
    }

    CompletableFuture<QueryResponse> future = new CompletableFuture<>();

    // If the query's sequence number is less than the session's current request sequence number but greater than the
    // session's current applied sequence number, queue the request for handling once the state machine is caught up.
    if (entry.getSequence() > session.getCommandSequence()) {
      session.registerSequenceQuery(entry.getSequence(), () -> applyQuery(entry, future));
    }
    // If the query is already in sequence then just apply it.
    else {
      applyQuery(entry, future);
    }
    return future;
  }
1129779
public synchronized long getCheckpointedSequence() {
		long sequence = lastSequence;
		if(!sequences.isEmpty()) {
			sequence = sequences.first() - 1;
		}
		
		if(sequence > firstValueSequence) {
			// Garbage-collect inaccessible values:
			int numToRemove = (int)(sequence - firstValueSequence);
			for(int i = 0; i < numToRemove; i++) {
				values.remove(0);
			}
			firstValueSequence += numToRemove;
		}
		
		return sequence;
	}
646025
private synchronized long nextId(boolean isPadding, long busId) {

        long timestamp = timeGen();
        long paddingnum = regionId;

        if (isPadding) {
            paddingnum = busId;
        }

        if (timestamp < lastTimestamp) {
            try {
                throw new Exception("Clock moved backwards.  Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //如果上次生成时间和当前时间相同,在同一毫秒内
        if (lastTimestamp == timestamp) {
            //sequence自增，因为sequence只有10bit，所以和sequenceMask相与一下，去掉高位
            sequence = (sequence + 1) & sequenceMask;
            //判断是否溢出,也就是每毫秒内超过1024，当为1024时，与sequenceMask相与，sequence就等于0
            if (sequence == 0) {
                //自旋等待到下一毫秒
                timestamp = tailNextMillis(lastTimestamp);
            }
        } else {
            // 如果和上次生成时间不同,重置sequence，就是下一毫秒开始，sequence计数重新从0开始累加,
            // 为了保证尾数随机性更大一些,最后一位设置一个随机数
            sequence = new SecureRandom().nextInt(10);
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) | (paddingnum << regionIdShift) | (workerId << workerIdShift) | sequence;
    }
1209015
@Override
    public SequenceRecord nextSequence() {
        SequenceRecord next = sequenceRecordReader.nextSequence();
        next.setSequenceRecord(transformProcess.executeSequence(next.getSequenceRecord()));
        return next;
    }
349604
private void audit(JsonSimple response, String oid, String message) {
		JsonObject order = newSubscription(response, oid);
		JsonObject messageObject = (JsonObject) order.get("message");
		messageObject.put("eventType", message);
	}
782162
public void setMaxSequenceNumber(int maxSequenceNumber) throws Exception {
        if (this.isStarted)
            throw new Exception("MaxSequenceNumber parameter can be updated only when M3UA stack is NOT running");

        if (maxSequenceNumber < 1) {
            maxSequenceNumber = 1;
        } else if (maxSequenceNumber > MAX_SEQUENCE_NUMBER) {
            maxSequenceNumber = MAX_SEQUENCE_NUMBER;
        }
        this.maxSequenceNumber = maxSequenceNumber;
    }
5170
public static void addSeqRes(Chain modelChain, String sequence) {
		List<Group> seqResGroups = modelChain.getSeqResGroups();
		GroupType chainType = getChainType(modelChain.getAtomGroups());
		for(int i=0; i<sequence.length(); i++){
			char singleLetterCode = sequence.charAt(i);
			Group group = null;
			if(seqResGroups.size()<=i){
			}
			else{
				group=seqResGroups.get(i);
			}
			if(group!=null){
				continue;
			}
			group = getSeqResGroup(modelChain, singleLetterCode, chainType);
			addGroupAtId(seqResGroups, group, i);
			seqResGroups.set(i, group);
		}
	}
423892
protected String getShardIterator(SequenceNumber sequenceNumber) throws Exception {

		if (isSentinelSequenceNumber(sequenceNumber)) {
			return getShardIteratorForSentinel(sequenceNumber);
		} else {
			// we will be starting from an actual sequence number (due to restore from failure).
			return getShardIteratorForRealSequenceNumber(sequenceNumber);
		}
	}
121467
@Override
	public Long nextValue(NextValueRequest request) {
		String sequenceName = sequenceName( request.getKey() );
		// This method return 2 statements: the first one to acquire a lock and the second one to update the sequence node
		RemoteStatements remoteStatements = updateNextValueQuery( request );

		Number nextValue = nextValue( remoteStatements );

		// sequence nodes are expected to have been created up-front
		if ( request.getKey().getMetadata().getType() == IdSourceType.SEQUENCE ) {
			if ( nextValue == null ) {
				throw logger.sequenceNotFound( sequenceName );
			}
		}
		// The only way I found to make it work in a multi-threaded environment is to first increment the value and then read it.
		// Our API allows for an initial value and to make sure that I'm actually reading the correct one,
		// the first time I need to decrement the value I obtain from the db.
		return nextValue.longValue() - request.getIncrement();
	}
1103294
void logSequences() {

        OrderedHashSet set = sessionData.sequenceUpdateSet;

        if (set == null || set.isEmpty()) {
            return;
        }

        for (int i = 0, size = set.size(); i < size; i++) {
            NumberSequence sequence = (NumberSequence) set.get(i);

            database.logger.writeSequenceStatement(this, sequence);
        }

        sessionData.sequenceUpdateSet.clear();
    }
463953
public OutSegment openWriterSeq(long sequence)
  {
    int segmentSize = _segmentSizeNew;

    SegmentKelp segment = _segmentService.createSegment(segmentSize, getTableKey(), sequence);

    addTableSegmentLength(segmentSize);
    
    _activeSequenceSet.put(sequence, Boolean.TRUE);
    
    return new OutSegment(_table, _table.getTableService(), this, segment);
  }
738622
public boolean checkInputMessageNumbering(SccpConnectionImpl conn, SequenceNumber sendSequenceNumber,
                                              SequenceNumber receiveSequenceNumber) throws Exception {
        if (sendSequenceNumber != null) {
            if (expectingFirstMessageInputAfterInit && !sendSequenceNumber.equals(new SequenceNumberImpl(0))) {
                // local procedure error
                conn.reset(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
                return false;

            } else if (sendSequenceNumber.equals(sendSequenceNumberExpectedAtInput) && inputWindow.contains(sendSequenceNumber)) {
                sendSequenceNumberExpectedAtInput = sendSequenceNumberExpectedAtInput.nextNumber();

            } else {
                if (!inputWindow.contains(sendSequenceNumber)) {
                    conn.reset(new ResetCauseImpl(ResetCauseValue.REMOTE_PROCEDURE_ERROR_MESSAGE_OUT_OF_WINDOW));

                } else if (!sendSequenceNumber.equals(sendSequenceNumberExpectedAtInput)) {
                    // local procedure error
                    conn.resetSection(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
                }
                return false;
            }
        }

        if (rangeContains(lastReceiveSequenceNumberReceived, this.sendSequenceNumber.nextNumber(), receiveSequenceNumber)) {
            outputWindow.setLowerEdge(receiveSequenceNumber);
        } else {
            conn.resetSection(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
            return false;
        }

        lastReceiveSequenceNumberReceived = receiveSequenceNumber;
        expectingFirstMessageInputAfterInit = false;
        return true;
    }