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.mqueues;
020
021import java.io.Externalizable;
022import java.time.Duration;
023import java.util.Objects;
024
025/**
026 * An appender is used to append message into a MQueue.
027 * Implementations must be thread safe.
028 *
029 * @since 9.2
030 */
031public interface MQAppender<M extends Externalizable> extends AutoCloseable {
032
033    /**
034     * Returns the MQueue's name.
035     */
036    String name();
037
038    /**
039     * Returns the number of partitions.
040     */
041    int size();
042
043    /**
044     * Append a message into a partition, returns {@link MQOffset} position of the message.
045     *
046     * This method is thread safe, a queue can be shared by multiple producers.
047     *
048     * @param partition index lower than {@link #size()}
049     */
050    MQOffset append(int partition, M message);
051
052    /**
053     * Same as {@link #append(int, Externalizable)}, the queue is chosen using a hash of {@param key}.
054     */
055    default MQOffset append(String key, M message) {
056        Objects.requireNonNull(key);
057        // Provide a basic partitioning that works because:
058        // 1. String.hashCode is known to be constant even with different JVM (this is not the case for all objects)
059        // 2. the modulo operator is not optimal when rebalancing on partitions resizing but this should not happen.
060        // and yes hashCode can be negative.
061        int queue = (key.hashCode() & 0x7fffffff) % size();
062        return append(queue, message);
063    }
064
065    /**
066     * Wait for consumer to process a message up to the offset.
067     *
068     * The message is processed if a consumer commit its offset (or a bigger one) in the group name space.
069     *
070     * Return {@code true} if the message has been consumed, {@code false} in case of timeout.
071     */
072    boolean waitFor(MQOffset offset, String group, Duration timeout) throws InterruptedException;
073
074    /**
075     * Returns {@code true} if the close has been closed.
076     */
077    boolean closed();
078}