001/*
002 * (C) Copyright 2017 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bdelbosc
018 */
019package org.nuxeo.ecm.platform.importer.mqueues.pattern.consumer.internals;
020
021import org.nuxeo.ecm.platform.importer.mqueues.pattern.consumer.BatchPolicy;
022
023/**
024 * Keep state of a batch according to a batch policy.
025 *
026 * @since 9.1
027 */
028public class BatchState {
029    private final BatchPolicy policy;
030    private int counter;
031    private long endMs;
032
033    public enum State {FILLING, FULL, TIMEOUT, LAST}
034
035    State state = State.FILLING;
036
037    public BatchState(BatchPolicy policy) {
038        this.policy = policy;
039    }
040
041    public void start() {
042        endMs = System.currentTimeMillis() + policy.getTimeThreshold().toMillis();
043        counter = 0;
044        state = State.FILLING;
045    }
046
047    public State inc() {
048        if (state != State.FILLING) {
049            throw new IllegalStateException("Try to add an item to a batch in non filling state:" + state);
050        }
051        counter++;
052        return getState();
053    }
054
055    public void force() {
056        state = State.FULL;
057    }
058
059    public void last() {
060        state = State.LAST;
061    }
062
063    public State getState() {
064        if (state != State.FILLING) {
065            return state;
066        }
067        if (counter >= policy.getCapacity()) {
068            state = State.FULL;
069        } else if (System.currentTimeMillis() > endMs) {
070            state = State.TIMEOUT;
071        }
072        return state;
073    }
074
075    public int getSize() {
076        return counter;
077    }
078
079}