aries-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] cschneider closed pull request #15: Journaled Event implementation based on MongoDB
Date Sun, 06 Jan 2019 17:17:03 GMT
cschneider closed pull request #15: Journaled Event implementation based on MongoDB
URL: https://github.com/apache/aries-journaled-events/pull/15
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/org.apache.aries.events.mongo/pom.xml b/org.apache.aries.events.mongo/pom.xml
new file mode 100644
index 0000000..34cb08b
--- /dev/null
+++ b/org.apache.aries.events.mongo/pom.xml
@@ -0,0 +1,43 @@
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements. See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership. The SF licenses this file
+  ~ to you under the Apache License, Version 2.0 (the
+  ~ "License"); you may not use this file except in compliance
+  ~ with the License. You may obtain a copy of the License at
+  ~
+  ~     http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing,
+  ~ software distributed under the License is distributed on an
+  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  ~ KIND, either express or implied. See the License for the
+  ~ specific language governing permissions and limitations under the License.
+  -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.apache.aries.events</groupId>
+        <artifactId>org.apache.aries.events</artifactId>
+        <version>0.1.0-SNAPSHOT</version>
+    </parent>
+    <groupId>org.apache.aries.events.mongo</groupId>
+    <artifactId>org.apache.aries.events.mongo</artifactId>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.apache.aries.events</groupId>
+            <artifactId>org.apache.aries.events.api</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.mongodb</groupId>
+            <artifactId>mongo-java-driver</artifactId>
+            <version>3.8.2</version>
+        </dependency>
+    </dependencies>
+</project>
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/CachingFactory.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/CachingFactory.java
new file mode 100644
index 0000000..5b7fdc6
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/CachingFactory.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import org.slf4j.Logger;
+
+import java.io.Closeable;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Function;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * A factory that keeps previously created instances in a cache so that
+ * they will get reused if requested repeatedly.
+ * Currently there is no cache size limit implemented so this implementation
+ * is only good for the use case with limited parameter space.
+ * @param <K> key type. Serves as cache key as well as an input parameter for the
+ *           factory method. Must provide sensible implementations for
+ *          equals and hashCode methods
+ * @param <V> result type.
+ */
+public final class CachingFactory<K, V extends AutoCloseable> implements Closeable
{
+    
+
+    public static <K2, V2 extends AutoCloseable> CachingFactory<K2, V2> cachingFactory(Function<K2,
V2> create) {
+        return new CachingFactory<K2, V2>(create);
+    }
+
+    /**
+     * Find or created a value for the specified key
+     * @param arg key instance
+     * @return either an existing (cached) value of newly created one.
+     */
+    public synchronized V get(K arg) {
+        return cache.computeIfAbsent(arg, create);
+    }
+
+    /**
+     * Clears all cached instances properly disposing them.
+     */
+    public synchronized void clear() {
+        cache.values().stream()
+            .forEach(CachingFactory::safeClose);
+        cache.clear();
+    }
+
+    /**
+     * Closing this factory properly disposing all cached instances
+     */
+    @Override
+    public void close() {
+        clear();
+    }
+
+    //*********************************************
+    // Private
+    //*********************************************
+
+    private static final Logger LOG = getLogger(CachingFactory.class);
+    private final Map<K, V> cache = new HashMap<K, V>();
+    private final Function<K, V> create;
+
+    private CachingFactory(Function<K, V> create) {
+        this.create = create;
+    }
+
+    private static void safeClose(AutoCloseable closable) {
+        try {
+            closable.close();
+        } catch (Exception e) {
+            LOG.warn(e.getMessage(), e);
+        }
+    }
+
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/Common.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/Common.java
new file mode 100644
index 0000000..be5bc76
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/Common.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import com.mongodb.client.MongoCollection;
+import org.bson.Document;
+
+import static com.mongodb.client.model.Filters.lte;
+import static com.mongodb.client.model.Indexes.descending;
+import static org.apache.aries.events.mongo.Common.Fields.INDEX;
+
+/**
+ * Common string definitions
+ */
+@SuppressWarnings({"HardCodedStringLiteral", "InterfaceNeverImplemented"})
+interface Common {
+
+    String DEFAULT_DB_NAME = "aem-replication";
+
+    /** MongoDB field names */
+    interface Fields {
+        String INDEX = "i";
+        String TIME_STAMP = "t";
+        String PAYLOAD = "d";
+        String PROPS = "p";
+    }
+
+    /**
+     * Returns the next available index in the collection
+     * @param col collection to check. The collection must contain
+     *            log messages published by a Publisher instance
+     * @return the index that should be assigned to the next message when
+     * it gets published
+     */
+    static long upcomingIndex(MongoCollection<Document> col) {
+        Document doc = col.find(lte(INDEX, Long.MAX_VALUE))
+                          .sort(descending(INDEX))
+                          .first();
+        if (doc != null) {
+            long latestAvailable = doc.getLong(INDEX);
+            return latestAvailable + 1L;
+        } else {
+            return 0L;
+        }
+    }
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageReceiver.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageReceiver.java
new file mode 100644
index 0000000..1a9626e
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageReceiver.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import org.apache.aries.events.api.Message;
+
+public interface MessageReceiver extends AutoCloseable {
+
+    /** returns data entry for the specified offset.
+     * If necessary waits until data is available.
+     * If data entry at the specified offset has
+     * been evicted, throws NoSuchElement exception
+     * @param index an offset to the desired entry
+     * @return requested data entry together with the
+     *         offset for the next data entry
+     */
+    Message receive(long index) throws InterruptedException;
+
+    /** returns the index of the earliest available
+     * data entry. It also causes the receiver to
+     * pre-fetch and cache a batch of earliest available
+     * entries thus giving the user a chance to consume
+     * them and catch up before they get evicted
+     * @return an index of the first available data entry or
+     * 0 if the log is empty
+     */
+    long earliestIndex();
+
+    /** returns the index of the next available data
+     *  entry.
+     *  The returned index points to the entry yet to
+     *  be inserted into the log.
+     *  @return index of the data entry that will be
+     *  inserted next. 0 if the log is empty.
+     */
+    long latestIndex();
+
+    @Override
+    void close();
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageReceiverImpl.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageReceiverImpl.java
new file mode 100644
index 0000000..b2e4b19
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageReceiverImpl.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+
+import com.mongodb.Mongo;
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.model.Filters;
+import org.apache.aries.events.api.Message;
+import org.apache.aries.events.api.Received;
+import org.apache.aries.events.mongo.Common.Fields;
+import org.bson.Document;
+import org.bson.types.Binary;
+import org.slf4j.Logger;
+
+import static java.lang.Math.min;
+import static java.lang.System.currentTimeMillis;
+import static java.lang.Thread.sleep;
+import static java.util.Collections.emptyList;
+import static org.apache.aries.events.mongo.Common.Fields.PAYLOAD;
+import static org.apache.aries.events.mongo.Common.Fields.INDEX;
+import static org.apache.aries.events.mongo.Common.upcomingIndex;
+import static org.slf4j.LoggerFactory.getLogger;
+
+final class MessageReceiverImpl implements MessageReceiver {
+
+    static MessageReceiver messageReceiver(MongoCollection<Document> col) {
+        return new MessageReceiverImpl(col, Optional.empty());
+    }
+
+    @Override
+    public Message receive(long index) throws InterruptedException {
+        fetch(index);
+        long bufferIndex = index - firstIndex;
+        assert bufferIndex < buffer.size() : bufferIndex + ", " + buffer.size();
+        return buffer.get((int) bufferIndex);
+    }
+
+    @Override
+    public long earliestIndex() {
+       refreshBuffer(FIRST_AVAILABLE);
+       return firstIndex;
+    }
+
+    @Override
+    public long latestIndex() {
+        long result = upcomingIndex(col);
+        if (result > 0) {
+            result -= 1;
+        }
+        return result;
+    }
+
+    @Override
+    public void close() {
+        // MongoDB driver doesn't like to be interruped so
+        // we try to get out of the poll loop in a gentle way
+        interrupted = true;
+        mongoClient.ifPresent(Mongo::close);
+    }
+
+    //*********************************************
+    // Internals
+    //*********************************************
+
+    private static final Logger LOGGER = getLogger(MessageReceiverImpl.class);
+    private static final long FINE_GRAINED_DELAY = 100L;
+    private static final long FIRST_AVAILABLE = -1;
+    private final Optional<MongoClient> mongoClient;
+    private final MongoCollection<Document> col;
+    private long maxWaitTime = 1000L;
+    private int fetchLimit = 100;
+    private long lastReceived = currentTimeMillis();
+    private long firstIndex = 0L;
+    private List<Message> buffer = emptyList();
+    private volatile boolean interrupted = false;
+
+    private MessageReceiverImpl(MongoCollection<Document> col, Optional<MongoClient>
mongoClient) {
+        LOGGER.info("Creating new receiver: " + col.getNamespace().getCollectionName());
+        this.mongoClient = mongoClient;
+        this.col = col;
+    }
+
+    private void fetch(long index) throws InterruptedException {
+        while (firstIndex > index || firstIndex + buffer.size() <= index) {
+            long delay = min(maxWaitTime, (currentTimeMillis() - lastReceived) / 2);
+            adaptivePause(delay);
+            refreshBuffer(index);
+        }
+    }
+
+    private void refreshBuffer(long index) {
+        long startIndex = index;
+        try (MongoCursor<Document> cursor = col.find(Filters.gte(INDEX, startIndex)).iterator())
{
+            List<Message> collected = new ArrayList<>(fetchLimit);
+            while (cursor.hasNext()) {
+                int i = collected.size();
+                Document document = cursor.next();
+                long idx = document.get(INDEX, Long.class);
+                if (startIndex == FIRST_AVAILABLE) {
+                    startIndex = idx;
+                }
+                if (idx == startIndex + i) {
+                    Binary payload = document.get(PAYLOAD, Binary.class);
+                    Map<String, String> props = (Map<String, String>) document.get(Fields.PROPS);
+                    Message message = new MongoMessage(payload.getData(), props);
+                    collected.add(message);
+                } else {
+                    if (i == 0) {
+                        throw new NoSuchElementException("Element [" + startIndex + "] has
been evicted from the log. Oldest available: [" + idx + "]");
+                    } else {
+                        throw new IllegalStateException("Missing element at [" + (startIndex
+ i) + "]. Next available at [" + idx + "]");
+                    }
+                }
+            }
+            buffer = collected;
+            firstIndex = (startIndex == FIRST_AVAILABLE) ? 0L : startIndex;
+            if (collected.size() > 0) {
+                lastReceived = currentTimeMillis();
+            }
+        }
+    }
+
+    @SuppressWarnings("BusyWait")
+    private void adaptivePause(long ms) throws InterruptedException {
+        if (interrupted) {
+            throw new InterruptedException();
+        }
+        long currentTime = currentTimeMillis();
+        long stopTime = currentTime + ms;
+        while (currentTime < stopTime) {
+            if (interrupted) {
+                throw new InterruptedException();
+            }
+            sleep(min(FINE_GRAINED_DELAY, ms));
+            currentTime = currentTimeMillis();
+        }
+    }
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageSender.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageSender.java
new file mode 100644
index 0000000..cd187f6
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageSender.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+package org.apache.aries.events.mongo;
+
+import org.apache.aries.events.api.Message;
+
+import java.util.Map;
+
+/**
+ * Provides an API for publishing data to a distribution log
+ */
+public interface MessageSender extends AutoCloseable {
+
+    /**
+     * Publishes a single message to a log.
+     * @param message specifies a message to publish.
+     *             The following value types are supported:
+     *             Integer
+     *             Long
+     *             Boolean
+     *             String
+     *             byte[]
+     */
+    void send(Message message);
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageSenderImpl.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageSenderImpl.java
new file mode 100644
index 0000000..849e91f
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MessageSenderImpl.java
@@ -0,0 +1,140 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import com.mongodb.MongoWriteException;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.model.IndexOptions;
+import org.apache.aries.events.api.Message;
+import org.bson.Document;
+import org.slf4j.Logger;
+
+import java.util.function.Consumer;
+
+import static com.mongodb.client.model.Filters.lt;
+import static java.lang.System.currentTimeMillis;
+import static org.apache.aries.events.mongo.Common.Fields.INDEX;
+import static org.apache.aries.events.mongo.Common.Fields.PAYLOAD;
+import static org.apache.aries.events.mongo.Common.Fields.PROPS;
+import static org.apache.aries.events.mongo.Common.Fields.TIME_STAMP;
+import static org.apache.aries.events.mongo.Common.upcomingIndex;
+import static org.slf4j.LoggerFactory.getLogger;
+
+final class MessageSenderImpl implements MessageSender {
+
+    //*********************************************
+    // Creation
+    //*********************************************
+
+    static MessageSender messageSender(MongoCollection<Document> col, long maxAge)
{
+        return new MessageSenderImpl(col, maxAge);
+    }
+
+    //*********************************************
+    // Specialization
+    //*********************************************
+
+    @Override
+    public void send(Message message) {
+        publish1(message, 3);
+        evict();
+    }
+
+    @Override
+    public void close() {}
+
+    //*********************************************
+    // Internals
+    //*********************************************
+
+    private static final Logger LOGGER = getLogger(MessageSenderImpl.class);
+    private final MongoCollection<Document> collection;
+    private long nextEvictionTime = 0L;
+    private final long maxAge;
+
+    private MessageSenderImpl(MongoCollection<Document> collection, long maxAge) {
+        LOGGER.info("Creating new publisher: " + collection.getNamespace().getCollectionName());
+        ensureIndexes(collection);
+        this.collection = collection;
+        this.maxAge = maxAge;
+    }
+
+    private void evict() {
+        long currentTime = currentTimeMillis();
+        if (currentTime > nextEvictionTime) {
+            doEvict(currentTime - maxAge);
+            nextEvictionTime = oldestTimeStamp() + maxAge;
+        }
+    }
+
+    /**
+     * Deletes documents that are older then specified threshold but preserving at least
one document.
+     * At least one document is needed in the collection in order to keep track of the oldest
time stamp.
+     * @param threshold time threshold (ms). Documents older then specified by threshold
are removed.
+     */
+    private void doEvict(long threshold) {
+        collection.find()
+                  .projection(new Document(TIME_STAMP, 1))
+                  .sort(new Document(TIME_STAMP, -1))
+                  .limit(1)
+                  .forEach((Consumer<Document>) doc -> {
+               long newestTimeStamp = timeStamp(doc);
+               long adjustedThreshold = Math.min(threshold, newestTimeStamp);
+               collection.deleteMany(lt(TIME_STAMP, adjustedThreshold));
+           });
+    }
+
+    private void publish1(Message message, int retry) {
+        try {
+            long index = upcomingIndex(collection);
+            collection.insertOne(createDoc(index, message));
+        } catch (MongoWriteException e) {
+            if (retry > 0) {
+                publish1(message, retry - 1);
+            } else {
+                throw e;
+            }
+        }
+    }
+
+    private long oldestTimeStamp() {
+        try (MongoCursor<Document> docs = collection.find().sort(new Document(TIME_STAMP,
1)).iterator()) {
+            return docs.hasNext() ? docs.next().get(TIME_STAMP, Long.class) : 0L;
+        }
+    }
+
+    private static long timeStamp(Document doc) {
+        return doc.get(TIME_STAMP, Long.class);
+    }
+
+    private Document createDoc(long index, Message message) {
+        Document result = new Document();
+        result.put(INDEX,      index);
+        result.put(TIME_STAMP, currentTimeMillis());
+        result.put(PAYLOAD,    message.getPayload());
+        result.put(PROPS,      message.getProperties());
+        return result;
+    }
+
+    private void ensureIndexes(MongoCollection<Document> col) {
+        col.createIndex(new Document(INDEX, 1), new IndexOptions().unique(true));
+    }
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoEndpoint.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoEndpoint.java
new file mode 100644
index 0000000..7ee2a13
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoEndpoint.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
+
+/** Mongo endpoint configuration. (not used yet) */
+@ObjectClassDefinition(
+        name        = "Adobe Granite Mongo Distribution - MongoDB endpoint",
+        description = "Mongodb URI"
+)
+public @interface MongoEndpoint {
+
+    @AttributeDefinition(
+            name        = "Mongo URI",
+            description = "Specifies mongodb URI as it is specified here: https://docs.mongodb.com/manual/reference/connection-string/
"
+    )
+    String mongoUri() default "mongodb://localhost:27017/aem_distribution";
+
+    @AttributeDefinition(
+            name        = "Max Age",
+            description = "Log retention time expressed in milliseconds"
+    )
+    long maxAge() default 1000L * 3600 * 24 * 7; // One week in ms
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoMessage.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoMessage.java
new file mode 100644
index 0000000..5f47327
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoMessage.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import org.apache.aries.events.api.Message;
+
+import java.util.Map;
+
+class MongoMessage implements Message {
+
+    private byte[] payload;
+    private Map<String, String> properties;
+
+    MongoMessage(byte[] payload, Map<String, String> props) {
+	this.payload = payload;
+	properties = props;
+    }
+
+    @Override
+    public byte[] getPayload() {
+	return this.payload;
+    }
+
+    @Override
+    public Map<String, String> getProperties() {
+	return this.properties;
+    }
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoMessaging.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoMessaging.java
new file mode 100644
index 0000000..a3747eb
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoMessaging.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import com.mongodb.MongoClient;
+import com.mongodb.MongoClientURI;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import org.apache.aries.events.api.Message;
+import org.apache.aries.events.api.Messaging;
+import org.apache.aries.events.api.Position;
+import org.apache.aries.events.api.Received;
+import org.apache.aries.events.api.Seek;
+import org.apache.aries.events.api.Subscription;
+import org.bson.Document;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.metatype.annotations.Designate;
+
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+
+import static org.apache.aries.events.mongo.Common.DEFAULT_DB_NAME;
+import static org.apache.aries.events.mongo.MongoPosition.index;
+import static org.apache.aries.events.mongo.MongoPosition.position;
+import static org.apache.aries.events.mongo.MongoSubscription.subscription;
+import static org.apache.aries.events.mongo.MessageSenderImpl.messageSender;
+import static org.apache.aries.events.mongo.MessageReceiverImpl.messageReceiver;
+import static org.apache.aries.events.mongo.CachingFactory.cachingFactory;
+import static org.osgi.service.component.annotations.ConfigurationPolicy.REQUIRE;
+
+@Component(service = Messaging.class, configurationPolicy = REQUIRE)
+@Designate(ocd = MongoEndpoint.class)
+public class MongoMessaging implements Messaging {
+
+    @Override
+    public void send(String topic, Message message) {
+        MessageSender sender = senderFactory.get(topic);
+        sender.send(message);
+    }
+
+    @Override
+    public Subscription subscribe(
+	    String topic, Position position, Seek seek, Consumer<Received> callback
+    ) {
+        MongoCollection<Document> collection = database.getCollection(topic);
+        MessageReceiver receiver = messageReceiver(collection);
+        return subscription(receiver, index(position), seek, callback);
+    }
+
+    @Override
+    public Message newMessage(byte[] payload, Map<String, String> props) {
+        return new MongoMessage(payload, props);
+    }
+
+    @Override
+    public Position positionFromString(String position) {
+        long index = Long.parseLong(position);
+        return position(index);
+    }
+
+    // *******************************************************
+    // Private
+    // *******************************************************
+
+    private CachingFactory<String, MessageSender> senderFactory = initializedInActivate();
+    private MongoEndpoint config = initializedInActivate();
+    private MongoClient client = initializedInActivate();
+    private MongoDatabase database = initializedInActivate();
+
+    @Activate
+    protected void activate(MongoEndpoint config) {
+	this.config = config;
+	MongoClientURI uri = new MongoClientURI(config.mongoUri());
+	client = new MongoClient(uri);
+	String dbName = Optional.ofNullable(uri.getDatabase()).orElse(DEFAULT_DB_NAME);
+	this.database = client.getDatabase(dbName);
+	this.senderFactory = cachingFactory(topic -> {
+	    MongoCollection<Document> collection = database.getCollection(topic);
+	    return messageSender(collection, config.maxAge());
+	});
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        client.close();
+    }
+
+    private static <T> T initializedInActivate() {
+        return null;
+    }
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoPosition.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoPosition.java
new file mode 100644
index 0000000..910b15a
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoPosition.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import org.apache.aries.events.api.Position;
+
+class MongoPosition implements Position {
+
+    static Position position(long index) {
+        return new MongoPosition(index);
+    }
+
+    static long index(Position position) {
+        return ((MongoPosition) position).index;
+    }
+
+    @Override
+    public String positionToString() {
+        return String.valueOf(index);
+    }
+
+    @Override
+    public int compareTo(Position o) {
+        long thatIndex = ((MongoPosition) o).index;
+        if (this.index > thatIndex) return 1;
+        if (this.index == thatIndex) return 0;
+	return -1;
+    }
+
+    // *******************************************************
+    // Private
+    // *******************************************************
+
+    private final long index;
+
+    private MongoPosition(long index) {
+	this.index = index;
+    }
+
+}
diff --git a/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoSubscription.java
b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoSubscription.java
new file mode 100644
index 0000000..ea95f2f
--- /dev/null
+++ b/org.apache.aries.events.mongo/src/main/java/org/apache/aries/events/mongo/MongoSubscription.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The SF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ */
+
+package org.apache.aries.events.mongo;
+
+import org.apache.aries.events.api.Message;
+import org.apache.aries.events.api.Received;
+import org.apache.aries.events.api.Seek;
+import org.apache.aries.events.api.Subscription;
+import org.bson.Document;
+import org.slf4j.Logger;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.Consumer;
+
+import static java.lang.Thread.currentThread;
+import static java.lang.Thread.interrupted;
+import static org.apache.aries.events.mongo.MongoPosition.position;
+import static org.slf4j.LoggerFactory.getLogger;
+
+final class MongoSubscription implements Subscription {
+
+    //*********************************************
+    // Creation
+    //*********************************************
+
+    static MongoSubscription subscription(
+            MessageReceiver receiver, long index, Seek fallBack, Consumer<Received>
consumer
+    ) {
+        assert index >= 0L : "Illegal log index: [" + index + "]";
+        return new MongoSubscription(receiver, index, consumer);
+    }
+
+    static MongoSubscription subscription(
+            MessageReceiver receiver, Seek seek, Consumer<Received> consumer
+    ) {
+        switch (seek) {
+            case latest:
+                return new MongoSubscription(receiver, LATEST_INDEX, consumer);
+            case earliest:
+                return new MongoSubscription(receiver, EARLIEST_INDEX, consumer);
+            default:
+                throw new AssertionError(seek);
+        }
+    }
+
+    //*********************************************
+    // Package interface
+    //*********************************************
+
+    long index() {
+        return index;
+    }
+
+    //*********************************************
+    // Specialization
+    //*********************************************
+
+    @Override
+    public void close() {
+        receiver.close();
+    }
+
+    @Override
+    public String toString() {
+        return "Subscription" + receiver + '[' + index + ']';
+    }
+
+    //*********************************************
+    // Private
+    //*********************************************
+
+    private static final long LATEST_INDEX = -1;
+    private static final long EARLIEST_INDEX = -2;
+    private static final Logger LOGGER = getLogger(MongoSubscription.class);
+    private final MessageReceiver receiver;
+    private long index;
+    private final Consumer<Received> consumer;
+
+    private MongoSubscription(
+            MessageReceiver receiver, long index, Consumer<Received> consumer
+    ) {
+        this.consumer = consumer;
+        this.receiver = receiver;
+        if (index == EARLIEST_INDEX) {
+            this.index = receiver.earliestIndex();
+        } else if (index == LATEST_INDEX) {
+            this.index = receiver.latestIndex();
+        } else {
+            this.index = index;
+        }
+        this.index = index == LATEST_INDEX ? receiver.latestIndex() : index;
+        startBackgroundThread(() -> poll(receiver), "MongoMessageConsumer-" + receiver);
+    }
+
+    private void poll(MessageReceiver receiver) {
+        while (!interrupted()) {
+            try {
+                Message message = receiver.receive(index);
+                LOGGER.info("Received: " + message);
+                Received received = new Received(position(index), message);
+                consumer.accept(received);
+                index += 1L;
+            } catch (InterruptedException e) {
+                currentThread().interrupt();
+            } catch (Exception e) {
+                LOGGER.error("Error handling message", e);
+            }
+        }
+        LOGGER.info("Quitting " + this);
+        receiver.close();
+    }
+
+    private static Thread startBackgroundThread(Runnable runnable, String threadName) {
+        Thread thread = new Thread(runnable, threadName);
+        thread.setDaemon(true);
+        thread.start();
+        return thread;
+    }
+
+}
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index bf7e8b4..6105640 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,6 +43,7 @@
     <modules>
         <module>org.apache.aries.events.api</module>
         <module>org.apache.aries.events.memory</module>
+        <module>org.apache.aries.events.mongo</module>
     </modules>
 
     <properties>


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

Mime
View raw message