Distributed topic primitive

Change-Id: Ia3ccd84c33075f297d7e6b9bc205efe92aec9bea
diff --git a/apps/vtn/vtnrsc/src/test/java/org/onosproject/vtnrsc/util/VtnStorageServiceAdapter.java b/apps/vtn/vtnrsc/src/test/java/org/onosproject/vtnrsc/util/VtnStorageServiceAdapter.java
index fa64b5d..8421bb2 100644
--- a/apps/vtn/vtnrsc/src/test/java/org/onosproject/vtnrsc/util/VtnStorageServiceAdapter.java
+++ b/apps/vtn/vtnrsc/src/test/java/org/onosproject/vtnrsc/util/VtnStorageServiceAdapter.java
@@ -15,6 +15,7 @@
  */
 package org.onosproject.vtnrsc.util;
 
+import org.onosproject.store.service.Topic;
 import org.onosproject.store.service.WorkQueue;
 import org.onosproject.store.service.EventuallyConsistentMapBuilder;
 import org.onosproject.store.service.ConsistentMapBuilder;
@@ -69,4 +70,9 @@
     public <E> WorkQueue<E> getWorkQueue(String name, Serializer serializer) {
         return null;
     }
+
+    @Override
+    public <T> Topic<T> getTopic(String name, Serializer serializer) {
+        return null;
+    }
 }
diff --git a/core/api/src/main/java/org/onosproject/store/service/DistributedPrimitive.java b/core/api/src/main/java/org/onosproject/store/service/DistributedPrimitive.java
index 77bfd09..b19a04b 100644
--- a/core/api/src/main/java/org/onosproject/store/service/DistributedPrimitive.java
+++ b/core/api/src/main/java/org/onosproject/store/service/DistributedPrimitive.java
@@ -67,6 +67,11 @@
         WORK_QUEUE,
 
         /**
+         * Distributed topic.
+         */
+        TOPIC,
+
+        /**
          * Leader elector.
          */
         LEADER_ELECTOR,
diff --git a/core/api/src/main/java/org/onosproject/store/service/StorageService.java b/core/api/src/main/java/org/onosproject/store/service/StorageService.java
index 1e006eb..ebc60d1 100644
--- a/core/api/src/main/java/org/onosproject/store/service/StorageService.java
+++ b/core/api/src/main/java/org/onosproject/store/service/StorageService.java
@@ -110,4 +110,15 @@
      * @return WorkQueue instance
      */
     <E> WorkQueue<E> getWorkQueue(String name, Serializer serializer);
+
+    /**
+     * Returns an instance of {@code Topic} with specified name.
+     *
+     * @param <E> topic message type
+     * @param name topic name
+     * @param serializer serializer
+     *
+     * @return Topic instance
+     */
+    <T> Topic<T> getTopic(String name, Serializer serializer);
 }
diff --git a/core/api/src/main/java/org/onosproject/store/service/Topic.java b/core/api/src/main/java/org/onosproject/store/service/Topic.java
new file mode 100644
index 0000000..ac3742e
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/store/service/Topic.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed 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.onosproject.store.service;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Consumer;
+
+/**
+ * A distributed publish subscribe primitive.
+ * <p>
+ * This primitive provides ordered message delivery guarantee i.e. all messages will be delivered to
+ * all <i>active</i> subscribers and messages published from each publisher will be delivered
+ * to all active subscribers in the order in which they are published.
+ * <p>
+ * Transient disruptions in communication such as occasional message drops are automatically handled
+ * and recovered from without loss of delivery guarantees.
+ * <p>
+ * However, subscribers need to remain active or alive for these guarantees to apply. A subscriber that is
+ * partitioned away for an extended duration (typically 5 seconds or more) will be marked as inactive and
+ * during that period of inactivity will be removed from the list of current subscribers.
+ *
+ * @param <T> The type of message to be distributed to subscribers
+ */
+public interface Topic<T> extends DistributedPrimitive {
+
+    /**
+     * Publishes a message to all subscribers.
+     * <p>
+     * The message is delivered in a asynchronous fashion which means subscribers will receive the
+     * message eventually but not necessarily before the future returned by this method is completed.
+     * @param message The non-null message to send to all current subscribers
+     * @return a future that is completed when the message is logged (not necessarily delivered).
+     */
+    CompletableFuture<Void> publish(T message);
+
+    /**
+     * Subscribes to messages published to this topic.
+     * @param callback callback that will invoked when a message published to the topic is received.
+     * @return a future that is completed when subscription request is completed.
+     */
+    CompletableFuture<Void> subscribe(Consumer<T> callback);
+
+    /**
+     * Unsubscribes from this topic.
+     * @param callback previously subscribed callback
+     * @return a future that is completed when unsubscription request is completed.
+     */
+    CompletableFuture<Void> unsubscribe(Consumer<T> callback);
+}
\ No newline at end of file
diff --git a/core/api/src/test/java/org/onosproject/store/service/StorageServiceAdapter.java b/core/api/src/test/java/org/onosproject/store/service/StorageServiceAdapter.java
index 3978614..0cd1b60 100644
--- a/core/api/src/test/java/org/onosproject/store/service/StorageServiceAdapter.java
+++ b/core/api/src/test/java/org/onosproject/store/service/StorageServiceAdapter.java
@@ -58,4 +58,9 @@
     public <E> WorkQueue<E> getWorkQueue(String name, Serializer serializer) {
         return null;
     }
+
+    @Override
+    public <T> Topic<T> getTopic(String name, Serializer serializer) {
+        return null;
+    }
 }
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedTopic.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedTopic.java
new file mode 100644
index 0000000..df7bf9b
--- /dev/null
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/DefaultDistributedTopic.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed 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.onosproject.store.primitives.impl;
+
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Consumer;
+
+import org.onosproject.store.service.AsyncAtomicValue;
+import org.onosproject.store.service.AtomicValueEventListener;
+import org.onosproject.store.service.DistributedPrimitive;
+import org.onosproject.store.service.Topic;
+
+import com.google.common.collect.Maps;
+
+/**
+ * Default implementation of {@link Topic}.
+ *
+ * @param <T> topic message type.
+ */
+public class DefaultDistributedTopic<T> implements Topic<T> {
+
+    private final AsyncAtomicValue<T> atomicValue;
+    private final Map<Consumer<T>, AtomicValueEventListener<T>> callbacks = Maps.newIdentityHashMap();
+
+    DefaultDistributedTopic(AsyncAtomicValue<T> atomicValue) {
+        this.atomicValue = atomicValue;
+    }
+
+    @Override
+    public String name() {
+        return atomicValue.name();
+    }
+
+    @Override
+    public Type primitiveType() {
+        return DistributedPrimitive.Type.TOPIC;
+    }
+
+    @Override
+    public CompletableFuture<Void> destroy() {
+        return atomicValue.destroy();
+    }
+
+    @Override
+    public CompletableFuture<Void> publish(T message) {
+        return atomicValue.set(message);
+    }
+
+    @Override
+    public CompletableFuture<Void> subscribe(Consumer<T> callback) {
+        AtomicValueEventListener<T> valueListener = event -> callback.accept(event.newValue());
+        if (callbacks.putIfAbsent(callback, valueListener) == null) {
+            return atomicValue.addListener(valueListener);
+        }
+        return CompletableFuture.completedFuture(null);
+    }
+
+    @Override
+    public CompletableFuture<Void> unsubscribe(Consumer<T> callback) {
+        AtomicValueEventListener<T> valueListener = callbacks.remove(callback);
+        if (valueListener != null) {
+            return atomicValue.removeListener(valueListener);
+        }
+        return CompletableFuture.completedFuture(null);
+    }
+}
diff --git a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/StorageManager.java b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/StorageManager.java
index bc699d5..7658793 100644
--- a/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/StorageManager.java
+++ b/core/store/primitives/src/main/java/org/onosproject/store/primitives/impl/StorageManager.java
@@ -41,6 +41,7 @@
 import org.onosproject.store.primitives.PartitionService;
 import org.onosproject.store.primitives.TransactionId;
 import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.AsyncAtomicValue;
 import org.onosproject.store.service.AsyncConsistentMap;
 import org.onosproject.store.service.AtomicCounterBuilder;
 import org.onosproject.store.service.AtomicValueBuilder;
@@ -54,6 +55,7 @@
 import org.onosproject.store.service.Serializer;
 import org.onosproject.store.service.StorageAdminService;
 import org.onosproject.store.service.StorageService;
+import org.onosproject.store.service.Topic;
 import org.onosproject.store.service.TransactionContextBuilder;
 import org.onosproject.store.service.WorkQueue;
 import org.onosproject.store.service.WorkQueueStats;
@@ -217,4 +219,13 @@
                     return new MapInfo(name, map.size());
         }).collect(Collectors.toList());
     }
+
+    @Override
+    public <T> Topic<T> getTopic(String name, Serializer serializer) {
+        AsyncAtomicValue<T> atomicValue = this.<T>atomicValueBuilder()
+                                              .withName("topic-" + name)
+                                              .withSerializer(serializer)
+                                              .build();
+        return new DefaultDistributedTopic<>(atomicValue);
+    }
 }