001/*
002 * (C) Copyright 2018 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.lib.stream.computation;
020
021import java.time.Duration;
022
023import net.jodah.failsafe.RetryPolicy;
024
025/**
026 * Builder to create a ComputationPolicy.
027 *
028 * @since 10.3
029 */
030public class ComputationPolicyBuilder {
031
032    protected static final int DEFAULT_BATCH_CAPACITY = 1;
033
034    protected static final int DEFAULT_BATCH_THRESHOLD_SECOND = 1;
035
036    protected RetryPolicy retryPolicy = ComputationPolicy.NO_RETRY;
037
038    protected boolean skipFailure = false;
039
040    protected int batchCapacity = DEFAULT_BATCH_CAPACITY;
041
042    protected Duration batchThreshold = Duration.ofSeconds(DEFAULT_BATCH_THRESHOLD_SECOND);
043
044    public ComputationPolicyBuilder() {
045        // Empty constructor
046    }
047
048    /**
049     * Defines how to group records by batch using a capacity and a time threshold.
050     * <p>
051     * This is used only by computation that extends AbstractBatchComputation.
052     *
053     * @param capacity the number of records in the batch
054     * @param timeThreshold process the batch even if not full after this duration
055     */
056    public ComputationPolicyBuilder batchPolicy(int capacity, Duration timeThreshold) {
057        batchCapacity = capacity;
058        batchThreshold = timeThreshold;
059        return this;
060    }
061
062    /**
063     * Defines what to do in case of failure during the batch processing.
064     */
065    public ComputationPolicyBuilder retryPolicy(RetryPolicy policy) {
066        retryPolicy = policy;
067        return this;
068    }
069
070    /**
071     * The fallback when processing a batch has failed after applying the retry policy has failed.
072     *
073     * @param value When {@code true} Skips the records affected by the batch in failure and continue.<br/>
074     *            When {@code false} aborts the computation, this is the default behavior.
075     */
076    public ComputationPolicyBuilder continueOnFailure(boolean value) {
077        skipFailure = value;
078        return this;
079    }
080
081    /**
082     * Creates the policy.
083     */
084    public ComputationPolicy build() {
085        return new ComputationPolicy(this);
086    }
087
088}