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