Merged topic subscription search and publish into single MessagePublisher method

First step on implementing H2 storage

Minor, fixed not imported class

Cleaned MessageStore interface to avoid duplication of methods used in couple. Switched from guid + message to move messages

Separated ISubscriptionsStore from ISessionStore

Implemented H2 queue
This commit is contained in:
andsel
2017-06-02 10:13:34 +02:00
parent c18c915dd2
commit d9ff81131c
39 changed files with 1585 additions and 735 deletions
+14
View File
@@ -173,6 +173,20 @@
</configuration> </configuration>
</plugin> </plugin>
<!-- Generate the test-jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Includes to generate OSGi headers --> <!-- Includes to generate OSGi headers -->
<plugin> <plugin>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
@@ -16,20 +16,19 @@
package io.moquette.persistence; package io.moquette.persistence;
import io.moquette.spi.IMessagesStore;
import io.moquette.spi.IMatchingCondition; import io.moquette.spi.IMatchingCondition;
import io.moquette.spi.MessageGUID; import io.moquette.spi.IMessagesStore;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*; import java.util.*;
public class MemoryMessagesStore implements IMessagesStore { public class MemoryMessagesStore implements IMessagesStore {
private static final Logger LOG = LoggerFactory.getLogger(MemoryMessagesStore.class); private static final Logger LOG = LoggerFactory.getLogger(MemoryMessagesStore.class);
private Map<Topic, MessageGUID> m_retainedStore = new HashMap<>(); private Map<Topic, StoredMessage> m_retainedStore = new HashMap<>();
private Map<MessageGUID, StoredMessage> m_persistentMessageStore = new HashMap<>();
MemoryMessagesStore() { MemoryMessagesStore() {
} }
@@ -39,8 +38,12 @@ public class MemoryMessagesStore implements IMessagesStore {
} }
@Override @Override
public void storeRetained(Topic topic, MessageGUID guid) { public void storeRetained(Topic topic, StoredMessage storedMessage) {
m_retainedStore.put(topic, guid); LOG.debug("Store retained message for topic={}, CId={}", topic, storedMessage.getClientID());
if (storedMessage.getClientID() == null) {
throw new IllegalArgumentException( "Message to be persisted must have a not null client ID");
}
m_retainedStore.put(topic, storedMessage);
} }
@Override @Override
@@ -49,9 +52,8 @@ public class MemoryMessagesStore implements IMessagesStore {
List<StoredMessage> results = new ArrayList<>(); List<StoredMessage> results = new ArrayList<>();
for (Map.Entry<Topic, MessageGUID> entry : m_retainedStore.entrySet()) { for (Map.Entry<Topic, StoredMessage> entry : m_retainedStore.entrySet()) {
final MessageGUID guid = entry.getValue(); StoredMessage storedMsg = entry.getValue();
StoredMessage storedMsg = m_persistentMessageStore.get(guid);
if (condition.match(entry.getKey())) { if (condition.match(entry.getKey())) {
results.add(storedMsg); results.add(storedMsg);
} }
@@ -60,31 +62,6 @@ public class MemoryMessagesStore implements IMessagesStore {
return results; return results;
} }
@Override
public MessageGUID storePublishForFuture(StoredMessage storedMessage) {
LOG.debug("storePublishForFuture store evt {}", storedMessage);
MessageGUID guid = new MessageGUID(UUID.randomUUID().toString());
storedMessage.setGuid(guid);
m_persistentMessageStore.put(guid, storedMessage);
return guid;
}
@Override
public void dropInFlightMessagesInSession(Collection<MessageGUID> pendingAckMessages) {
//remove all guids from retained
Collection<MessageGUID> messagesToRemove = new HashSet<>(pendingAckMessages);
messagesToRemove.removeAll(m_retainedStore.values());
for (MessageGUID guid : messagesToRemove) {
m_persistentMessageStore.remove(guid);
}
}
@Override
public StoredMessage getMessageByGuid(MessageGUID guid) {
return m_persistentMessageStore.get(guid);
}
@Override @Override
public void cleanRetained(Topic topic) { public void cleanRetained(Topic topic) {
m_retainedStore.remove(topic); m_retainedStore.remove(topic);
@@ -18,22 +18,20 @@ package io.moquette.persistence;
import io.moquette.server.Constants; import io.moquette.server.Constants;
import io.moquette.spi.ClientSession; import io.moquette.spi.ClientSession;
import io.moquette.spi.IMessagesStore;
import io.moquette.spi.IMessagesStore.StoredMessage; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.MessageGUID; import io.moquette.spi.ISubscriptionsStore;
import io.moquette.spi.impl.Utils; import io.moquette.spi.impl.Utils;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*; import java.util.*;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import static io.moquette.spi.impl.Utils.defaultGet; public class MemorySessionStore implements ISessionsStore, ISubscriptionsStore {
public class MemorySessionStore implements ISessionsStore {
private static final Logger LOG = LoggerFactory.getLogger(MemorySessionStore.class); private static final Logger LOG = LoggerFactory.getLogger(MemorySessionStore.class);
@@ -41,21 +39,18 @@ public class MemorySessionStore implements ISessionsStore {
private Map<String, PersistentSession> m_persistentSessions = new HashMap<>(); private Map<String, PersistentSession> m_persistentSessions = new HashMap<>();
// maps clientID->[MessageId -> guid]
private Map<String, Map<Integer, MessageGUID>> m_inflightStore = new HashMap<>();
// maps clientID->BlockingQueue // maps clientID->BlockingQueue
private Map<String, BlockingQueue<StoredMessage>> queues = new HashMap<>(); private Map<String, BlockingQueue<StoredMessage>> queues = new HashMap<>();
// maps clientID->[MessageId -> guid] // maps clientID->[MessageId -> msg]
private Map<String, Map<Integer, MessageGUID>> m_secondPhaseStore = new HashMap<>(); private Map<String, Map<Integer, StoredMessage>> m_secondPhaseStore = new HashMap<>();
private Map<String, Map<Integer, MessageGUID>> outboundFlightMessageToGuid = new HashMap<>(); // maps clientID->[MessageId -> msg]
private Map<String, Map<Integer, StoredMessage>> outboundFlightMessages = new HashMap<>();
private Map<String, Map<Integer, MessageGUID>> inboundFlightMessageToGuid = new HashMap<>(); // maps clientID->[MessageId -> msg]
private Map<String, Map<Integer, StoredMessage>> inboundFlightMessages = new HashMap<>();
private final IMessagesStore m_messagesStore; public MemorySessionStore() {
public MemorySessionStore(IMessagesStore messagesStore) {
this.m_messagesStore = messagesStore;
} }
@Override @Override
@@ -72,6 +67,11 @@ public class MemorySessionStore implements ISessionsStore {
public void initStore() { public void initStore() {
} }
@Override
public ISubscriptionsStore subscriptionStore() {
return this;
}
@Override @Override
public void addNewSubscription(Subscription newSubscription) { public void addNewSubscription(Subscription newSubscription) {
final String clientID = newSubscription.getClientId(); final String clientID = newSubscription.getClientId();
@@ -102,7 +102,7 @@ public class MemorySessionStore implements ISessionsStore {
LOG.debug("clientID {} is a newcome, creating it's empty subscriptions set", clientID); LOG.debug("clientID {} is a newcome, creating it's empty subscriptions set", clientID);
m_persistentSubscriptions.put(clientID, new HashMap<Topic, Subscription>()); m_persistentSubscriptions.put(clientID, new HashMap<Topic, Subscription>());
m_persistentSessions.put(clientID, new PersistentSession(cleanSession)); m_persistentSessions.put(clientID, new PersistentSession(cleanSession));
return new ClientSession(clientID, m_messagesStore, this, cleanSession); return new ClientSession(clientID, this, this, cleanSession);
} }
@Override @Override
@@ -112,14 +112,14 @@ public class MemorySessionStore implements ISessionsStore {
} }
PersistentSession storedSession = m_persistentSessions.get(clientID); PersistentSession storedSession = m_persistentSessions.get(clientID);
return new ClientSession(clientID, m_messagesStore, this, storedSession.cleanSession); return new ClientSession(clientID, this, this, storedSession.cleanSession);
} }
@Override @Override
public Collection<ClientSession> getAllSessions() { public Collection<ClientSession> getAllSessions() {
Collection<ClientSession> result = new ArrayList<>(); Collection<ClientSession> result = new ArrayList<>();
for (Map.Entry<String, PersistentSession> entry : m_persistentSessions.entrySet()) { for (Map.Entry<String, PersistentSession> entry : m_persistentSessions.entrySet()) {
result.add(new ClientSession(entry.getKey(), m_messagesStore, this, entry.getValue().cleanSession)); result.add(new ClientSession(entry.getKey(), this, this, entry.getValue().cleanSession));
} }
return result; return result;
} }
@@ -159,28 +159,25 @@ public class MemorySessionStore implements ISessionsStore {
} }
@Override @Override
public void inFlightAck(String clientID, int messageID) { public StoredMessage inFlightAck(String clientID, int messageID) {
Map<Integer, MessageGUID> m = this.m_inflightStore.get(clientID); Map<Integer, StoredMessage> m = this.outboundFlightMessages.get(clientID);
if (m == null) { if (m == null) {
LOG.error("Can't find the inFlight record for client <{}>", clientID); LOG.error("Can't find the inFlight record for client <{}>", clientID);
return; throw new RuntimeException("Can't find the inFlight record for client <" + clientID + ">");
} }
m.remove(messageID); StoredMessage msg = m.remove(messageID);
this.outboundFlightMessages.put(clientID, m);
return msg;
} }
@Override @Override
public void inFlight(String clientID, int messageID, MessageGUID guid) { public void inFlight(String clientID, int messageID, StoredMessage msg) {
Map<Integer, MessageGUID> m = this.m_inflightStore.get(clientID); Map<Integer, StoredMessage> messages = outboundFlightMessages.get(clientID);
if (m == null) { if (messages == null) {
m = new HashMap<>(); messages = new HashMap<>();
} }
m.put(messageID, guid); messages.put(messageID, msg);
this.m_inflightStore.put(clientID, m); outboundFlightMessages.put(clientID, messages);
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
Map<Integer, MessageGUID> guids = defaultGet(outboundFlightMessageToGuid, clientID, emptyGuids);
guids.put(messageID, guid);
outboundFlightMessageToGuid.put(clientID, guids);
} }
/** /**
@@ -188,7 +185,7 @@ public class MemorySessionStore implements ISessionsStore {
*/ */
@Override @Override
public int nextPacketID(String clientID) { public int nextPacketID(String clientID) {
Map<Integer, MessageGUID> m = this.m_inflightStore.get(clientID); Map<Integer, StoredMessage> m = this.outboundFlightMessages.get(clientID);
if (m == null) { if (m == null) {
m = new HashMap<>(); m = new HashMap<>();
int nextPacketId = 1; int nextPacketId = 1;
@@ -215,61 +212,73 @@ public class MemorySessionStore implements ISessionsStore {
} }
@Override @Override
public void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID) { public void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID, StoredMessage msg) {
LOG.info("acknowledging inflight clientID <{}> messageID {}", clientID, messageID); LOG.info("Moving msg inflight second phase store, clientID <{}> messageID {}", clientID, messageID);
Map<Integer, MessageGUID> m = this.m_inflightStore.get(clientID); Map<Integer, StoredMessage> m = this.m_secondPhaseStore.get(clientID);
if (m == null) { if (m == null) {
LOG.error("Can't find the inFlight record for client <{}>", clientID); m = new HashMap<>();
return;
} }
MessageGUID guid = m.remove(messageID); m.put(messageID, msg);
this.outboundFlightMessages.put(clientID, m);
LOG.info("Moving to second phase store");
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
Map<Integer, MessageGUID> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, emptyGuids);
messageIDs.put(messageID, guid);
m_secondPhaseStore.put(clientID, messageIDs);
} }
@Override @Override
public MessageGUID secondPhaseAcknowledged(String clientID, int messageID) { public StoredMessage secondPhaseAcknowledged(String clientID, int messageID) {
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>(); LOG.info("Acknowledged message in second phase, clientID <{}> messageID {}", clientID, messageID);
Map<Integer, MessageGUID> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, emptyGuids); final Map<Integer, StoredMessage> m = this.m_secondPhaseStore.get(clientID);
MessageGUID guid = messageIDs.remove(messageID); if (m == null) {
m_secondPhaseStore.put(clientID, messageIDs); String error = String.format("Can't find the inFlight record for client <%s> during the second phase " +
return guid; "acking of QoS2 pub", clientID);
} LOG.error(error);
throw new RuntimeException(error);
}
@Override StoredMessage msg = m.remove(messageID);
public StoredMessage getInflightMessage(String clientID, int messageID) { m_secondPhaseStore.put(clientID, m);
Map<Integer, MessageGUID> inflightMessages = m_inflightStore.get(clientID); return msg;
MessageGUID guid = inflightMessages.get(messageID);
return m_messagesStore.getMessageByGuid(guid);
} }
@Override @Override
public int getInflightMessagesNo(String clientID) { public int getInflightMessagesNo(String clientID) {
Map<Integer, MessageGUID> inflightMessages = m_inflightStore.get(clientID); int totalInflight = 0;
if (inflightMessages == null) Map<Integer, StoredMessage> inflightPerClient = this.inboundFlightMessages.get(clientID);
return 0; if (inflightPerClient != null) {
else totalInflight += inflightPerClient.size();
return inflightMessages.size(); }
Map<Integer, StoredMessage> secondPhaseInFlight = this.m_secondPhaseStore.get(clientID);
if (secondPhaseInFlight != null) {
totalInflight += secondPhaseInFlight.size();
}
Map<Integer, StoredMessage> outboundPerClient = outboundFlightMessages.get(clientID);
if (outboundPerClient != null) {
totalInflight += outboundPerClient.size();
}
return totalInflight;
} }
@Override @Override
public StoredMessage inboundInflight(String clientID, int messageID) { public StoredMessage inboundInflight(String clientID, int messageID) {
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>(); Map<Integer, StoredMessage> inflightPerClient = this.inboundFlightMessages.get(clientID);
Map<Integer, MessageGUID> guids = Utils.defaultGet(inboundFlightMessageToGuid, clientID, emptyGuids); if (inflightPerClient == null) {
final MessageGUID guid = guids.get(messageID); String error = String.format("Can't find inbound inflight zone for client <%s>", clientID);
return m_messagesStore.getMessageByGuid(guid); LOG.error(error);
throw new RuntimeException(error);
}
return inflightPerClient.get(messageID);
} }
@Override @Override
public void markAsInboundInflight(String clientID, int messageID, MessageGUID guid) { public void markAsInboundInflight(String clientID, int messageID, StoredMessage msg) {
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>(); Map<Integer, StoredMessage> inflightPerClient = this.inboundFlightMessages.get(clientID);
Map<Integer, MessageGUID> guids = Utils.defaultGet(inboundFlightMessageToGuid, clientID, emptyGuids); if (inflightPerClient == null) {
guids.put(messageID, guid); inflightPerClient = new HashMap<>();
inboundFlightMessageToGuid.put(clientID, guids); }
inflightPerClient.put(messageID, msg);
inboundFlightMessages.put(clientID, inflightPerClient);
} }
@Override @Override
@@ -279,7 +288,7 @@ public class MemorySessionStore implements ISessionsStore {
@Override @Override
public int getSecondPhaseAckPendingMessages(String clientID) { public int getSecondPhaseAckPendingMessages(String clientID) {
Map<Integer, MessageGUID> pendingAcks = m_secondPhaseStore.get(clientID); Map<Integer, StoredMessage> pendingAcks = m_secondPhaseStore.get(clientID);
if (pendingAcks == null) if (pendingAcks == null)
return 0; return 0;
else else
@@ -287,12 +296,8 @@ public class MemorySessionStore implements ISessionsStore {
} }
@Override @Override
public Collection<MessageGUID> pendingAck(String clientID) { public void dropInFlightMessagesInSession(String clientID) {
Map<Integer, MessageGUID> messageGUIDMap = outboundFlightMessageToGuid.get(clientID); outboundFlightMessages.remove(clientID);
if (messageGUIDMap == null || messageGUIDMap.isEmpty()) { inboundFlightMessages.remove(clientID);
return Collections.emptyList();
}
return new ArrayList<>(messageGUIDMap.values());
} }
} }
@@ -27,7 +27,7 @@ public class MemoryStorageService implements IStore {
public MemoryStorageService() { public MemoryStorageService() {
m_messagesStore = new MemoryMessagesStore(); m_messagesStore = new MemoryMessagesStore();
m_sessionsStore = new MemorySessionStore(m_messagesStore); m_sessionsStore = new MemorySessionStore();
m_messagesStore.initStore(); m_messagesStore.initStore();
m_sessionsStore.initStore(); m_sessionsStore.initStore();
} }
@@ -42,6 +42,10 @@ public class MemoryStorageService implements IStore {
return m_sessionsStore; return m_sessionsStore;
} }
@Override
public void initStore() {
}
@Override @Override
public void close() { public void close() {
} }
@@ -16,11 +16,12 @@
package io.moquette.spi; package io.moquette.spi;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISubscriptionsStore.ClientTopicCouple;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
@@ -44,22 +45,22 @@ public class ClientSession {
class OutboundFlightZone { class OutboundFlightZone {
/** /**
* Save the binding messageID, clientID - guid * Save the binding messageID, clientID - message
*
* @param messageID the packet ID used in transmission * @param messageID the packet ID used in transmission
* @param guid the guid of the message being in flight. * @param msg the message to put in flight zone
*/ */
void waitingAck(int messageID, MessageGUID guid) { void waitingAck(int messageID, IMessagesStore.StoredMessage msg) {
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("Adding to inflight {}, guid <{}>", messageID, guid); LOG.trace("Adding to inflight {}, guid <{}>", messageID, msg.getGuid());
} }
m_sessionsStore.inFlight(ClientSession.this.clientID, messageID, guid); m_sessionsStore.inFlight(ClientSession.this.clientID, messageID, msg);
} }
void acknowledged(int messageID) { IMessagesStore.StoredMessage acknowledged(int messageID) {
if (LOG.isTraceEnabled()) if (LOG.isTraceEnabled())
LOG.trace("Acknowledging inflight, clientID <{}> messageID {}", ClientSession.this.clientID, messageID); LOG.trace("Acknowledging inflight, clientID <{}> messageID {}", ClientSession.this.clientID, messageID);
m_sessionsStore.inFlightAck(ClientSession.this.clientID, messageID); return m_sessionsStore.inFlightAck(ClientSession.this.clientID, messageID);
} }
} }
@@ -69,8 +70,8 @@ public class ClientSession {
return m_sessionsStore.inboundInflight(clientID, messageID); return m_sessionsStore.inboundInflight(clientID, messageID);
} }
public void waitingRel(int messageID, MessageGUID guid) { public void waitingRel(int messageID, IMessagesStore.StoredMessage msg) {
m_sessionsStore.markAsInboundInflight(clientID, messageID, guid); m_sessionsStore.markAsInboundInflight(clientID, messageID, msg);
} }
} }
@@ -78,12 +79,11 @@ public class ClientSession {
public final String clientID; public final String clientID;
private final IMessagesStore messagesStore;
private final ISessionsStore m_sessionsStore; private final ISessionsStore m_sessionsStore;
private Set<Subscription> subscriptions = new HashSet<>(); private Set<Subscription> subscriptions = new HashSet<>();
private final ISubscriptionsStore subscriptionsStore;
private volatile boolean cleanSession; private volatile boolean cleanSession;
// private BlockingQueue<AbstractMessage> m_queueToPublish = new // private BlockingQueue<AbstractMessage> m_queueToPublish = new
@@ -91,11 +91,11 @@ public class ClientSession {
private final OutboundFlightZone outboundFlightZone; private final OutboundFlightZone outboundFlightZone;
private final InboundFlightZone inboundFlightZone; private final InboundFlightZone inboundFlightZone;
public ClientSession(String clientID, IMessagesStore messagesStore, ISessionsStore sessionsStore, public ClientSession(String clientID, ISessionsStore sessionsStore, ISubscriptionsStore subscriptionsStore,
boolean cleanSession) { boolean cleanSession) {
this.clientID = clientID; this.clientID = clientID;
this.messagesStore = messagesStore;
this.m_sessionsStore = sessionsStore; this.m_sessionsStore = sessionsStore;
this.subscriptionsStore = subscriptionsStore;
this.cleanSession = cleanSession; this.cleanSession = cleanSession;
this.outboundFlightZone = new OutboundFlightZone(); this.outboundFlightZone = new OutboundFlightZone();
this.inboundFlightZone = new InboundFlightZone(); this.inboundFlightZone = new InboundFlightZone();
@@ -129,7 +129,7 @@ public class ClientSession {
return false; return false;
} }
ClientTopicCouple matchingCouple = new ClientTopicCouple(this.clientID, newSubscription.getTopicFilter()); ClientTopicCouple matchingCouple = new ClientTopicCouple(this.clientID, newSubscription.getTopicFilter());
Subscription existingSub = m_sessionsStore.getSubscription(matchingCouple); Subscription existingSub = subscriptionsStore.getSubscription(matchingCouple);
// update the selected subscriptions if not present or if has a greater qos // update the selected subscriptions if not present or if has a greater qos
if (existingSub == null || existingSub.getRequestedQos().value() < newSubscription.getRequestedQos().value()) { if (existingSub == null || existingSub.getRequestedQos().value() < newSubscription.getRequestedQos().value()) {
if (existingSub != null) { if (existingSub != null) {
@@ -139,14 +139,14 @@ public class ClientSession {
subscriptions.remove(newSubscription); subscriptions.remove(newSubscription);
} }
subscriptions.add(newSubscription); subscriptions.add(newSubscription);
m_sessionsStore.addNewSubscription(newSubscription); subscriptionsStore.addNewSubscription(newSubscription);
} }
return true; return true;
} }
public void unsubscribeFrom(Topic topicFilter) { public void unsubscribeFrom(Topic topicFilter) {
LOG.info("Removing subscription. ClientID={}, topics={}", clientID, topicFilter); LOG.info("Removing subscription. ClientID={}, topics={}", clientID, topicFilter);
m_sessionsStore.removeSubscription(topicFilter, clientID); subscriptionsStore.removeSubscription(topicFilter, clientID);
Set<Subscription> subscriptionsToRemove = new HashSet<>(); Set<Subscription> subscriptionsToRemove = new HashSet<>();
for (Subscription sub : this.subscriptions) { for (Subscription sub : this.subscriptions) {
if (sub.getTopicFilter().equals(topicFilter)) { if (sub.getTopicFilter().equals(topicFilter)) {
@@ -166,11 +166,11 @@ public class ClientSession {
public void cleanSession() { public void cleanSession() {
LOG.info("Wiping existing subscriptions. ClientId={}", this.clientID); LOG.info("Wiping existing subscriptions. ClientId={}", this.clientID);
m_sessionsStore.wipeSubscriptions(this.clientID); subscriptionsStore.wipeSubscriptions(this.clientID);
// remove also the messages stored of type QoS1/2 // remove also the messages stored of type QoS1/2
LOG.info("Removing stored messages with QoS 1 and 2. ClientId={}", this.clientID); LOG.info("Removing stored messages with QoS 1 and 2. ClientId={}", this.clientID);
messagesStore.dropInFlightMessagesInSession(m_sessionsStore.pendingAck(this.clientID)); m_sessionsStore.dropInFlightMessagesInSession(this.clientID);
//remove also the enqueued messages //remove also the enqueued messages
this.m_sessionsStore.dropQueue(this.clientID); this.m_sessionsStore.dropQueue(this.clientID);
@@ -189,8 +189,8 @@ public class ClientSession {
return this.m_sessionsStore.nextPacketID(this.clientID); return this.m_sessionsStore.nextPacketID(this.clientID);
} }
public void inFlightAcknowledged(int messageID) { public IMessagesStore.StoredMessage inFlightAcknowledged(int messageID) {
outboundFlightZone.acknowledged(messageID); return outboundFlightZone.acknowledged(messageID);
} }
/** /**
@@ -200,21 +200,13 @@ public class ClientSession {
* */ * */
public int inFlightAckWaiting(IMessagesStore.StoredMessage msg) { public int inFlightAckWaiting(IMessagesStore.StoredMessage msg) {
LOG.debug("Adding message ot inflight zone. ClientId={}", clientID); LOG.debug("Adding message ot inflight zone. ClientId={}", clientID);
MessageGUID guid = msg.getGuid();
if (guid == null) {
guid = messagesStore.storePublishForFuture(msg);
msg.setGuid(guid);
LOG.debug("Not yet assigned guid to message, updating guid={}", guid);
}
int messageId = ClientSession.this.nextPacketId(); int messageId = ClientSession.this.nextPacketId();
outboundFlightZone.waitingAck(messageId, guid); outboundFlightZone.waitingAck(messageId, msg);
return messageId; return messageId;
} }
public IMessagesStore.StoredMessage secondPhaseAcknowledged(int messageID) { public IMessagesStore.StoredMessage secondPhaseAcknowledged(int messageID) {
MessageGUID guid = m_sessionsStore.secondPhaseAcknowledged(clientID, messageID); return m_sessionsStore.secondPhaseAcknowledged(clientID, messageID);
return messagesStore.getMessageByGuid(guid);
} }
/** /**
@@ -231,16 +223,12 @@ public class ClientSession {
return inboundFlightZone.lookup(messageID); return inboundFlightZone.lookup(messageID);
} }
public void markAsInboundInflight(int messageID, MessageGUID guid) { public void markAsInboundInflight(int messageID, IMessagesStore.StoredMessage msg) {
inboundFlightZone.waitingRel(messageID, guid); inboundFlightZone.waitingRel(messageID, msg);
} }
public void moveInFlightToSecondPhaseAckWaiting(int messageID) { public void moveInFlightToSecondPhaseAckWaiting(int messageID, IMessagesStore.StoredMessage msg) {
m_sessionsStore.moveInFlightToSecondPhaseAckWaiting(this.clientID, messageID); m_sessionsStore.moveInFlightToSecondPhaseAckWaiting(this.clientID, messageID, msg);
}
public IMessagesStore.StoredMessage getInflightMessage(int messageID) {
return m_sessionsStore.getInflightMessage(clientID, messageID);
} }
public Set<Subscription> getSubscriptions() { public Set<Subscription> getSubscriptions() {
@@ -93,16 +93,6 @@ public interface IMessagesStore {
*/ */
void initStore(); void initStore();
/**
* Persist the message. If the message is empty then the topic is cleaned, else it's stored.
*
* @param topic
* for the retained.
* @param guid
* of the message to mark as retained.
*/
void storeRetained(Topic topic, MessageGUID guid);
/** /**
* Return a list of retained messages that satisfy the condition. * Return a list of retained messages that satisfy the condition.
* *
@@ -112,18 +102,7 @@ public interface IMessagesStore {
*/ */
Collection<StoredMessage> searchMatching(IMatchingCondition condition); Collection<StoredMessage> searchMatching(IMatchingCondition condition);
/**
* Persist the message.
*
* @param storedMessage
* the message to store for future usage.
* @return the unique id in the storage (guid).
*/
MessageGUID storePublishForFuture(StoredMessage storedMessage);
void dropInFlightMessagesInSession(Collection<MessageGUID> pendingAckMessages);
StoredMessage getMessageByGuid(MessageGUID guid);
void cleanRetained(Topic topic); void cleanRetained(Topic topic);
void storeRetained(Topic topic, StoredMessage storedMessage);
} }
@@ -17,11 +17,8 @@
package io.moquette.spi; package io.moquette.spi;
import io.moquette.spi.IMessagesStore.StoredMessage; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
/** /**
@@ -29,90 +26,12 @@ import java.util.concurrent.BlockingQueue;
*/ */
public interface ISessionsStore { public interface ISessionsStore {
class ClientTopicCouple {
public final Topic topicFilter;
public final String clientID;
public ClientTopicCouple(String clientID, Topic topicFilter) {
this.clientID = clientID;
this.topicFilter = topicFilter;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ClientTopicCouple that = (ClientTopicCouple) o;
if (topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null)
return false;
return !(clientID != null ? !clientID.equals(that.clientID) : that.clientID != null);
}
@Override
public int hashCode() {
int result = topicFilter != null ? topicFilter.hashCode() : 0;
result = 31 * result + (clientID != null ? clientID.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ClientTopicCouple{" + "topicFilter='" + topicFilter + '\'' + ", clientID='" + clientID + '\'' + '}';
}
}
void initStore(); void initStore();
ISubscriptionsStore subscriptionStore();
void updateCleanStatus(String clientID, boolean cleanSession); void updateCleanStatus(String clientID, boolean cleanSession);
/**
* Add a new subscription to the session
*
* @param newSubscription
* the subscription to add.
*/
void addNewSubscription(Subscription newSubscription);
/**
* Removed a specific subscription
*
* @param topic
* the topic of the subscription.
* @param clientID
* the session client.
*/
void removeSubscription(Topic topic, String clientID);
/**
* Remove all the subscriptions of the session
*
* @param sessionID
* the client ID
*/
void wipeSubscriptions(String sessionID);
/**
* Return all topic filters to recreate the subscription tree.
*/
List<ClientTopicCouple> listAllSubscriptions();
/**
* @param couple
* the subscription descriptor.
* @return the subscription stored by clientID and topicFilter, if any else null;
*/
Subscription getSubscription(ClientTopicCouple couple);
/*
* @return all subscriptions stored.
*/
List<Subscription> getSubscriptions();
/** /**
* @param clientID * @param clientID
* the session client ID. * the session client ID.
@@ -132,23 +51,23 @@ public interface ISessionsStore {
/** /**
* Returns all the sessions * Returns all the sessions
* *
* @return * @return the collection of all stored client sessions.
*/ */
Collection<ClientSession> getAllSessions(); Collection<ClientSession> getAllSessions();
void inFlightAck(String clientID, int messageID); StoredMessage inFlightAck(String clientID, int messageID);
/** /**
* Save the binding messageID, clientID - guid * Save the message msg with messageID, clientID as in flight
* *
* @param clientID * @param clientID
* the client ID * the client ID
* @param messageID * @param messageID
* the message ID * the message ID
* @param guid * @param msg
* the uuid of the message to mark as inflight. * the message to put in flight zone
*/ */
void inFlight(String clientID, int messageID, MessageGUID guid); void inFlight(String clientID, int messageID, StoredMessage msg);
/** /**
* Return the next valid packetIdentifier for the given client session. * Return the next valid packetIdentifier for the given client session.
@@ -170,7 +89,7 @@ public interface ISessionsStore {
void dropQueue(String clientID); void dropQueue(String clientID);
void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID); void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID, StoredMessage msg);
/** /**
* @param clientID * @param clientID
@@ -179,9 +98,7 @@ public interface ISessionsStore {
* the message ID that reached the second phase. * the message ID that reached the second phase.
* @return the guid of message just acked. * @return the guid of message just acked.
*/ */
MessageGUID secondPhaseAcknowledged(String clientID, int messageID); StoredMessage secondPhaseAcknowledged(String clientID, int messageID);
StoredMessage getInflightMessage(String clientID, int messageID);
/** /**
* Returns the number of inflight messages for the given client ID * Returns the number of inflight messages for the given client ID
@@ -196,7 +113,7 @@ public interface ISessionsStore {
* */ * */
IMessagesStore.StoredMessage inboundInflight(String clientID, int messageID); IMessagesStore.StoredMessage inboundInflight(String clientID, int messageID);
void markAsInboundInflight(String clientID, int messageID, MessageGUID guid); void markAsInboundInflight(String clientID, int messageID, StoredMessage msg);
/** /**
* Returns the size of the session queue for the given client ID * Returns the size of the session queue for the given client ID
@@ -214,5 +131,5 @@ public interface ISessionsStore {
*/ */
int getSecondPhaseAckPendingMessages(String clientID); int getSecondPhaseAckPendingMessages(String clientID);
Collection<MessageGUID> pendingAck(String clientID); void dropInFlightMessagesInSession(String clientID);
} }
@@ -18,9 +18,21 @@ package io.moquette.spi;
public interface IStore { public interface IStore {
IMessagesStore messagesStore(); void initStore();
ISessionsStore sessionsStore();
void close(); void close();
/**
* Factory method to instantiate the messages store.
*
* @return the create instance of IMessagesStore.
* */
IMessagesStore messagesStore();
/**
* Factory method to instantiate the session store.
*
* @return the create instance of ISessionsStore.
* */
ISessionsStore sessionsStore();
} }
@@ -0,0 +1,90 @@
package io.moquette.spi;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic;
import java.util.List;
public interface ISubscriptionsStore {
class ClientTopicCouple {
public final Topic topicFilter;
public final String clientID;
public ClientTopicCouple(String clientID, Topic topicFilter) {
this.clientID = clientID;
this.topicFilter = topicFilter;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ClientTopicCouple that = (ClientTopicCouple) o;
if (topicFilter != null ? !topicFilter.equals(that.topicFilter) : that.topicFilter != null)
return false;
return !(clientID != null ? !clientID.equals(that.clientID) : that.clientID != null);
}
@Override
public int hashCode() {
int result = topicFilter != null ? topicFilter.hashCode() : 0;
result = 31 * result + (clientID != null ? clientID.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ClientTopicCouple{" + "topicFilter='" + topicFilter + '\'' + ", clientID='" + clientID + '\'' + '}';
}
}
/**
* Add a new subscription to the session
*
* @param newSubscription
* the subscription to add.
*/
void addNewSubscription(Subscription newSubscription);
/**
* Removed a specific subscription
*
* @param topic
* the topic of the subscription.
* @param clientID
* the session client.
*/
void removeSubscription(Topic topic, String clientID);
/**
* Remove all the subscriptions of the session
*
* @param sessionID
* the client ID
*/
void wipeSubscriptions(String sessionID);
/**
* Return all topic filters to recreate the subscription tree.
*/
List<ClientTopicCouple> listAllSubscriptions();
/**
* @param couple
* the subscription descriptor.
* @return the subscription stored by clientID and topicFilter, if any else null;
*/
Subscription getSubscription(ClientTopicCouple couple);
/*
* @return all subscriptions stored.
*/
List<Subscription> getSubscriptions();
}
@@ -21,7 +21,7 @@ import io.moquette.spi.ClientSession;
import io.moquette.spi.IMessagesStore; import io.moquette.spi.IMessagesStore;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore; import io.moquette.spi.impl.subscriptions.SubscriptionsDirectory;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.*; import io.netty.handler.codec.mqtt.*;
@@ -36,10 +36,10 @@ class MessagesPublisher {
private final ConnectionDescriptorStore connectionDescriptors; private final ConnectionDescriptorStore connectionDescriptors;
private final ISessionsStore m_sessionsStore; private final ISessionsStore m_sessionsStore;
private final PersistentQueueMessageSender messageSender; private final PersistentQueueMessageSender messageSender;
private final SubscriptionsStore subscriptions; private final SubscriptionsDirectory subscriptions;
public MessagesPublisher(ConnectionDescriptorStore connectionDescriptors, ISessionsStore sessionsStore, public MessagesPublisher(ConnectionDescriptorStore connectionDescriptors, ISessionsStore sessionsStore,
PersistentQueueMessageSender messageSender, SubscriptionsStore subscriptions) { PersistentQueueMessageSender messageSender, SubscriptionsDirectory subscriptions) {
this.connectionDescriptors = connectionDescriptors; this.connectionDescriptors = connectionDescriptors;
this.m_sessionsStore = sessionsStore; this.m_sessionsStore = sessionsStore;
this.messageSender = messageSender; this.messageSender = messageSender;
@@ -59,11 +59,11 @@ class MessagesPublisher {
void publish2Subscribers(IMessagesStore.StoredMessage pubMsg, Topic topic, int messageID) { void publish2Subscribers(IMessagesStore.StoredMessage pubMsg, Topic topic, int messageID) {
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("Sending publish message to subscribers. CId={}, topic={}, messageId={}, payload={}, " + LOG.trace("Sending publish message to subscribers. ClientId={}, topic={}, messageId={}, payload={}, " +
"subscriptionTree={}", pubMsg.getClientID(), topic, messageID, DebugUtils.payload2Str(pubMsg.getPayload()), "subscriptionTree={}", pubMsg.getClientID(), topic, messageID, DebugUtils.payload2Str(pubMsg.getPayload()),
subscriptions.dumpTree()); subscriptions.dumpTree());
} else { } else {
LOG.info("Sending publish message to subscribers. CId={}, topic={}, messageId={}", pubMsg.getClientID(), topic, LOG.info("Sending publish message to subscribers. ClientId={}, topic={}, messageId={}", pubMsg.getClientID(), topic,
messageID); messageID);
} }
publish2Subscribers(pubMsg, topic); publish2Subscribers(pubMsg, topic);
@@ -24,7 +24,7 @@ import io.moquette.server.netty.NettyUtils;
import io.moquette.spi.*; import io.moquette.spi.*;
import io.moquette.spi.IMessagesStore.StoredMessage; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore; import io.moquette.spi.impl.subscriptions.SubscriptionsDirectory;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import io.moquette.spi.security.IAuthenticator; import io.moquette.spi.security.IAuthenticator;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
@@ -130,7 +130,8 @@ public class ProtocolProcessor {
protected ConnectionDescriptorStore connectionDescriptors; protected ConnectionDescriptorStore connectionDescriptors;
protected ConcurrentMap<RunningSubscription, SubscriptionState> subscriptionInCourse; protected ConcurrentMap<RunningSubscription, SubscriptionState> subscriptionInCourse;
private SubscriptionsStore subscriptions; private SubscriptionsDirectory subscriptions;
private ISubscriptionsStore subscriptionStore;
private boolean allowAnonymous; private boolean allowAnonymous;
private boolean allowZeroByteClientId; private boolean allowZeroByteClientId;
private IAuthorizator m_authorizator; private IAuthorizator m_authorizator;
@@ -141,7 +142,6 @@ public class ProtocolProcessor {
private IAuthenticator m_authenticator; private IAuthenticator m_authenticator;
private BrokerInterceptor m_interceptor; private BrokerInterceptor m_interceptor;
private String m_server_port;
private Qos0PublishHandler qos0PublishHandler; private Qos0PublishHandler qos0PublishHandler;
private Qos1PublishHandler qos1PublishHandler; private Qos1PublishHandler qos1PublishHandler;
@@ -155,23 +155,23 @@ public class ProtocolProcessor {
ProtocolProcessor() { ProtocolProcessor() {
} }
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, public void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator, IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator,
BrokerInterceptor interceptor) { BrokerInterceptor interceptor) {
init(subscriptions, storageService, sessionsStore, authenticator, allowAnonymous, false, authorizator, init(subscriptions, storageService, sessionsStore, authenticator, allowAnonymous, false, authorizator,
interceptor, null); interceptor, null);
} }
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, public void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthorizator authorizator, BrokerInterceptor interceptor) { IAuthorizator authorizator, BrokerInterceptor interceptor) {
init(subscriptions, storageService, sessionsStore, authenticator, allowAnonymous, allowZeroByteClientId, init(subscriptions, storageService, sessionsStore, authenticator, allowAnonymous, allowZeroByteClientId,
authorizator, interceptor, null); authorizator, interceptor, null);
} }
public void init(SubscriptionsStore subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, public void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore,
IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId,
IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) { IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort) {
init(new ConnectionDescriptorStore(sessionsStore), subscriptions, storageService, sessionsStore, authenticator, init(new ConnectionDescriptorStore(sessionsStore), subscriptions, storageService, sessionsStore, authenticator,
allowAnonymous, allowZeroByteClientId, authorizator, interceptor, serverPort); allowAnonymous, allowZeroByteClientId, authorizator, interceptor, serverPort);
} }
@@ -194,7 +194,7 @@ public class ProtocolProcessor {
* @param interceptor * @param interceptor
* to notify events to an intercept handler * to notify events to an intercept handler
*/ */
void init(ConnectionDescriptorStore connectionDescriptors, SubscriptionsStore subscriptions, void init(ConnectionDescriptorStore connectionDescriptors, SubscriptionsDirectory subscriptions,
IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator,
boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator,
BrokerInterceptor interceptor, String serverPort) { BrokerInterceptor interceptor, String serverPort) {
@@ -212,7 +212,7 @@ public class ProtocolProcessor {
m_authenticator = authenticator; m_authenticator = authenticator;
m_messagesStore = storageService; m_messagesStore = storageService;
m_sessionsStore = sessionsStore; m_sessionsStore = sessionsStore;
m_server_port = serverPort; subscriptionStore = sessionsStore.subscriptionStore();
LOG.info("Initializing messages publisher..."); LOG.info("Initializing messages publisher...");
final PersistentQueueMessageSender messageSender = new PersistentQueueMessageSender(this.connectionDescriptors); final PersistentQueueMessageSender messageSender = new PersistentQueueMessageSender(this.connectionDescriptors);
@@ -468,12 +468,11 @@ public class ProtocolProcessor {
LOG.trace("retrieving inflight for messageID <{}>", messageID); LOG.trace("retrieving inflight for messageID <{}>", messageID);
ClientSession targetSession = m_sessionsStore.sessionForClient(clientID); ClientSession targetSession = m_sessionsStore.sessionForClient(clientID);
StoredMessage inflightMsg = targetSession.getInflightMessage(messageID); StoredMessage inflightMsg = targetSession.inFlightAcknowledged(messageID);
targetSession.inFlightAcknowledged(messageID);
String topic = inflightMsg.getTopic(); String topic = inflightMsg.getTopic();
m_interceptor InterceptAcknowledgedMessage wrapped = new InterceptAcknowledgedMessage(inflightMsg, topic, username, messageID);
.notifyMessageAcknowledged(new InterceptAcknowledgedMessage(inflightMsg, topic, username, messageID)); m_interceptor.notifyMessageAcknowledged(wrapped);
} }
public static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg) { public static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg) {
@@ -539,9 +538,9 @@ public class ProtocolProcessor {
} else { } else {
toStoreMsg.setClientID(clientId); toStoreMsg.setClientID(clientId);
} }
if (qos == EXACTLY_ONCE) { // QoS2 // if (qos == EXACTLY_ONCE) { // QoS2
guid = m_messagesStore.storePublishForFuture(toStoreMsg); // guid = m_messagesStore.storePublishForFuture(toStoreMsg);
} // }
this.messagesPublisher.publish2Subscribers(toStoreMsg, topic); this.messagesPublisher.publish2Subscribers(toStoreMsg, topic);
if (!msg.fixedHeader().isRetain()) { if (!msg.fixedHeader().isRetain()) {
@@ -552,11 +551,11 @@ public class ProtocolProcessor {
m_messagesStore.cleanRetained(topic); m_messagesStore.cleanRetained(topic);
return; return;
} }
if (guid == null) { // if (guid == null) {
// before wasn't stored // // before wasn't stored
guid = m_messagesStore.storePublishForFuture(toStoreMsg); // guid = m_messagesStore.storePublishForFuture(toStoreMsg);
} // }
m_messagesStore.storeRetained(topic, guid); m_messagesStore.storeRetained(topic, toStoreMsg);
} }
/** /**
@@ -597,7 +596,8 @@ public class ProtocolProcessor {
ClientSession targetSession = m_sessionsStore.sessionForClient(clientID); ClientSession targetSession = m_sessionsStore.sessionForClient(clientID);
// remove from the inflight and move to the QoS2 second phase queue // remove from the inflight and move to the QoS2 second phase queue
int messageID = messageId(msg); int messageID = messageId(msg);
targetSession.moveInFlightToSecondPhaseAckWaiting(messageID); StoredMessage ackedMsg = targetSession.inFlightAcknowledged(messageID);
targetSession.moveInFlightToSecondPhaseAckWaiting(messageID, ackedMsg);
// once received a PUBREC reply with a PUBREL(messageID) // once received a PUBREC reply with a PUBREL(messageID)
LOG.debug("Processing PUBREC message. CId={}, messageId={}", clientID, messageID); LOG.debug("Processing PUBREC message. CId={}, messageId={}", clientID, messageID);
@@ -678,7 +678,7 @@ public class ProtocolProcessor {
if (descriptor.cleanSession) { if (descriptor.cleanSession) {
LOG.info("Removing saved subscriptions. CId={}", descriptor.clientID); LOG.info("Removing saved subscriptions. CId={}", descriptor.clientID);
m_sessionsStore.wipeSubscriptions(clientID); subscriptionStore.wipeSubscriptions(clientID);
LOG.info("The saved subscriptions have been removed. CId={}", descriptor.clientID); LOG.info("The saved subscriptions have been removed. CId={}", descriptor.clientID);
} }
return true; return true;
@@ -918,9 +918,8 @@ public class ProtocolProcessor {
emptyQueue = true; emptyQueue = true;
} else { } else {
// recreate a publish from stored publish in queue // recreate a publish from stored publish in queue
boolean retained = m_messagesStore.getMessageByGuid(msg.getGuid()) != null;
MqttPublishMessage pubMsg = createPublishForQos( msg.getTopic(), msg.getQos(), msg.getPayload(), MqttPublishMessage pubMsg = createPublishForQos( msg.getTopic(), msg.getQos(), msg.getPayload(),
retained, 0); msg.isRetained(), 0);
channel.write(pubMsg); channel.write(pubMsg);
} }
} }
@@ -25,17 +25,15 @@ import io.moquette.server.config.IResourceLoader;
import io.moquette.spi.IMessagesStore; import io.moquette.spi.IMessagesStore;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.IStore; import io.moquette.spi.IStore;
import io.moquette.spi.impl.security.ACLFileParser; import io.moquette.spi.ISubscriptionsStore;
import io.moquette.spi.impl.security.AcceptAllAuthenticator; import io.moquette.spi.impl.security.*;
import io.moquette.spi.impl.security.DenyAllAuthorizator;
import io.moquette.spi.impl.security.PermitAllAuthorizator;
import io.moquette.spi.impl.security.ResourceAuthenticator;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore; import io.moquette.spi.impl.subscriptions.SubscriptionsDirectory;
import io.moquette.spi.security.IAuthenticator; import io.moquette.spi.security.IAuthenticator;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.text.ParseException; import java.text.ParseException;
@@ -50,16 +48,13 @@ public class ProtocolProcessorBootstrapper {
private static final Logger LOG = LoggerFactory.getLogger(ProtocolProcessorBootstrapper.class); private static final Logger LOG = LoggerFactory.getLogger(ProtocolProcessorBootstrapper.class);
public static final String MAPDB_STORE_CLASS = "io.moquette.persistence.MemoryStorageService"; public static final String MAPDB_STORE_CLASS = "io.moquette.persistence.MemoryStorageService";
private SubscriptionsStore subscriptions;
private ISessionsStore m_sessionsStore; private ISessionsStore m_sessionsStore;
private ISubscriptionsStore subscriptionsStore;
private Runnable storeShutdown; private Runnable storeShutdown;
private BrokerInterceptor m_interceptor;
private final ProtocolProcessor m_processor = new ProtocolProcessor(); private final ProtocolProcessor m_processor = new ProtocolProcessor();
private ConnectionDescriptorStore connectionDescriptors; private ConnectionDescriptorStore connectionDescriptors;
public ProtocolProcessorBootstrapper() { public ProtocolProcessorBootstrapper() {
@@ -86,8 +81,6 @@ public class ProtocolProcessorBootstrapper {
*/ */
public ProtocolProcessor init(IConfig props, List<? extends InterceptHandler> embeddedObservers, public ProtocolProcessor init(IConfig props, List<? extends InterceptHandler> embeddedObservers,
IAuthenticator authenticator, IAuthorizator authorizator, Server server) { IAuthenticator authenticator, IAuthorizator authorizator, Server server) {
subscriptions = new SubscriptionsStore();
IMessagesStore messagesStore; IMessagesStore messagesStore;
LOG.info("Initializing messages and sessions stores..."); LOG.info("Initializing messages and sessions stores...");
String storageClassName = props.getProperty(BrokerConstants.STORAGE_CLASS_NAME, MAPDB_STORE_CLASS); String storageClassName = props.getProperty(BrokerConstants.STORAGE_CLASS_NAME, MAPDB_STORE_CLASS);
@@ -98,6 +91,7 @@ public class ProtocolProcessorBootstrapper {
final IStore store = loadClass(storageClassName, IStore.class, Server.class, server); final IStore store = loadClass(storageClassName, IStore.class, Server.class, server);
messagesStore = store.messagesStore(); messagesStore = store.messagesStore();
m_sessionsStore = store.sessionsStore(); m_sessionsStore = store.sessionsStore();
this.subscriptionsStore = m_sessionsStore.subscriptionStore();
storeShutdown = new Runnable() { storeShutdown = new Runnable() {
@Override @Override
@@ -116,9 +110,10 @@ public class ProtocolProcessorBootstrapper {
observers.add(handler); observers.add(handler);
} }
} }
m_interceptor = new BrokerInterceptor(props, observers); BrokerInterceptor interceptor = new BrokerInterceptor(props, observers);
LOG.info("Initializing subscriptions store..."); LOG.info("Initializing subscriptions store...");
SubscriptionsDirectory subscriptions = new SubscriptionsDirectory();
subscriptions.init(m_sessionsStore); subscriptions.init(m_sessionsStore);
LOG.info("Configuring MQTT authenticator..."); LOG.info("Configuring MQTT authenticator...");
@@ -170,7 +165,7 @@ public class ProtocolProcessorBootstrapper {
boolean allowZeroByteClientId = Boolean boolean allowZeroByteClientId = Boolean
.parseBoolean(props.getProperty(BrokerConstants.ALLOW_ZERO_BYTE_CLIENT_ID_PROPERTY_NAME, "false")); .parseBoolean(props.getProperty(BrokerConstants.ALLOW_ZERO_BYTE_CLIENT_ID_PROPERTY_NAME, "false"));
m_processor.init(connectionDescriptors, subscriptions, messagesStore, m_sessionsStore, authenticator, m_processor.init(connectionDescriptors, subscriptions, messagesStore, m_sessionsStore, authenticator,
allowAnonymous, allowZeroByteClientId, authorizator, m_interceptor, allowAnonymous, allowZeroByteClientId, authorizator, interceptor,
props.getProperty(BrokerConstants.PORT_PROPERTY_NAME)); props.getProperty(BrokerConstants.PORT_PROPERTY_NAME));
return m_processor; return m_processor;
} }
@@ -262,7 +257,7 @@ public class ProtocolProcessorBootstrapper {
} }
public List<Subscription> getSubscriptions() { public List<Subscription> getSubscriptions() {
return m_sessionsStore.getSubscriptions(); return this.subscriptionsStore.getSubscriptions();
} }
public void shutdown() { public void shutdown() {
@@ -19,9 +19,6 @@ package io.moquette.spi.impl;
import io.moquette.server.ConnectionDescriptorStore; import io.moquette.server.ConnectionDescriptorStore;
import io.moquette.server.netty.NettyUtils; import io.moquette.server.netty.NettyUtils;
import io.moquette.spi.IMessagesStore; import io.moquette.spi.IMessagesStore;
import io.moquette.spi.MessageGUID;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
import io.netty.channel.Channel; import io.netty.channel.Channel;
@@ -31,7 +28,7 @@ import io.netty.handler.codec.mqtt.MqttPubAckMessage;
import io.netty.handler.codec.mqtt.MqttPublishMessage; import io.netty.handler.codec.mqtt.MqttPublishMessage;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage; import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from; import static io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader.from;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE; import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
@@ -79,11 +76,7 @@ class Qos1PublishHandler extends QosPublishHandler {
m_messagesStore.cleanRetained(topic); m_messagesStore.cleanRetained(topic);
} else { } else {
// before wasn't stored // before wasn't stored
MessageGUID guid = m_messagesStore.storePublishForFuture(toStoreMsg); m_messagesStore.storeRetained(topic, toStoreMsg);
//TODO Il messaggio non ha il guid settato
// m_messagesStore.storeRetained(topic, toStoreMsg.getGuid());
m_messagesStore.storeRetained(topic, guid);
} }
} }
@@ -21,16 +21,13 @@ import io.moquette.server.netty.NettyUtils;
import io.moquette.spi.ClientSession; import io.moquette.spi.ClientSession;
import io.moquette.spi.IMessagesStore; import io.moquette.spi.IMessagesStore;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.MessageGUID; import io.moquette.spi.impl.subscriptions.SubscriptionsDirectory;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.*; import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
import static io.moquette.spi.impl.DebugUtils.payload2Str; import static io.moquette.spi.impl.DebugUtils.payload2Str;
import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage; import static io.moquette.spi.impl.ProtocolProcessor.asStoredMessage;
@@ -42,14 +39,14 @@ class Qos2PublishHandler extends QosPublishHandler {
private static final Logger LOG = LoggerFactory.getLogger(Qos2PublishHandler.class); private static final Logger LOG = LoggerFactory.getLogger(Qos2PublishHandler.class);
private final SubscriptionsStore subscriptions; private final SubscriptionsDirectory subscriptions;
private final IMessagesStore m_messagesStore; private final IMessagesStore m_messagesStore;
private final BrokerInterceptor m_interceptor; private final BrokerInterceptor m_interceptor;
private final ConnectionDescriptorStore connectionDescriptors; private final ConnectionDescriptorStore connectionDescriptors;
private final ISessionsStore m_sessionsStore; private final ISessionsStore m_sessionsStore;
private final MessagesPublisher publisher; private final MessagesPublisher publisher;
public Qos2PublishHandler(IAuthorizator authorizator, SubscriptionsStore subscriptions, public Qos2PublishHandler(IAuthorizator authorizator, SubscriptionsDirectory subscriptions,
IMessagesStore messagesStore, BrokerInterceptor interceptor, IMessagesStore messagesStore, BrokerInterceptor interceptor,
ConnectionDescriptorStore connectionDescriptors, ISessionsStore sessionsStore, ConnectionDescriptorStore connectionDescriptors, ISessionsStore sessionsStore,
MessagesPublisher messagesPublisher) { MessagesPublisher messagesPublisher) {
@@ -81,23 +78,22 @@ class Qos2PublishHandler extends QosPublishHandler {
LOG.trace("payload={}, subs Tree={}", payload2Str(toStoreMsg.getPayload()), subscriptions.dumpTree()); LOG.trace("payload={}, subs Tree={}", payload2Str(toStoreMsg.getPayload()), subscriptions.dumpTree());
} }
// QoS2 m_sessionsStore.sessionForClient(clientID)
MessageGUID guid = m_messagesStore.storePublishForFuture(toStoreMsg); .markAsInboundInflight(messageID, toStoreMsg);
ClientSession sourceSession = m_sessionsStore.sessionForClient(clientID);
sourceSession.markAsInboundInflight(messageID, guid);
sendPubRec(clientID, messageID); sendPubRec(clientID, messageID);
// Next the client will send us a pub rel // Next the client will send us a pub rel
// NB publish to subscribers for QoS 2 happen upon PUBREL from publisher // NB publish to subscribers for QoS 2 happen upon PUBREL from publisher
if (msg.fixedHeader().isRetain()) { // if (msg.fixedHeader().isRetain()) {
if (msg.payload().readableBytes() == 0) { // if (msg.payload().readableBytes() == 0) {
m_messagesStore.cleanRetained(topic); // m_messagesStore.cleanRetained(topic);
} else { // } else {
m_messagesStore.storeRetained(topic, guid); // m_messagesStore.storeRetained(topic, toStoreMsg);
} // }
} // }
//TODO this should happen on PUB_REL, else we notify false positive
m_interceptor.notifyTopicPublished(msg, clientID, username); m_interceptor.notifyTopicPublished(msg, clientID, username);
} }
@@ -123,10 +119,13 @@ class Qos2PublishHandler extends QosPublishHandler {
if (evt.getPayload().readableBytes() == 0) { if (evt.getPayload().readableBytes() == 0) {
m_messagesStore.cleanRetained(topic); m_messagesStore.cleanRetained(topic);
} else { } else {
m_messagesStore.storeRetained(topic, evt.getGuid()); m_messagesStore.storeRetained(topic, evt);
} }
} }
//TODO here we should notify to the listeners
//m_interceptor.notifyTopicPublished(msg, clientID, username);
sendPubComp(clientID, messageID); sendPubComp(clientID, messageID);
} }
@@ -16,7 +16,7 @@
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISubscriptionsStore.ClientTopicCouple;
import io.netty.handler.codec.mqtt.MqttQoS; import io.netty.handler.codec.mqtt.MqttQoS;
import java.io.Serializable; import java.io.Serializable;
@@ -17,7 +17,8 @@
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISubscriptionsStore;
import io.moquette.spi.ISubscriptionsStore.ClientTopicCouple;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*; import java.util.*;
@@ -27,7 +28,7 @@ import java.util.concurrent.atomic.AtomicReference;
/** /**
* Represents a tree of topics subscriptions. * Represents a tree of topics subscriptions.
*/ */
public class SubscriptionsStore { public class SubscriptionsDirectory {
public static class NodeCouple { public static class NodeCouple {
@@ -79,8 +80,9 @@ public class SubscriptionsStore {
} }
private AtomicReference<TreeNode> subscriptions = new AtomicReference<>(new TreeNode()); private AtomicReference<TreeNode> subscriptions = new AtomicReference<>(new TreeNode());
private static final Logger LOG = LoggerFactory.getLogger(SubscriptionsStore.class); private static final Logger LOG = LoggerFactory.getLogger(SubscriptionsDirectory.class);
private volatile ISessionsStore m_sessionsStore; private volatile ISessionsStore m_sessionsStore;
private volatile ISubscriptionsStore subscriptionsStore;
/** /**
* Initialize the subscription tree with the list of subscriptions. Maintained for compatibility * Initialize the subscription tree with the list of subscriptions. Maintained for compatibility
@@ -92,21 +94,20 @@ public class SubscriptionsStore {
public void init(ISessionsStore sessionsStore) { public void init(ISessionsStore sessionsStore) {
LOG.info("Initializing subscriptions store..."); LOG.info("Initializing subscriptions store...");
m_sessionsStore = sessionsStore; m_sessionsStore = sessionsStore;
List<ClientTopicCouple> subscriptions = sessionsStore.listAllSubscriptions(); this.subscriptionsStore = sessionsStore.subscriptionStore();
List<ClientTopicCouple> subscriptions = this.subscriptionsStore.listAllSubscriptions();
// reload any subscriptions persisted // reload any subscriptions persisted
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("Reloading all stored subscriptions. SubscriptionTree = {}.", dumpTree()); LOG.trace("Reloading all stored subscriptions. SubscriptionTree = {}", dumpTree());
} }
for (ClientTopicCouple clientTopic : subscriptions) { for (ClientTopicCouple clientTopic : subscriptions) {
LOG.info( LOG.info("Re-subscribing client to topic CId={}, topicFilter={}", clientTopic.clientID,
"Re-subscribing client to topic. ClientId = {}, topicFilter = {}.", clientTopic.topicFilter);
clientTopic.clientID,
clientTopic.topicFilter);
add(clientTopic); add(clientTopic);
} }
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("The stored subscriptions have been reloaded. SubscriptionTree = {}.", dumpTree()); LOG.trace("Stored subscriptions have been reloaded. SubscriptionTree = {}", dumpTree());
} }
} }
@@ -204,7 +205,7 @@ public class SubscriptionsStore {
Map<String, Subscription> subsForClient = new HashMap<>(); Map<String, Subscription> subsForClient = new HashMap<>();
for (ClientTopicCouple matchingCouple : matchingSubs) { for (ClientTopicCouple matchingCouple : matchingSubs) {
Subscription existingSub = subsForClient.get(matchingCouple.clientID); Subscription existingSub = subsForClient.get(matchingCouple.clientID);
Subscription sub = m_sessionsStore.getSubscription(matchingCouple); Subscription sub = this.subscriptionsStore.getSubscription(matchingCouple);
if (sub == null) { if (sub == null) {
// if the m_sessionStore hasn't the sub because the client disconnected // if the m_sessionStore hasn't the sub because the client disconnected
continue; continue;
@@ -16,7 +16,7 @@
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISubscriptionsStore.ClientTopicCouple;
import java.util.*; import java.util.*;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
@@ -0,0 +1,92 @@
package io.moquette.persistence;
import io.moquette.spi.*;
import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.ISubscriptionsStore.ClientTopicCouple;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.junit.Test;
import java.util.List;
import static io.moquette.spi.impl.subscriptions.Topic.asTopic;
import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE;
import static io.netty.handler.codec.mqtt.MqttQoS.EXACTLY_ONCE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Defines all test that an implementation of a IMessageStore should satisfy.
* */
public abstract class MessageStoreTCK {
public static final String TEST_CLIENT = "TestClient";
protected ISessionsStore sessionsStore;
protected IMessagesStore messagesStore;
@Test
public void testDropMessagesInSessionDoesntCleanAnyRetainedStoredMessages() {
final ClientSession session = sessionsStore.createNewSession(TEST_CLIENT, true);
StoredMessage publishToStore = new StoredMessage("Hello".getBytes(), EXACTLY_ONCE, "/topic");
publishToStore.setClientID(TEST_CLIENT);
publishToStore.setRetained(true);
messagesStore.storeRetained(new Topic("/topic"), publishToStore);
// Exercise
session.cleanSession();
// Verify the message store for session is empty.
StoredMessage storedPublish = messagesStore.searchMatching(new IMatchingCondition() {
@Override
public boolean match(Topic key) {
return key.match(new Topic("/topic"));
}
}).iterator().next();
assertNotNull("The stored retained message must be present after client's session drop", storedPublish);
}
@Test
public void testStoreRetained() {
StoredMessage msgStored = new StoredMessage("Hello".getBytes(), MqttQoS.AT_LEAST_ONCE, "/topic");
msgStored.setClientID(TEST_CLIENT);
messagesStore.storeRetained(asTopic("/topic"), msgStored);
//Verify the message is in the store
StoredMessage msgRetrieved = messagesStore.searchMatching(new IMatchingCondition() {
@Override
public boolean match(Topic key) {
return key.match(new Topic("/topic"));
}
}).iterator().next();
final ByteBuf payload = msgRetrieved.getPayload();
byte[] content = new byte[payload.readableBytes()];
payload.readBytes(content);
assertEquals("Hello", new String(content));
}
@Test
public void givenSubscriptionAlreadyStoredIsOverwrittenByAnotherWithSameTopic() {
ClientSession session1 = sessionsStore.createNewSession("SESSION_ID_1", true);
// Subscribe on /topic with QOSType.MOST_ONE
Subscription oldSubscription = new Subscription(session1.clientID, new Topic("/topic"), AT_MOST_ONCE);
session1.subscribe(oldSubscription);
// Subscribe on /topic again that overrides the previous subscription.
Subscription overridingSubscription = new Subscription(session1.clientID, new Topic("/topic"), EXACTLY_ONCE);
session1.subscribe(overridingSubscription);
// Verify
final ISubscriptionsStore subscriptionsStore = sessionsStore.subscriptionStore();
List<ClientTopicCouple> subscriptions = subscriptionsStore.listAllSubscriptions();
assertEquals(1, subscriptions.size());
Subscription sub = subscriptionsStore.getSubscription(subscriptions.get(0));
assertEquals(overridingSubscription.getRequestedQos(), sub.getRequestedQos());
}
}
@@ -18,7 +18,7 @@ package io.moquette.spi;
import io.moquette.persistence.MemoryStorageService; import io.moquette.persistence.MemoryStorageService;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore; import io.moquette.spi.impl.subscriptions.SubscriptionsDirectory;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import static io.netty.handler.codec.mqtt.MqttQoS.*; import static io.netty.handler.codec.mqtt.MqttQoS.*;
import org.junit.Before; import org.junit.Before;
@@ -31,11 +31,11 @@ public class ClientSessionTest {
ClientSession session1; ClientSession session1;
ClientSession session2; ClientSession session2;
ISessionsStore sessionsStore; ISessionsStore sessionsStore;
SubscriptionsStore store; SubscriptionsDirectory store;
@Before @Before
public void setUp() { public void setUp() {
store = new SubscriptionsStore(); store = new SubscriptionsDirectory();
MemoryStorageService storageService = new MemoryStorageService(); MemoryStorageService storageService = new MemoryStorageService();
this.sessionsStore = storageService.sessionsStore(); this.sessionsStore = storageService.sessionsStore();
store.init(sessionsStore); store.init(sessionsStore);
@@ -26,7 +26,7 @@ import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.impl.security.PermitAllAuthorizator; import io.moquette.spi.impl.security.PermitAllAuthorizator;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore; import io.moquette.spi.impl.subscriptions.SubscriptionsDirectory;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import io.moquette.spi.security.IAuthorizator; import io.moquette.spi.security.IAuthorizator;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
@@ -62,7 +62,7 @@ public class ProtocolProcessorTest {
IMessagesStore m_messagesStore; IMessagesStore m_messagesStore;
ISessionsStore m_sessionStore; ISessionsStore m_sessionStore;
SubscriptionsStore subscriptions; SubscriptionsDirectory subscriptions;
MockAuthenticator m_mockAuthenticator; MockAuthenticator m_mockAuthenticator;
@Before @Before
@@ -92,7 +92,7 @@ public class ProtocolProcessorTest {
users.put(TEST_USER, TEST_PWD); users.put(TEST_USER, TEST_PWD);
m_mockAuthenticator = new MockAuthenticator(clientIds, users); m_mockAuthenticator = new MockAuthenticator(clientIds, users);
subscriptions = new SubscriptionsStore(); subscriptions = new SubscriptionsDirectory();
subscriptions.init(memStorage.sessionsStore()); subscriptions.init(memStorage.sessionsStore());
m_processor = new ProtocolProcessor(); m_processor = new ProtocolProcessor();
m_processor.init(subscriptions, m_messagesStore, m_sessionStore, m_mockAuthenticator, true, m_processor.init(subscriptions, m_messagesStore, m_sessionStore, m_mockAuthenticator, true,
@@ -104,7 +104,7 @@ public class ProtocolProcessorTest {
final Subscription subscription = new Subscription(FAKE_CLIENT_ID, new Topic(FAKE_TOPIC), MqttQoS.AT_MOST_ONCE); final Subscription subscription = new Subscription(FAKE_CLIENT_ID, new Topic(FAKE_TOPIC), MqttQoS.AT_MOST_ONCE);
// subscriptions.matches(topic) redefine the method to return true // subscriptions.matches(topic) redefine the method to return true
SubscriptionsStore subs = new SubscriptionsStore() { SubscriptionsDirectory subs = new SubscriptionsDirectory() {
@Override @Override
public List<Subscription> matches(Topic topic) { public List<Subscription> matches(Topic topic) {
@@ -152,7 +152,7 @@ public class ProtocolProcessorTest {
MqttQoS.AT_MOST_ONCE); MqttQoS.AT_MOST_ONCE);
// subscriptions.matches(topic) redefine the method to return true // subscriptions.matches(topic) redefine the method to return true
SubscriptionsStore subs = new SubscriptionsStore() { SubscriptionsDirectory subs = new SubscriptionsDirectory() {
@Override @Override
public List<Subscription> matches(Topic topic) { public List<Subscription> matches(Topic topic) {
@@ -311,7 +311,7 @@ public class ProtocolProcessorTest {
new Subscription(FAKE_PUBLISHER_ID, new Topic(FAKE_TOPIC), MqttQoS.AT_MOST_ONCE); new Subscription(FAKE_PUBLISHER_ID, new Topic(FAKE_TOPIC), MqttQoS.AT_MOST_ONCE);
// subscriptions.matches(topic) redefine the method to return true // subscriptions.matches(topic) redefine the method to return true
SubscriptionsStore subs = new SubscriptionsStore() { SubscriptionsDirectory subs = new SubscriptionsDirectory() {
@Override @Override
public List<Subscription> matches(Topic topic) { public List<Subscription> matches(Topic topic) {
@@ -355,14 +355,14 @@ public class ProtocolProcessorTest {
@Test @Test
public void testRepublishAndConsumePersistedMessages_onReconnect() { public void testRepublishAndConsumePersistedMessages_onReconnect() {
SubscriptionsStore subs = mock(SubscriptionsStore.class); SubscriptionsDirectory subs = mock(SubscriptionsDirectory.class);
List<Subscription> emptySubs = Collections.emptyList(); List<Subscription> emptySubs = Collections.emptyList();
when(subs.matches(any(Topic.class))).thenReturn(emptySubs); when(subs.matches(any(Topic.class))).thenReturn(emptySubs);
StoredMessage retainedMessage = new StoredMessage("Hello".getBytes(), MqttQoS.EXACTLY_ONCE, "/topic"); StoredMessage retainedMessage = new StoredMessage("Hello".getBytes(), MqttQoS.EXACTLY_ONCE, "/topic");
retainedMessage.setRetained(true); retainedMessage.setRetained(true);
retainedMessage.setClientID(FAKE_PUBLISHER_ID); retainedMessage.setClientID(FAKE_PUBLISHER_ID);
m_messagesStore.storePublishForFuture(retainedMessage); m_messagesStore.storeRetained(new Topic("/topic"), retainedMessage);
m_processor.init(subs, m_messagesStore, m_sessionStore, null, true, new PermitAllAuthorizator(), m_processor.init(subs, m_messagesStore, m_sessionStore, null, true, new PermitAllAuthorizator(),
NO_OBSERVERS_INTERCEPTOR); NO_OBSERVERS_INTERCEPTOR);
@@ -382,7 +382,7 @@ public class ProtocolProcessorTest {
// create an inactive session for Subscriber // create an inactive session for Subscriber
m_sessionStore.createNewSession("Subscriber", false); m_sessionStore.createNewSession("Subscriber", false);
SubscriptionsStore mockedSubscriptions = mock(SubscriptionsStore.class); SubscriptionsDirectory mockedSubscriptions = mock(SubscriptionsDirectory.class);
Subscription inactiveSub = new Subscription("Subscriber", new Topic("/topic"), MqttQoS.AT_LEAST_ONCE); Subscription inactiveSub = new Subscription("Subscriber", new Topic("/topic"), MqttQoS.AT_LEAST_ONCE);
List<Subscription> inactiveSubscriptions = Collections.singletonList(inactiveSub); List<Subscription> inactiveSubscriptions = Collections.singletonList(inactiveSub);
when(mockedSubscriptions.matches(eq(new Topic("/topic")))).thenReturn(inactiveSubscriptions); when(mockedSubscriptions.matches(eq(new Topic("/topic")))).thenReturn(inactiveSubscriptions);
@@ -24,7 +24,7 @@ import io.moquette.spi.IMessagesStore;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.impl.security.PermitAllAuthorizator; import io.moquette.spi.impl.security.PermitAllAuthorizator;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.SubscriptionsStore; import io.moquette.spi.impl.subscriptions.SubscriptionsDirectory;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.mqtt.MqttConnectMessage; import io.netty.handler.codec.mqtt.MqttConnectMessage;
@@ -51,7 +51,7 @@ public class ProtocolProcessor_CONNECT_Test {
IMessagesStore m_messagesStore; IMessagesStore m_messagesStore;
ISessionsStore m_sessionStore; ISessionsStore m_sessionStore;
SubscriptionsStore subscriptions; SubscriptionsDirectory subscriptions;
MockAuthenticator m_mockAuthenticator; MockAuthenticator m_mockAuthenticator;
@Before @Before
@@ -73,7 +73,7 @@ public class ProtocolProcessor_CONNECT_Test {
users.put(ProtocolProcessorTest.TEST_USER, ProtocolProcessorTest.TEST_PWD); users.put(ProtocolProcessorTest.TEST_USER, ProtocolProcessorTest.TEST_PWD);
m_mockAuthenticator = new MockAuthenticator(clientIds, users); m_mockAuthenticator = new MockAuthenticator(clientIds, users);
subscriptions = new SubscriptionsStore(); subscriptions = new SubscriptionsDirectory();
subscriptions.init(m_sessionStore); subscriptions.init(m_sessionStore);
m_processor = new ProtocolProcessor(); m_processor = new ProtocolProcessor();
m_processor.init( m_processor.init(
@@ -16,42 +16,48 @@
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
import io.moquette.persistence.MemoryStorageService;
import io.moquette.spi.ClientSession; import io.moquette.spi.ClientSession;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.ISessionsStore.ClientTopicCouple; import io.moquette.spi.ISubscriptionsStore;
import io.moquette.persistence.MemoryStorageService; import io.moquette.spi.ISubscriptionsStore.ClientTopicCouple;
import io.netty.handler.codec.mqtt.MqttQoS; import io.netty.handler.codec.mqtt.MqttQoS;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.*;
public class SubscriptionsStoreTest { import static org.assertj.core.api.Assertions.assertThat;
private SubscriptionsStore store; public class SubscriptionsDirectoryTest {
private SubscriptionsDirectory store;
private ISessionsStore sessionsStore; private ISessionsStore sessionsStore;
private ISubscriptionsStore subscriptionsStore;
public SubscriptionsStoreTest() { public SubscriptionsDirectoryTest() {
} }
@Before @Before
public void setUp() throws IOException { public void setUp() throws IOException {
store = new SubscriptionsStore(); store = new SubscriptionsDirectory();
MemoryStorageService storageService = new MemoryStorageService(); MemoryStorageService storageService = new MemoryStorageService();
this.sessionsStore = storageService.sessionsStore(); this.sessionsStore = storageService.sessionsStore();
store.init(sessionsStore); store.init(sessionsStore);
this.subscriptionsStore = this.sessionsStore.subscriptionStore();
} }
@Test @Test
public void testMatchSimple() { public void testMatchSimple() {
Subscription slashSub = new Subscription("FAKE_CLI_ID_1", new Topic("/"), MqttQoS.AT_MOST_ONCE); Subscription slashSub = new Subscription("FAKE_CLI_ID_1", new Topic("/"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(slashSub); this.subscriptionsStore.addNewSubscription(slashSub);
store.add(slashSub.asClientTopicCouple()); store.add(slashSub.asClientTopicCouple());
assertThat(store.matches(new Topic("finance"))).isEmpty(); assertThat(store.matches(new Topic("finance"))).isEmpty();
Subscription slashFinanceSub = new Subscription("FAKE_CLI_ID_1", new Topic("/finance"), MqttQoS.AT_MOST_ONCE); Subscription slashFinanceSub = new Subscription("FAKE_CLI_ID_1", new Topic("/finance"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(slashFinanceSub); this.subscriptionsStore.addNewSubscription(slashFinanceSub);
store.add(slashFinanceSub.asClientTopicCouple()); store.add(slashFinanceSub.asClientTopicCouple());
assertThat(store.matches(new Topic("finance"))).isEmpty(); assertThat(store.matches(new Topic("finance"))).isEmpty();
@@ -62,12 +68,12 @@ public class SubscriptionsStoreTest {
@Test @Test
public void testMatchSimpleMulti() { public void testMatchSimpleMulti() {
Subscription anySub = new Subscription("FAKE_CLI_ID_1", new Topic("#"), MqttQoS.AT_MOST_ONCE); Subscription anySub = new Subscription("FAKE_CLI_ID_1", new Topic("#"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(anySub); this.subscriptionsStore.addNewSubscription(anySub);
store.add(anySub.asClientTopicCouple()); store.add(anySub.asClientTopicCouple());
assertThat(store.matches(new Topic("finance"))).contains(anySub); assertThat(store.matches(new Topic("finance"))).contains(anySub);
Subscription financeAnySub = new Subscription("FAKE_CLI_ID_2", new Topic("finance/#"), MqttQoS.AT_MOST_ONCE); Subscription financeAnySub = new Subscription("FAKE_CLI_ID_2", new Topic("finance/#"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(financeAnySub); this.subscriptionsStore.addNewSubscription(financeAnySub);
store.add(financeAnySub.asClientTopicCouple()); store.add(financeAnySub.asClientTopicCouple());
assertThat(store.matches(new Topic("finance"))).containsExactlyInAnyOrder(financeAnySub, anySub); assertThat(store.matches(new Topic("finance"))).containsExactlyInAnyOrder(financeAnySub, anySub);
} }
@@ -76,8 +82,8 @@ public class SubscriptionsStoreTest {
public void testMatchingDeepMulti_one_layer() { public void testMatchingDeepMulti_one_layer() {
Subscription anySub = new Subscription("FAKE_CLI_ID_1", new Topic("#"), MqttQoS.AT_MOST_ONCE); Subscription anySub = new Subscription("FAKE_CLI_ID_1", new Topic("#"), MqttQoS.AT_MOST_ONCE);
Subscription financeAnySub = new Subscription("FAKE_CLI_ID_2", new Topic("finance/#"), MqttQoS.AT_MOST_ONCE); Subscription financeAnySub = new Subscription("FAKE_CLI_ID_2", new Topic("finance/#"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(anySub); this.subscriptionsStore.addNewSubscription(anySub);
sessionsStore.addNewSubscription(financeAnySub); this.subscriptionsStore.addNewSubscription(financeAnySub);
store.add(anySub.asClientTopicCouple()); store.add(anySub.asClientTopicCouple());
store.add(financeAnySub.asClientTopicCouple()); store.add(financeAnySub.asClientTopicCouple());
@@ -92,7 +98,7 @@ public class SubscriptionsStoreTest {
"FAKE_CLI_ID_1", "FAKE_CLI_ID_1",
new Topic("finance/stock/#"), new Topic("finance/stock/#"),
MqttQoS.AT_MOST_ONCE); MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(financeAnySub); this.subscriptionsStore.addNewSubscription(financeAnySub);
store.add(financeAnySub.asClientTopicCouple()); store.add(financeAnySub.asClientTopicCouple());
// Verify // Verify
@@ -102,12 +108,12 @@ public class SubscriptionsStoreTest {
@Test @Test
public void testMatchSimpleSingle() { public void testMatchSimpleSingle() {
Subscription anySub = new Subscription("FAKE_CLI_ID_1", new Topic("+"), MqttQoS.AT_MOST_ONCE); Subscription anySub = new Subscription("FAKE_CLI_ID_1", new Topic("+"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(anySub); this.subscriptionsStore.addNewSubscription(anySub);
store.add(anySub.asClientTopicCouple()); store.add(anySub.asClientTopicCouple());
assertThat(store.matches(new Topic("finance"))).containsExactly(anySub); assertThat(store.matches(new Topic("finance"))).containsExactly(anySub);
Subscription financeOne = new Subscription("FAKE_CLI_ID_1", new Topic("finance/+"), MqttQoS.AT_MOST_ONCE); Subscription financeOne = new Subscription("FAKE_CLI_ID_1", new Topic("finance/+"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(financeOne); this.subscriptionsStore.addNewSubscription(financeOne);
store.add(financeOne.asClientTopicCouple()); store.add(financeOne.asClientTopicCouple());
assertThat(store.matches(new Topic("finance/stock"))).containsExactly(financeOne); assertThat(store.matches(new Topic("finance/stock"))).containsExactly(financeOne);
} }
@@ -115,7 +121,7 @@ public class SubscriptionsStoreTest {
@Test @Test
public void testMatchManySingle() { public void testMatchManySingle() {
Subscription manySub = new Subscription("FAKE_CLI_ID_1", new Topic("+/+"), MqttQoS.AT_MOST_ONCE); Subscription manySub = new Subscription("FAKE_CLI_ID_1", new Topic("+/+"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(manySub); this.subscriptionsStore.addNewSubscription(manySub);
store.add(manySub.asClientTopicCouple()); store.add(manySub.asClientTopicCouple());
// verify // verify
@@ -125,10 +131,10 @@ public class SubscriptionsStoreTest {
@Test @Test
public void testMatchSlashSingle() { public void testMatchSlashSingle() {
Subscription slashPlusSub = new Subscription("FAKE_CLI_ID_1", new Topic("/+"), MqttQoS.AT_MOST_ONCE); Subscription slashPlusSub = new Subscription("FAKE_CLI_ID_1", new Topic("/+"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(slashPlusSub); this.subscriptionsStore.addNewSubscription(slashPlusSub);
store.add(slashPlusSub.asClientTopicCouple()); store.add(slashPlusSub.asClientTopicCouple());
Subscription anySub = new Subscription("FAKE_CLI_ID_1", new Topic("+"), MqttQoS.AT_MOST_ONCE); Subscription anySub = new Subscription("FAKE_CLI_ID_1", new Topic("+"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(anySub); this.subscriptionsStore.addNewSubscription(anySub);
store.add(anySub.asClientTopicCouple()); store.add(anySub.asClientTopicCouple());
// Verify // Verify
@@ -142,14 +148,14 @@ public class SubscriptionsStoreTest {
"FAKE_CLI_ID_1", "FAKE_CLI_ID_1",
new Topic("/finance/+/ibm"), new Topic("/finance/+/ibm"),
MqttQoS.AT_MOST_ONCE); MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(slashPlusSub); this.subscriptionsStore.addNewSubscription(slashPlusSub);
store.add(slashPlusSub.asClientTopicCouple()); store.add(slashPlusSub.asClientTopicCouple());
Subscription slashPlusDeepSub = new Subscription( Subscription slashPlusDeepSub = new Subscription(
"FAKE_CLI_ID_2", "FAKE_CLI_ID_2",
new Topic("/+/stock/+"), new Topic("/+/stock/+"),
MqttQoS.AT_MOST_ONCE); MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(slashPlusDeepSub); this.subscriptionsStore.addNewSubscription(slashPlusDeepSub);
store.add(slashPlusDeepSub.asClientTopicCouple()); store.add(slashPlusDeepSub.asClientTopicCouple());
// Verify // Verify
@@ -160,7 +166,7 @@ public class SubscriptionsStoreTest {
@Test @Test
public void testMatchSimpleMulti_allTheTree() { public void testMatchSimpleMulti_allTheTree() {
Subscription sub = new Subscription("FAKE_CLI_ID_1", new Topic("#"), MqttQoS.AT_MOST_ONCE); Subscription sub = new Subscription("FAKE_CLI_ID_1", new Topic("#"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(sub); this.subscriptionsStore.addNewSubscription(sub);
store.add(sub.asClientTopicCouple()); store.add(sub.asClientTopicCouple());
assertThat(store.matches(new Topic("finance"))).isNotEmpty(); assertThat(store.matches(new Topic("finance"))).isNotEmpty();
assertThat(store.matches(new Topic("finance/ibm"))).isNotEmpty(); assertThat(store.matches(new Topic("finance/ibm"))).isNotEmpty();
@@ -170,7 +176,7 @@ public class SubscriptionsStoreTest {
public void testMatchSimpleMulti_zeroLevel() { public void testMatchSimpleMulti_zeroLevel() {
// check MULTI in case of zero level match // check MULTI in case of zero level match
Subscription sub = new Subscription("FAKE_CLI_ID_1", new Topic("finance/#"), MqttQoS.AT_MOST_ONCE); Subscription sub = new Subscription("FAKE_CLI_ID_1", new Topic("finance/#"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(sub); this.subscriptionsStore.addNewSubscription(sub);
store.add(sub.asClientTopicCouple()); store.add(sub.asClientTopicCouple());
assertThat(store.matches(new Topic("finance"))).isNotEmpty(); assertThat(store.matches(new Topic("finance"))).isNotEmpty();
} }
@@ -202,12 +208,12 @@ public class SubscriptionsStoreTest {
private void assertMatch(String s, String t) { private void assertMatch(String s, String t) {
Topic subscription = new Topic(s); Topic subscription = new Topic(s);
Topic topic = new Topic(t); Topic topic = new Topic(t);
store = new SubscriptionsStore(); store = new SubscriptionsDirectory();
MemoryStorageService memStore = new MemoryStorageService(); MemoryStorageService memStore = new MemoryStorageService();
ISessionsStore aSessionsStore = memStore.sessionsStore(); ISessionsStore aSessionsStore = memStore.sessionsStore();
store.init(aSessionsStore); store.init(aSessionsStore);
Subscription sub = new Subscription("FAKE_CLI_ID_1", subscription, MqttQoS.AT_MOST_ONCE); Subscription sub = new Subscription("FAKE_CLI_ID_1", subscription, MqttQoS.AT_MOST_ONCE);
aSessionsStore.addNewSubscription(sub); aSessionsStore.subscriptionStore().addNewSubscription(sub);
store.add(sub.asClientTopicCouple()); store.add(sub.asClientTopicCouple());
assertThat(store.matches(topic)).isNotEmpty(); assertThat(store.matches(topic)).isNotEmpty();
} }
@@ -215,11 +221,11 @@ public class SubscriptionsStoreTest {
private void assertNotMatch(String s, String t) { private void assertNotMatch(String s, String t) {
Topic subscription = new Topic(s); Topic subscription = new Topic(s);
Topic topic = new Topic(t); Topic topic = new Topic(t);
store = new SubscriptionsStore(); store = new SubscriptionsDirectory();
MemoryStorageService memStore = new MemoryStorageService(); MemoryStorageService memStore = new MemoryStorageService();
store.init(memStore.sessionsStore()); store.init(memStore.sessionsStore());
Subscription sub = new Subscription("FAKE_CLI_ID_1", subscription, MqttQoS.AT_MOST_ONCE); Subscription sub = new Subscription("FAKE_CLI_ID_1", subscription, MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(sub); this.subscriptionsStore.addNewSubscription(sub);
store.add(sub.asClientTopicCouple()); store.add(sub.asClientTopicCouple());
assertThat(store.matches(topic)).isEmpty(); assertThat(store.matches(topic)).isEmpty();
} }
@@ -228,7 +234,7 @@ public class SubscriptionsStoreTest {
public void testRemoveClientSubscriptions_existingClientID() { public void testRemoveClientSubscriptions_existingClientID() {
String cliendID = "FAKE_CLID_1"; String cliendID = "FAKE_CLID_1";
Subscription sub = new Subscription(cliendID, new Topic("finance/#"), MqttQoS.AT_MOST_ONCE); Subscription sub = new Subscription(cliendID, new Topic("finance/#"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(sub); this.subscriptionsStore.addNewSubscription(sub);
store.add(sub.asClientTopicCouple()); store.add(sub.asClientTopicCouple());
// Exercise // Exercise
@@ -242,7 +248,7 @@ public class SubscriptionsStoreTest {
public void testRemoveClientSubscriptions_notexistingClientID() { public void testRemoveClientSubscriptions_notexistingClientID() {
String clientID = "FAKE_CLID_1"; String clientID = "FAKE_CLID_1";
Subscription s = new Subscription(clientID, new Topic("finance/#"), MqttQoS.AT_MOST_ONCE); Subscription s = new Subscription(clientID, new Topic("finance/#"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(s); this.subscriptionsStore.addNewSubscription(s);
store.add(s.asClientTopicCouple()); store.add(s.asClientTopicCouple());
// Exercise // Exercise
@@ -255,10 +261,10 @@ public class SubscriptionsStoreTest {
@Test @Test
public void testOverlappingSubscriptions() { public void testOverlappingSubscriptions() {
Subscription genericSub = new Subscription("FAKE_CLI_ID_1", new Topic("a/+"), MqttQoS.EXACTLY_ONCE); Subscription genericSub = new Subscription("FAKE_CLI_ID_1", new Topic("a/+"), MqttQoS.EXACTLY_ONCE);
sessionsStore.addNewSubscription(genericSub); this.subscriptionsStore.addNewSubscription(genericSub);
store.add(genericSub.asClientTopicCouple()); store.add(genericSub.asClientTopicCouple());
Subscription specificSub = new Subscription("FAKE_CLI_ID_1", new Topic("a/b"), MqttQoS.AT_LEAST_ONCE); Subscription specificSub = new Subscription("FAKE_CLI_ID_1", new Topic("a/b"), MqttQoS.AT_LEAST_ONCE);
sessionsStore.addNewSubscription(specificSub); this.subscriptionsStore.addNewSubscription(specificSub);
store.add(specificSub.asClientTopicCouple()); store.add(specificSub.asClientTopicCouple());
// Verify // Verify
@@ -267,19 +273,19 @@ public class SubscriptionsStoreTest {
@Test @Test
public void removeSubscription_withDifferentClients_subscribedSameTopic() { public void removeSubscription_withDifferentClients_subscribedSameTopic() {
SubscriptionsStore aStore = new SubscriptionsStore(); SubscriptionsDirectory aStore = new SubscriptionsDirectory();
MemoryStorageService memStore = new MemoryStorageService(); MemoryStorageService memStore = new MemoryStorageService();
ISessionsStore sessionsStore = memStore.sessionsStore(); ISessionsStore sessionsStore = memStore.sessionsStore();
aStore.init(sessionsStore); aStore.init(sessionsStore);
// subscribe a not active clientID1 to /topic // subscribe a not active clientID1 to /topic
sessionsStore.createNewSession("FAKE_CLI_ID_1", true); sessionsStore.createNewSession("FAKE_CLI_ID_1", true);
Subscription slashSub = new Subscription("FAKE_CLI_ID_1", new Topic("/topic"), MqttQoS.AT_MOST_ONCE); Subscription slashSub = new Subscription("FAKE_CLI_ID_1", new Topic("/topic"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(slashSub); sessionsStore.subscriptionStore().addNewSubscription(slashSub);
aStore.add(slashSub.asClientTopicCouple()); aStore.add(slashSub.asClientTopicCouple());
// subscribe an active clientID2 to /topic // subscribe an active clientID2 to /topic
Subscription slashSub2 = new Subscription("FAKE_CLI_ID_2", new Topic("/topic"), MqttQoS.AT_MOST_ONCE); Subscription slashSub2 = new Subscription("FAKE_CLI_ID_2", new Topic("/topic"), MqttQoS.AT_MOST_ONCE);
sessionsStore.addNewSubscription(slashSub2); sessionsStore.subscriptionStore().addNewSubscription(slashSub2);
aStore.add(new ClientTopicCouple("FAKE_CLI_ID_2", new Topic("/topic"))); aStore.add(new ClientTopicCouple("FAKE_CLI_ID_2", new Topic("/topic")));
// Exercise // Exercise
@@ -325,7 +331,7 @@ public class SubscriptionsStoreTest {
@Test @Test
public void testRecreatePath_emptyRoot() { public void testRecreatePath_emptyRoot() {
TreeNode oldRoot = new TreeNode(); TreeNode oldRoot = new TreeNode();
final SubscriptionsStore.NodeCouple resp = store.recreatePath(new Topic("/finance"), oldRoot); final SubscriptionsDirectory.NodeCouple resp = store.recreatePath(new Topic("/finance"), oldRoot);
// Verify // Verify
assertThat(resp.root).isNotNull(); assertThat(resp.root).isNotNull();
@@ -337,8 +343,8 @@ public class SubscriptionsStoreTest {
@Test @Test
public void testRecreatePath_1layer_tree() { public void testRecreatePath_1layer_tree() {
TreeNode oldRoot = new TreeNode(); TreeNode oldRoot = new TreeNode();
final SubscriptionsStore.NodeCouple respFinance = store.recreatePath(new Topic("/finance"), oldRoot); final SubscriptionsDirectory.NodeCouple respFinance = store.recreatePath(new Topic("/finance"), oldRoot);
final SubscriptionsStore.NodeCouple respPlus = store.recreatePath(new Topic("/+"), respFinance.root); final SubscriptionsDirectory.NodeCouple respPlus = store.recreatePath(new Topic("/+"), respFinance.root);
// Verify // Verify
assertThat(respPlus.root).isNotNull(); assertThat(respPlus.root).isNotNull();
@@ -17,6 +17,8 @@
package io.moquette.spi.impl.subscriptions; package io.moquette.spi.impl.subscriptions;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.ISubscriptionsStore;
import io.moquette.spi.ISubscriptionsStore.ClientTopicCouple;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@@ -28,7 +30,7 @@ public class TreeNodeTest {
TreeNode root = new TreeNode(); TreeNode root = new TreeNode();
TreeNode subNode1 = new TreeNode(); TreeNode subNode1 = new TreeNode();
subNode1.addSubscription(new ISessionsStore.ClientTopicCouple("Client1", new Topic("/topic1"))); subNode1.addSubscription(new ClientTopicCouple("Client1", new Topic("/topic1")));
root.addChild(subNode1); root.addChild(subNode1);
TreeNode updatedRoot = root.removeClientSubscriptions("Client1"); TreeNode updatedRoot = root.removeClientSubscriptions("Client1");
@@ -42,7 +44,7 @@ public class TreeNodeTest {
TreeNode intermediateEmptyNode = new TreeNode(); TreeNode intermediateEmptyNode = new TreeNode();
TreeNode subNode1 = new TreeNode(); TreeNode subNode1 = new TreeNode();
subNode1.addSubscription(new ISessionsStore.ClientTopicCouple("Client1", new Topic("/sub/topic1"))); subNode1.addSubscription(new ClientTopicCouple("Client1", new Topic("/sub/topic1")));
intermediateEmptyNode.addChild(subNode1); intermediateEmptyNode.addChild(subNode1);
root.addChild(intermediateEmptyNode); root.addChild(intermediateEmptyNode);
@@ -57,11 +59,11 @@ public class TreeNodeTest {
TreeNode intermediateEmptyNode = new TreeNode(); TreeNode intermediateEmptyNode = new TreeNode();
TreeNode subNode1 = new TreeNode(); TreeNode subNode1 = new TreeNode();
subNode1.addSubscription(new ISessionsStore.ClientTopicCouple("Client1", new Topic("/sub/topic1"))); subNode1.addSubscription(new ClientTopicCouple("Client1", new Topic("/sub/topic1")));
intermediateEmptyNode.addChild(subNode1); intermediateEmptyNode.addChild(subNode1);
TreeNode subNode2 = new TreeNode(); TreeNode subNode2 = new TreeNode();
subNode2.addSubscription(new ISessionsStore.ClientTopicCouple("Client2", new Topic("/sub/topic2"))); subNode2.addSubscription(new ClientTopicCouple("Client2", new Topic("/sub/topic2")));
intermediateEmptyNode.addChild(subNode2); intermediateEmptyNode.addChild(subNode2);
root.addChild(intermediateEmptyNode); root.addChild(intermediateEmptyNode);
+1 -1
View File
@@ -9,7 +9,7 @@ log4j.logger.io.moquette.spi.impl.ProtocolProcessor=WARN
log4j.logger.io.moquette.server.netty.NettyMQTTHandler=WARN log4j.logger.io.moquette.server.netty.NettyMQTTHandler=WARN
#Storage service #Storage service
#log4j.logger.io.moquette.spi.impl.subscriptions.SubscriptionsStore=DEBUG #log4j.logger.io.moquette.spi.impl.subscriptions.SubscriptionsDirectorytory=DEBUG
log4j.logger.io.moquette.spi.persistence.MapDBPersistentStore=WARN log4j.logger.io.moquette.spi.persistence.MapDBPersistentStore=WARN
log4j.logger.io.moquette.spi.persistence.MapDBSessionsStore=WARN log4j.logger.io.moquette.spi.persistence.MapDBSessionsStore=WARN
@@ -11,7 +11,7 @@ log4j.logger.io.moquette.server.netty.NettyMQTTHandler=WARN
#log4j.logger.io.moquette.server.netty.NettyMQTTHandler=DEBUG #log4j.logger.io.moquette.server.netty.NettyMQTTHandler=DEBUG
log4j.logger.io.moquette.parser.netty=WARN log4j.logger.io.moquette.parser.netty=WARN
#Storage server #Storage server
#log4j.logger.io.moquette.spi.impl.subscriptions.SubscriptionsStore=DEBUG #log4j.logger.io.moquette.spi.impl.subscriptions.SubscriptionsDirectorytory=DEBUG
#log4j.logger.io.moquette.spi.impl.HawtDBStorageService=DEBUG #log4j.logger.io.moquette.spi.impl.HawtDBStorageService=DEBUG
# stdout appender is set to be a ConsoleAppender. # stdout appender is set to be a ConsoleAppender.
+129
View File
@@ -0,0 +1,129 @@
<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>
<relativePath>../</relativePath>
<artifactId>moquette-parent</artifactId>
<groupId>io.moquette</groupId>
<version>0.10-SNAPSHOT</version>
</parent>
<artifactId>moquette-h2-storage</artifactId>
<packaging>jar</packaging>
<name>Moquette - H2 storage</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<bintray.package>io.moquette.moquette-broker</bintray.package>
</properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>moquette-broker</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2-mvstore</artifactId>
<version>1.4.192</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>test</scope>
</dependency>
<!-- needs extra dependencies: objenesis & hamcrest -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<!-- use 2.6.0 for Java 7 projects -->
<version>2.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.moquette</groupId>
<artifactId>moquette-broker</artifactId>
<type>test-jar</type>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
<!-- Includes to generate OSGi headers -->
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>bintray</id>
<url>https://api.bintray.com/maven/${bintray.repo}/${bintray.package}</url>
</repository>
</distributionManagement>
</project>
@@ -0,0 +1,93 @@
/*
* Copyright (c) 2012-2017 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.moquette.persistence.h2;
import io.moquette.spi.IMatchingCondition;
import io.moquette.spi.IMessagesStore;
import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.MessageGUID;
import io.moquette.spi.impl.subscriptions.Topic;
import org.h2.mvstore.Cursor;
import org.h2.mvstore.MVMap;
import org.h2.mvstore.MVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.plugin2.message.Message;
import java.util.*;
class H2MessagesStore implements IMessagesStore {
private static final Logger LOG = LoggerFactory.getLogger(H2MessagesStore.class);
private final MVStore mvStore;
// maps clientID -> guid
private MVMap<Topic, MessageGUID> retainedStore;
// maps guid to message, it's message store
private MVMap<MessageGUID, StoredMessage> persistentMessageStore;
private MVMap<Topic, StoredMessage> new_retainedStore;
public H2MessagesStore(MVStore mvStore) {
this.mvStore = mvStore;
}
@Override
public void initStore() {
retainedStore = mvStore.openMap("retained");
persistentMessageStore = mvStore.openMap("oldPersistedMessages");
new_retainedStore = mvStore.openMap("persistedMessages");
LOG.info("Initialized message H2 store");
}
@Override
public void storeRetained(Topic topic, StoredMessage storedMessage) {
LOG.debug("Store retained message for topic={}, CId={}", topic, storedMessage.getClientID());
if (storedMessage.getClientID() == null) {
throw new IllegalArgumentException( "Message to be persisted must have a not null client ID");
}
new_retainedStore.put(topic, storedMessage);
}
@Override
public Collection<StoredMessage> searchMatching(IMatchingCondition condition) {
LOG.debug("Scanning retained messages");
List<StoredMessage> results = new ArrayList<>();
Cursor<Topic, MessageGUID> mapCursor = retainedStore.cursor(null);
while (mapCursor.hasNext()) {
final MessageGUID guid = mapCursor.getValue();
final Topic topic = mapCursor.getKey();
StoredMessage storedMsg = persistentMessageStore.get(guid);
if (condition.match(topic)) {
results.add(storedMsg);
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("Retained messages have been scanned matchingMessages={}", results);
}
return results;
}
@Override
public void cleanRetained(Topic topic) {
LOG.debug("Cleaning retained messages. Topic={}", topic);
retainedStore.remove(topic);
}
}
@@ -0,0 +1,83 @@
package io.moquette.persistence.h2;
import org.h2.mvstore.MVMap;
import org.h2.mvstore.MVStore;
import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicLong;
class H2PersistentQueue<T> extends AbstractQueue<T> {
private final MVMap<Long, T> mvMap;
private final MVMap<String, Long> metadataMap;
private final AtomicLong head;
private final AtomicLong tail;
H2PersistentQueue(MVStore store, String queueName) {
if (queueName == null || queueName.isEmpty()) {
throw new IllegalArgumentException("queueName parameter can't be empty or null");
}
this.mvMap = store.openMap("queue_" + queueName);
this.metadataMap = store.openMap("queue_" + queueName + "_meta");
//setup head index
long headIdx = 0L;
if (this.metadataMap.containsKey("head")) {
headIdx = this.metadataMap.get("head");
} else {
this.metadataMap.put("head", headIdx);
}
this.head = new AtomicLong(headIdx);
//setup tail index
long tailIdx = 0L;
if (this.metadataMap.containsKey("tail")) {
tailIdx = this.metadataMap.get("tail");
} else {
this.metadataMap.put("tail", tailIdx);
}
this.tail = new AtomicLong(tailIdx);
}
@Override
public Iterator<T> iterator() {
return null;
}
@Override
public int size() {
return this.head.intValue() - this.tail.intValue();
}
@Override
public boolean offer(T t) {
if (t == null) {
throw new NullPointerException("Inserted element can't be null");
}
final long nextHead = head.getAndIncrement();
this.mvMap.put(nextHead, t);
this.metadataMap.put("head", nextHead + 1);
return true;
}
@Override
public T poll() {
if (head.equals(tail)) {
return null;
}
final long nextTail = tail.getAndIncrement();
final T tail = this.mvMap.get(nextTail);
this.metadataMap.put("tail", nextTail + 1);
return tail;
}
@Override
public T peek() {
if (head.equals(tail)) {
return null;
}
return this.mvMap.get(tail.get());
}
}
@@ -0,0 +1,94 @@
/*
* Copyright (c) 2012-2017 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.moquette.persistence.h2;
import io.moquette.BrokerConstants;
import io.moquette.server.config.IConfig;
import io.moquette.spi.IMessagesStore;
import io.moquette.spi.ISessionsStore;
import io.moquette.spi.IStore;
import org.h2.mvstore.MVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class H2PersistentStore implements IStore {
private static final Logger LOG = LoggerFactory.getLogger(H2PersistentStore.class);
private final String storePath;
private final int autosaveInterval; // in seconds
protected final ScheduledExecutorService scheduler;
private MVStore mvStore;
private IMessagesStore messageStore;
private ISessionsStore sessionsStore;
public H2PersistentStore(IConfig props, ScheduledExecutorService scheduler) {
this.storePath = props.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME, "");
this.autosaveInterval = Integer.parseInt(props.getProperty(BrokerConstants.AUTOSAVE_INTERVAL_PROPERTY_NAME, "30"));
this.scheduler = scheduler;
}
@Override
public void initStore() {
LOG.info("Initializing H2 store");
if (storePath == null || storePath.isEmpty()) {
LOG.warn("H2 store file path is empty, using in-memory store");
mvStore = MVStore.open(null);
} else {
mvStore = new MVStore.Builder()
.fileName(storePath)
.autoCommitDisabled()
.open();
}
LOG.info("Scheduling H2 commit task");
scheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
LOG.debug("Committing to H2");
mvStore.commit();
}
}, this.autosaveInterval, this.autosaveInterval, TimeUnit.SECONDS);
messageStore = new H2MessagesStore(mvStore);
messageStore.initStore();
sessionsStore = new H2SessionsStore(mvStore);
sessionsStore.initStore();
}
@Override
public void close() {
}
@Override
public IMessagesStore messagesStore() {
return messageStore;
}
@Override
public ISessionsStore sessionsStore() {
return sessionsStore;
}
}
@@ -0,0 +1,370 @@
/*
* Copyright (c) 2012-2017 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.moquette.persistence.h2;
import io.moquette.persistence.PersistentSession;
import io.moquette.spi.ClientSession;
import io.moquette.spi.IMessagesStore;
import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.ISessionsStore;
import io.moquette.spi.ISubscriptionsStore;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic;
import org.h2.mvstore.Cursor;
import org.h2.mvstore.MVMap;
import org.h2.mvstore.MVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class H2SessionsStore implements ISessionsStore, ISubscriptionsStore {
private static final Logger LOG = LoggerFactory.getLogger(H2SessionsStore.class);
private final MVStore mvStore;
private ConcurrentMap<String, PersistentSession> sessions;
// maps clientID->[MessageId -> msg]
private ConcurrentMap<String, ConcurrentMap<Integer, StoredMessage>> outboundFlightMessages;
// map clientID <-> set of currently in flight packet identifiers
private Map<String, Set<Integer>> inFlightIds;
// maps clientID->[MessageId -> guid]
private ConcurrentMap<String, ConcurrentMap<Integer, StoredMessage>> secondPhaseStore;
public H2SessionsStore(MVStore mvStore) {
this.mvStore = mvStore;
}
@Override
public void initStore() {
this.sessions = mvStore.openMap("sessions");
this.outboundFlightMessages = mvStore.openMap("outboundFlight");
this.inFlightIds = mvStore.openMap("inflightPacketIDs");
this.secondPhaseStore = mvStore.openMap("secondPhase");
LOG.info("Initialized sessions H2 store");
}
@Override
public ISubscriptionsStore subscriptionStore() {
return this;
}
@Override
public void updateCleanStatus(String clientID, boolean cleanSession) {
LOG.info("Updating cleanSession flag. CId={}, cleanSession={}", clientID, cleanSession);
this.sessions.put(clientID, new PersistentSession(cleanSession));
}
@Override
public void addNewSubscription(Subscription newSubscription) {
LOG.info("Adding new subscription CId={}, topics={}", newSubscription.getClientId(),
newSubscription.getTopicFilter());
final String clientID = newSubscription.getClientId();
final MVMap<Object, Object> sessionSubscriptions = this.mvStore.openMap("subscriptions_" + clientID);
sessionSubscriptions.put(newSubscription.getTopicFilter(), newSubscription);
if (LOG.isTraceEnabled()) {
LOG.trace("Subscription has been added CId={}, topics={}, clientSubscriptions={}",
newSubscription.getClientId(), newSubscription.getTopicFilter(), sessionSubscriptions);
}
}
@Override
public void removeSubscription(Topic topicFilter, String clientID) {
LOG.info("Removing subscription. CId={}, topics={}", clientID, topicFilter);
if (!this.mvStore.hasMap("subscriptions_" + clientID)) {
return;
}
final MVMap<Object, Object> sessionsSubscriptions = this.mvStore.openMap("subscriptions_" + clientID);
sessionsSubscriptions.remove(topicFilter);
if (LOG.isDebugEnabled()) {
LOG.debug("Subscription has been removed. CId={}, topics={}, clientSubscriptions={}", clientID,
topicFilter, sessionsSubscriptions);
}
}
@Override
public void wipeSubscriptions(String sessionID) {
LOG.info("Wiping subscriptions. CId={}", sessionID);
if (!this.mvStore.hasMap("subscriptions_" + sessionID)) {
return;
}
final MVMap<Object, Object> subscriptions = this.mvStore.openMap("subscriptions_" + sessionID);
this.mvStore.removeMap(subscriptions);
if (LOG.isDebugEnabled()) {
LOG.debug("Subscriptions have been removed. CId={}, clientSubscriptions={}", sessionID, subscriptions);
}
}
@Override
public List<ClientTopicCouple> listAllSubscriptions() {
LOG.info("Retrieving existing subscriptions");
final List<ClientTopicCouple> allSubscriptions = new ArrayList<>();
for (String clientID : this.sessions.keySet()) {
ConcurrentMap<Topic, Subscription> clientSubscriptions = this.mvStore.openMap("subscriptions_" + clientID);
for (Topic topicFilter : clientSubscriptions.keySet()) {
allSubscriptions.add(new ClientTopicCouple(clientID, topicFilter));
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("The existing subscriptions have been retrieved. Result={}", allSubscriptions);
}
return allSubscriptions;
}
@Override
public List<Subscription> getSubscriptions() {
LOG.debug("Retrieving existing subscriptions...");
List<Subscription> subscriptions = new ArrayList<>();
for (String clientID : this.sessions.keySet()) {
ConcurrentMap<Topic, Subscription> clientSubscriptions = this.mvStore.openMap("subscriptions_" + clientID);
subscriptions.addAll(clientSubscriptions.values());
}
LOG.debug("Existing subscriptions has been retrieved Result={}", subscriptions);
return subscriptions;
}
@Override
public Subscription getSubscription(ClientTopicCouple couple) {
ConcurrentMap<Topic, Subscription> clientSubscriptions = this.mvStore.openMap("subscriptions_" + couple.clientID);
LOG.debug("Retrieving subscriptions CId={}, subscriptions={}", couple.clientID, clientSubscriptions);
return clientSubscriptions.get(couple.topicFilter);
}
@Override
public boolean contains(String clientID) {
return this.mvStore.hasMap("subscriptions_" + clientID);
}
@Override
public ClientSession createNewSession(String clientID, boolean cleanSession) {
if (sessions.containsKey(clientID)) {
LOG.error("Unable to create a new session: the client ID is already in use. CId={}, cleanSession={}",
clientID, cleanSession);
throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID);
}
LOG.debug("Creating new session. CId={}, cleanSession={}", clientID, cleanSession);
sessions.putIfAbsent(clientID, new PersistentSession(cleanSession));
return new ClientSession(clientID, this, this, cleanSession);
}
@Override
public ClientSession sessionForClient(String clientID) {
LOG.debug("Retrieving session. CId={}", clientID);
if (!this.sessions.containsKey(clientID)) {
LOG.warn("Session does not exist. CId={}", clientID);
return null;
}
PersistentSession storedSession = this.sessions.get(clientID);
return new ClientSession(clientID, this, this, storedSession.cleanSession);
}
@Override
public Collection<ClientSession> getAllSessions() {
Collection<ClientSession> result = new ArrayList<>();
for (Map.Entry<String, PersistentSession> entry : this.sessions.entrySet()) {
result.add(new ClientSession(entry.getKey(), this, this, entry.getValue().cleanSession));
}
return result;
}
@Override
public StoredMessage inFlightAck(String clientID, int messageID) {
LOG.debug("Acknowledging inflight message CId={}, messageId={}", clientID, messageID);
ConcurrentMap<Integer, StoredMessage> m = this.outboundFlightMessages.get(clientID);
if (m == null) {
LOG.error("Can't find the inFlight record for client <{}>", clientID);
throw new RuntimeException("Can't find the inFlight record for client <" + clientID + ">");
}
StoredMessage msg = m.remove(messageID);
this.outboundFlightMessages.put(clientID, m);
// remove from the ids store
Set<Integer> inFlightForClient = this.inFlightIds.get(clientID);
if (inFlightForClient != null) {
inFlightForClient.remove(messageID);
}
return msg;
}
@Override
public void inFlight(String clientID, int messageID, StoredMessage msg) {
ConcurrentMap<Integer, IMessagesStore.StoredMessage> messages = this.outboundFlightMessages.get(clientID);
if (messages == null) {
messages = new ConcurrentHashMap<>();
}
messages.put(messageID, msg);
this.outboundFlightMessages.put(clientID, messages);
}
@Override
public int nextPacketID(String clientID) {
LOG.debug("Generating next packet ID CId={}", clientID);
Set<Integer> inFlightForClient = this.inFlightIds.get(clientID);
if (inFlightForClient == null) {
int nextPacketId = 1;
inFlightForClient = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
inFlightForClient.add(nextPacketId);
this.inFlightIds.put(clientID, inFlightForClient);
return nextPacketId;
}
int maxId = inFlightForClient.isEmpty() ? 0 : Collections.max(inFlightForClient);
int nextPacketId = (maxId % 0xFFFF) + 1;
inFlightForClient.add(nextPacketId);
LOG.debug("Next packet ID has been generated CId={}, result={}", clientID, nextPacketId);
return nextPacketId;
}
class H2BackedQueue<T> extends AbstractQueue<T> {
private final MVMap<T, ?> map;
private final Cursor<T, ?> cursor;
H2BackedQueue(MVMap<T, ?> map) {
this.cursor = map.cursor(null);
this.map = map;
}
@Override
public Iterator<T> iterator() {
return cursor;
}
@Override
public int size() {
return map.size();
}
@Override
public boolean offer(T t) {
return false;
}
@Override
public T poll() {
return null;
}
@Override
public T peek() {
return null;
}
}
//TODO
@Override
public BlockingQueue<StoredMessage> queue(String clientID) {
throw new RuntimeException("Not yet implemented");
}
//TODO
@Override
public void dropQueue(String clientID) {
throw new RuntimeException("Not yet implemented");
}
@Override
public void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID, StoredMessage msg) {
LOG.debug("Moving inflight message to 2nd phase ack state CId={}, messageID={}", clientID, messageID);
ConcurrentMap<Integer, StoredMessage> m = this.secondPhaseStore.get(clientID);
if (m == null) {
String error = String.format("Can't find the inFlight record for client <%s> during the second phase of " +
"QoS2 pub", clientID);
LOG.error(error);
throw new RuntimeException(error);
}
m.put(messageID, msg);
this.outboundFlightMessages.put(clientID, m);
}
@Override
public StoredMessage secondPhaseAcknowledged(String clientID, int messageID) {
LOG.debug("Processing second phase ACK CId={}, messageId={}", clientID, messageID);
final ConcurrentMap<Integer, StoredMessage> m = this.secondPhaseStore.get(clientID);
if (m == null) {
String error = String.format("Can't find the inFlight record for client <%s> during the second phase " +
"acking of QoS2 pub", clientID);
LOG.error(error);
throw new RuntimeException(error);
}
StoredMessage msg = m.remove(messageID);
this.secondPhaseStore.put(clientID, m);
return msg;
}
@Override
public int getInflightMessagesNo(String clientID) {
int totalInflight = 0;
ConcurrentMap<Integer, StoredMessage> inflightPerClient = this.mvStore.openMap(inboundStoreForClient(clientID));
if (inflightPerClient != null) {
totalInflight += inflightPerClient.size();
}
Map<Integer, StoredMessage> secondPhaseInFlight = this.secondPhaseStore.get(clientID);
if (secondPhaseInFlight != null) {
totalInflight += secondPhaseInFlight.size();
}
Map<Integer, StoredMessage> outboundPerClient = outboundFlightMessages.get(clientID);
if (outboundPerClient != null) {
totalInflight += outboundPerClient.size();
}
return totalInflight;
}
private static String inboundStoreForClient(String clientID) {
return "inboundInflight_" + clientID;
}
@Override
public StoredMessage inboundInflight(String clientID, int messageID) {
LOG.debug("Mapping inbound message ID to GUID CId={}, messageId={}", clientID, messageID);
ConcurrentMap<Integer, StoredMessage> messageIdToGuid = this.mvStore.openMap(inboundStoreForClient(clientID));
return messageIdToGuid.get(messageID);
}
@Override
public void markAsInboundInflight(String clientID, int messageID, StoredMessage msg) {
ConcurrentMap<Integer, StoredMessage> messageIdToGuid = this.mvStore.openMap(inboundStoreForClient(clientID));
messageIdToGuid.put(messageID, msg);
}
@Override
public int getPendingPublishMessagesNo(String clientID) {
return queue(clientID).size();
}
@Override
public int getSecondPhaseAckPendingMessages(String clientID) {
if (!this.secondPhaseStore.containsKey(clientID))
return 0;
return this.secondPhaseStore.get(clientID).size();
}
@Override
public void dropInFlightMessagesInSession(String clientID) {
this.secondPhaseStore.remove(clientID);
this.outboundFlightMessages.remove(clientID);
}
}
@@ -0,0 +1,69 @@
/*
* Copyright (c) 2012-2017 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.moquette.persistence.h2;
import io.moquette.BrokerConstants;
import io.moquette.persistence.MessageStoreTCK;
import io.moquette.server.config.IConfig;
import io.moquette.server.config.MemoryConfig;
import org.junit.After;
import org.junit.Before;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import static org.junit.Assert.assertFalse;
public class H2MessagesStoreTest extends MessageStoreTCK {
H2PersistentStore storageService;
private ScheduledExecutorService scheduler;
@Before
public void setUp() throws Exception {
scheduler = Executors.newScheduledThreadPool(1);
cleanPersistenceFile(BrokerConstants.DEFAULT_PERSISTENT_PATH);
Properties props = new Properties();
props.setProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME, BrokerConstants.DEFAULT_PERSISTENT_PATH);
IConfig conf = new MemoryConfig(props);
storageService = new H2PersistentStore(conf, scheduler);
storageService.initStore();
messagesStore = storageService.messagesStore();
sessionsStore = storageService.sessionsStore();
}
@After
public void tearDown() {
if (storageService != null) {
storageService.close();
}
scheduler.shutdown();
cleanPersistenceFile(BrokerConstants.DEFAULT_PERSISTENT_PATH);
}
public static void cleanPersistenceFile(String fileName) {
File dbFile = new File(fileName);
if (dbFile.exists()) {
dbFile.delete();
}
assertFalse(dbFile.exists());
}
}
@@ -0,0 +1,96 @@
package io.moquette.persistence.h2;
import io.moquette.BrokerConstants;
import org.h2.mvstore.MVStore;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
public class H2PersistentQueueTest {
private MVStore mvStore;
@Before
public void setUp() {
this.mvStore = new MVStore.Builder()
.fileName(BrokerConstants.DEFAULT_PERSISTENT_PATH)
.autoCommitDisabled()
.open();
}
@After
public void tearDown() {
File dbFile = new File(BrokerConstants.DEFAULT_PERSISTENT_PATH);
if (dbFile.exists()) {
dbFile.delete();
}
assertFalse(dbFile.exists());
}
@Test
public void testAdd() {
H2PersistentQueue<String> sut = new H2PersistentQueue<>(this.mvStore, "test");
sut.add("Hello");
sut.add("world");
assertEquals("Hello", sut.peek());
assertEquals("Hello", sut.peek());
assertEquals("peek just return elements, doesn't remove them", 2, sut.size());
}
@Test
public void testPoll() {
H2PersistentQueue<String> sut = new H2PersistentQueue<>(this.mvStore, "test");
sut.add("Hello");
sut.add("world");
assertEquals("Hello", sut.poll());
assertEquals("world", sut.poll());
assertTrue("after poll 2 elements inserted before, should be empty", sut.isEmpty());
}
@Test
public void testPerformance() {
H2PersistentQueue<String> sut = new H2PersistentQueue<>(this.mvStore, "test");
int numIterations = 10000000;
for (int i=0; i < numIterations; i++) {
sut.add("Hello");
}
mvStore.commit();
for (int i=0; i < numIterations; i++) {
assertEquals("Hello", sut.poll());
}
assertTrue("should be empty", sut.isEmpty());
}
@Test
public void testReloadFromPersistedState() {
H2PersistentQueue<String> before = new H2PersistentQueue<>(this.mvStore, "test");
before.add("Hello");
before.add("crazy");
before.add("world");
assertEquals("Hello", before.poll());
this.mvStore.commit();
this.mvStore.close();
this.mvStore = new MVStore.Builder()
.fileName(BrokerConstants.DEFAULT_PERSISTENT_PATH)
.autoCommitDisabled()
.open();
//now reload the persisted state
H2PersistentQueue<String> after = new H2PersistentQueue<>(this.mvStore, "test");
assertEquals("crazy", after.poll());
assertEquals("world", after.poll());
assertTrue("should be empty", after.isEmpty());
}
}
+7 -42
View File
@@ -33,24 +33,9 @@
<dependency> <dependency>
<groupId>org.mapdb</groupId> <groupId>org.mapdb</groupId>
<artifactId>mapdb</artifactId> <artifactId>mapdb</artifactId>
<!--version>1.1.0-SNAPSHOT</version -->
<!--<version>2.0.0-SNAPSHOT</version> -->
<!--<version>2.0-alpha3</version> -->
<version>1.0.8</version> <version>1.0.8</version>
</dependency> </dependency>
<dependency>
<groupId>org.hdrhistogram</groupId>
<artifactId>HdrHistogram</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>3.5.4</version>
</dependency>
<!-- Test dependencies --> <!-- Test dependencies -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@@ -74,27 +59,6 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!--<dependency>-->
<!--<groupId>org.fusesource.mqtt-client</groupId>-->
<!--<artifactId>mqtt-client</artifactId>-->
<!--<version>1.12</version>-->
<!--<scope>test</scope>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.eclipse.paho</groupId>-->
<!--<artifactId>org.eclipse.paho.client.mqttv3</artifactId>-->
<!--<version>1.0.2</version>-->
<!--<scope>test</scope>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.eclipse.jetty.websocket</groupId>-->
<!--<artifactId>websocket-client</artifactId>-->
<!--<version>9.2.0.M1</version>-->
<!--<scope>test</scope>-->
<!--</dependency>-->
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
@@ -103,12 +67,13 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!--<dependency>--> <dependency>
<!--<groupId>com.h2database</groupId>--> <groupId>io.moquette</groupId>
<!--<artifactId>h2</artifactId>--> <artifactId>moquette-broker</artifactId>
<!--<version>1.4.191</version>--> <type>test-jar</type>
<!--<scope>test</scope>--> <version>${project.version}</version>
<!--</dependency>--> <scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@@ -18,12 +18,15 @@ package io.moquette.persistence.mapdb;
import io.moquette.spi.IMatchingCondition; import io.moquette.spi.IMatchingCondition;
import io.moquette.spi.IMessagesStore; import io.moquette.spi.IMessagesStore;
import io.moquette.spi.MessageGUID;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import org.mapdb.DB; import org.mapdb.DB;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
/** /**
@@ -35,10 +38,7 @@ class MapDBMessagesStore implements IMessagesStore {
private DB m_db; private DB m_db;
// maps clientID -> guid private ConcurrentMap<Topic, StoredMessage> m_retainedStore;
private ConcurrentMap<Topic, MessageGUID> m_retainedStore;
// maps guid to message, it's message store
private ConcurrentMap<MessageGUID, IMessagesStore.StoredMessage> m_persistentMessageStore;
MapDBMessagesStore(DB db) { MapDBMessagesStore(DB db) {
m_db = db; m_db = db;
@@ -47,66 +47,39 @@ class MapDBMessagesStore implements IMessagesStore {
@Override @Override
public void initStore() { public void initStore() {
m_retainedStore = m_db.getHashMap("retained"); m_retainedStore = m_db.getHashMap("retained");
m_persistentMessageStore = m_db.getHashMap("persistedMessages");
LOG.info("Initialized store"); LOG.info("Initialized store");
} }
@Override
public void storeRetained(Topic topic, MessageGUID guid) {
LOG.debug("Storing retained messages. Topic={}, guid={}", topic, guid);
m_retainedStore.put(topic, guid);
}
@Override @Override
public Collection<StoredMessage> searchMatching(IMatchingCondition condition) { public Collection<StoredMessage> searchMatching(IMatchingCondition condition) {
LOG.debug("Scanning retained messages..."); LOG.debug("Scanning retained messages");
List<StoredMessage> results = new ArrayList<>(); List<StoredMessage> results = new ArrayList<>();
for (Map.Entry<Topic, MessageGUID> entry : m_retainedStore.entrySet()) { for (Map.Entry<Topic, StoredMessage> entry : m_retainedStore.entrySet()) {
final MessageGUID guid = entry.getValue(); StoredMessage storedMsg = entry.getValue();
StoredMessage storedMsg = m_persistentMessageStore.get(guid);
if (condition.match(entry.getKey())) { if (condition.match(entry.getKey())) {
results.add(storedMsg); results.add(storedMsg);
} }
} }
if (LOG.isTraceEnabled()) { if (LOG.isTraceEnabled()) {
LOG.trace("The retained messages have been scanned. MatchingMessages={}", results); LOG.trace("Retained messages have been scanned matchingMessages={}", results);
} }
return results; return results;
} }
@Override
public MessageGUID storePublishForFuture(StoredMessage storedMessage) {
assert storedMessage.getClientID() != null : "Message to be persisted must have a valid client ID";
MessageGUID guid = new MessageGUID(UUID.randomUUID().toString());
storedMessage.setGuid(guid);
LOG.debug("Storing publish event. CId={}, guid={}, topic={}", storedMessage.getClientID(), guid,
storedMessage.getTopic());
m_persistentMessageStore.put(guid, storedMessage);
return guid;
}
@Override
public void dropInFlightMessagesInSession(Collection<MessageGUID> pendingAckMessages) {
//remove all guids from retained
Collection<MessageGUID> messagesToRemove = new HashSet<>(pendingAckMessages);
messagesToRemove.removeAll(m_retainedStore.values());
for (MessageGUID guid : messagesToRemove) {
m_persistentMessageStore.remove(guid);
}
}
@Override
public StoredMessage getMessageByGuid(MessageGUID guid) {
LOG.debug("Retrieving stored message. Guid={}", guid);
return m_persistentMessageStore.get(guid);
}
@Override @Override
public void cleanRetained(Topic topic) { public void cleanRetained(Topic topic) {
LOG.debug("Cleaning retained messages. Topic={}", topic); LOG.debug("Cleaning retained messages. Topic={}", topic);
m_retainedStore.remove(topic); m_retainedStore.remove(topic);
} }
@Override
public void storeRetained(Topic topic, StoredMessage storedMessage) {
LOG.debug("Store retained message for topic={}, CId={}", topic, storedMessage.getClientID());
if (storedMessage.getClientID() == null) {
throw new IllegalArgumentException( "Message to be persisted must have a not null client ID");
}
m_retainedStore.put(topic, storedMessage);
}
} }
@@ -52,11 +52,6 @@ public class MapDBPersistentStore implements IStore {
this.m_scheduler = scheduler; this.m_scheduler = scheduler;
} }
/**
* Factory method to create message store backed by MapDB
*
* @return the message store instance.
*/
@Override @Override
public IMessagesStore messagesStore() { public IMessagesStore messagesStore() {
return m_messageStore; return m_messageStore;
@@ -67,36 +62,32 @@ public class MapDBPersistentStore implements IStore {
return m_sessionsStore; return m_sessionsStore;
} }
@Override
public void initStore() { public void initStore() {
LOG.info("Initializing MapDB store..."); LOG.info("Initializing MapDB store");
if (m_storePath == null || m_storePath.isEmpty()) { if (m_storePath == null || m_storePath.isEmpty()) {
LOG.warn("The MapDB store file path is empty. Using in-memory store."); LOG.warn("MapDB store file path is empty, using in-memory store");
m_db = DBMaker.newMemoryDB().make(); m_db = DBMaker.newMemoryDB().make();
} else { } else {
File tmpFile; File tmpFile;
try { try {
LOG.info("Using user-defined MapDB store file. Path = {}.", m_storePath); LOG.info("Using user-defined MapDB store file. Path={}", m_storePath);
tmpFile = new File(m_storePath); tmpFile = new File(m_storePath);
boolean fileNewlyCreated = tmpFile.createNewFile(); boolean fileNewlyCreated = tmpFile.createNewFile();
LOG.warn("Using {} MapDB store file. Path = {}.", fileNewlyCreated ? "fresh" : "existing", m_storePath); LOG.warn("Using {} MapDB store file. Path={}", fileNewlyCreated ? "fresh" : "existing", m_storePath);
} catch (IOException ex) { } catch (IOException ex) {
LOG.error( LOG.error("Unable to open MapDB store file. Path={}, cause={}, errorMessage={}", m_storePath,
"Unable to open MapDB store file. Path = {}, cause = {}, errorMessage = {}.", ex.getCause(), ex.getMessage());
m_storePath, throw new RuntimeException("Can't create temp subscriptions file storage [" + m_storePath + "]", ex);
ex.getCause(),
ex.getMessage());
throw new RuntimeException(
"Can't create temp file for subscriptions storage [" + m_storePath + "]",
ex);
} }
m_db = DBMaker.newFileDB(tmpFile).make(); m_db = DBMaker.newFileDB(tmpFile).make();
} }
LOG.info("Scheduling MapDB commit task..."); LOG.info("Scheduling MapDB commit task");
m_scheduler.scheduleWithFixedDelay(new Runnable() { m_scheduler.scheduleWithFixedDelay(new Runnable() {
@Override @Override
public void run() { public void run() {
LOG.debug("Committing to MapDB..."); LOG.debug("Committing to MapDB");
m_db.commit(); m_db.commit();
} }
}, this.m_autosaveInterval, this.m_autosaveInterval, TimeUnit.SECONDS); }, this.m_autosaveInterval, this.m_autosaveInterval, TimeUnit.SECONDS);
@@ -105,21 +96,21 @@ public class MapDBPersistentStore implements IStore {
m_messageStore = new MapDBMessagesStore(m_db); m_messageStore = new MapDBMessagesStore(m_db);
m_messageStore.initStore(); m_messageStore.initStore();
m_sessionsStore = new MapDBSessionsStore(m_db, m_messageStore); m_sessionsStore = new MapDBSessionsStore(m_db);
m_sessionsStore.initStore(); m_sessionsStore.initStore();
} }
@Override @Override
public void close() { public void close() {
if (this.m_db.isClosed()) { if (this.m_db.isClosed()) {
LOG.warn("The MapDB store is already closed. Nothing will be done."); LOG.warn("MapDB store is already closed. Nothing will be done");
return; return;
} }
LOG.info("Performing last commit to MapDB..."); LOG.info("Performing last commit to MapDB");
this.m_db.commit(); this.m_db.commit();
LOG.info("Closing MapDB store..."); LOG.info("Closing MapDB store");
this.m_db.close(); this.m_db.close();
LOG.info("Stopping MapDB commit tasks..."); LOG.info("Stopping MapDB commit tasks");
//TODO th scheduler must be stopped by the owning (the instance of Server) //TODO th scheduler must be stopped by the owning (the instance of Server)
//invalidate the added task //invalidate the added task
@@ -129,9 +120,9 @@ public class MapDBPersistentStore implements IStore {
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
if (!m_scheduler.isTerminated()) { if (!m_scheduler.isTerminated()) {
LOG.warn("Forcing shutdown of MapDB commit tasks..."); LOG.warn("Forcing shutdown of MapDB commit tasks");
m_scheduler.shutdown(); m_scheduler.shutdown();
} }
LOG.info("The MapDB store has been closed successfully."); LOG.info("MapDB store has been closed successfully");
} }
} }
@@ -18,11 +18,9 @@ package io.moquette.persistence.mapdb;
import io.moquette.persistence.PersistentSession; import io.moquette.persistence.PersistentSession;
import io.moquette.spi.ClientSession; import io.moquette.spi.ClientSession;
import io.moquette.spi.IMessagesStore;
import io.moquette.spi.IMessagesStore.StoredMessage; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.ISessionsStore; import io.moquette.spi.ISessionsStore;
import io.moquette.spi.MessageGUID; import io.moquette.spi.ISubscriptionsStore;
import io.moquette.spi.impl.Utils;
import io.moquette.spi.impl.subscriptions.Subscription; import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic; import io.moquette.spi.impl.subscriptions.Topic;
import org.mapdb.DB; import org.mapdb.DB;
@@ -37,34 +35,37 @@ import java.util.concurrent.ConcurrentMap;
/** /**
* ISessionsStore implementation backed by MapDB. * ISessionsStore implementation backed by MapDB.
*/ */
class MapDBSessionsStore implements ISessionsStore { class MapDBSessionsStore implements ISessionsStore, ISubscriptionsStore {
private static final Logger LOG = LoggerFactory.getLogger(MapDBSessionsStore.class); private static final Logger LOG = LoggerFactory.getLogger(MapDBSessionsStore.class);
// maps clientID->[MessageId -> guid] // maps clientID->[MessageId -> msg]
private ConcurrentMap<String, ConcurrentMap<Integer, MessageGUID>> m_inflightStore; private ConcurrentMap<String, ConcurrentMap<Integer, StoredMessage>> outboundFlightMessages;
// map clientID <-> set of currently in flight packet identifiers // map clientID <-> set of currently in flight packet identifiers
private Map<String, Set<Integer>> m_inFlightIds; private Map<String, Set<Integer>> m_inFlightIds;
private ConcurrentMap<String, PersistentSession> m_persistentSessions; private ConcurrentMap<String, PersistentSession> m_persistentSessions;
// maps clientID->[MessageId -> guid] // maps clientID->[MessageId -> guid]
private ConcurrentMap<String, Map<Integer, MessageGUID>> m_secondPhaseStore; private ConcurrentMap<String, ConcurrentMap<Integer, StoredMessage>> m_secondPhaseStore;
private final DB m_db; private final DB m_db;
private final IMessagesStore m_messagesStore;
MapDBSessionsStore(DB db, IMessagesStore messagesStore) { MapDBSessionsStore(DB db) {
m_db = db; m_db = db;
m_messagesStore = messagesStore;
} }
@Override @Override
public void initStore() { public void initStore() {
m_inflightStore = m_db.getHashMap("inflight"); outboundFlightMessages = m_db.getHashMap("outboundFlight");
m_inFlightIds = m_db.getHashMap("inflightPacketIDs"); m_inFlightIds = m_db.getHashMap("inflightPacketIDs");
m_persistentSessions = m_db.getHashMap("sessions"); m_persistentSessions = m_db.getHashMap("sessions");
m_secondPhaseStore = m_db.getHashMap("secondPhase"); m_secondPhaseStore = m_db.getHashMap("secondPhase");
} }
@Override
public ISubscriptionsStore subscriptionStore() {
return this;
}
@Override @Override
public void addNewSubscription(Subscription newSubscription) { public void addNewSubscription(Subscription newSubscription) {
LOG.info("Adding new subscription. ClientId={}, topics={}", newSubscription.getClientId(), LOG.info("Adding new subscription. ClientId={}, topics={}", newSubscription.getClientId(),
@@ -94,7 +95,7 @@ class MapDBSessionsStore implements ISessionsStore {
@Override @Override
public void wipeSubscriptions(String clientID) { public void wipeSubscriptions(String clientID) {
LOG.info("Wiping subscriptions. ClientId={}", clientID); LOG.info("Wiping subscriptions. CId={}", clientID);
m_db.delete("subscriptions_" + clientID); m_db.delete("subscriptions_" + clientID);
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("Subscriptions have been removed. ClientId={}, clientSubscriptions={}", clientID, LOG.debug("Subscriptions have been removed. ClientId={}, clientSubscriptions={}", clientID,
@@ -104,7 +105,7 @@ class MapDBSessionsStore implements ISessionsStore {
@Override @Override
public List<ClientTopicCouple> listAllSubscriptions() { public List<ClientTopicCouple> listAllSubscriptions() {
LOG.info("Retrieving existing subscriptions..."); LOG.debug("Retrieving existing subscriptions");
final List<ClientTopicCouple> allSubscriptions = new ArrayList<>(); final List<ClientTopicCouple> allSubscriptions = new ArrayList<>();
for (String clientID : m_persistentSessions.keySet()) { for (String clientID : m_persistentSessions.keySet()) {
ConcurrentMap<Topic, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + clientID); ConcurrentMap<Topic, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + clientID);
@@ -121,19 +122,19 @@ class MapDBSessionsStore implements ISessionsStore {
@Override @Override
public Subscription getSubscription(ClientTopicCouple couple) { public Subscription getSubscription(ClientTopicCouple couple) {
ConcurrentMap<Topic, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + couple.clientID); ConcurrentMap<Topic, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + couple.clientID);
LOG.info("Retrieving subscriptions. ClientId={}, subscriptions={}", couple.clientID, clientSubscriptions); LOG.debug("Retrieving subscriptions. CId={}, subscriptions={}", couple.clientID, clientSubscriptions);
return clientSubscriptions.get(couple.topicFilter); return clientSubscriptions.get(couple.topicFilter);
} }
@Override @Override
public List<Subscription> getSubscriptions() { public List<Subscription> getSubscriptions() {
LOG.info("Retrieving existing subscriptions..."); LOG.debug("Retrieving existing subscriptions...");
List<Subscription> subscriptions = new ArrayList<>(); List<Subscription> subscriptions = new ArrayList<>();
for (String clientID : m_persistentSessions.keySet()) { for (String clientID : m_persistentSessions.keySet()) {
ConcurrentMap<Topic, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + clientID); ConcurrentMap<Topic, Subscription> clientSubscriptions = m_db.getHashMap("subscriptions_" + clientID);
subscriptions.addAll(clientSubscriptions.values()); subscriptions.addAll(clientSubscriptions.values());
} }
LOG.debug("The existing subscriptions have been retrieved. Result={}", subscriptions); LOG.debug("Existing subscriptions has been retrieved Result={}", subscriptions);
return subscriptions; return subscriptions;
} }
@@ -149,35 +150,35 @@ class MapDBSessionsStore implements ISessionsStore {
clientID, cleanSession); clientID, cleanSession);
throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID); throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID);
} }
LOG.info("Creating new session. ClientId={}, cleanSession={}", clientID, cleanSession); LOG.debug("Creating new session. CId={}, cleanSession={}", clientID, cleanSession);
m_persistentSessions.putIfAbsent(clientID, new PersistentSession(cleanSession)); m_persistentSessions.putIfAbsent(clientID, new PersistentSession(cleanSession));
return new ClientSession(clientID, m_messagesStore, this, cleanSession); return new ClientSession(clientID, this, this, cleanSession);
} }
@Override @Override
public ClientSession sessionForClient(String clientID) { public ClientSession sessionForClient(String clientID) {
LOG.info("Retrieving session. ClientId={}", clientID); LOG.debug("Retrieving session CId={}", clientID);
if (!m_persistentSessions.containsKey(clientID)) { if (!m_persistentSessions.containsKey(clientID)) {
LOG.warn("The session does not exist. ClientId={}", clientID); LOG.warn("Session does not exist CId={}", clientID);
return null; return null;
} }
PersistentSession storedSession = m_persistentSessions.get(clientID); PersistentSession storedSession = m_persistentSessions.get(clientID);
return new ClientSession(clientID, m_messagesStore, this, storedSession.cleanSession); return new ClientSession(clientID, this, this, storedSession.cleanSession);
} }
@Override @Override
public Collection<ClientSession> getAllSessions() { public Collection<ClientSession> getAllSessions() {
Collection<ClientSession> result = new ArrayList<>(); Collection<ClientSession> result = new ArrayList<>();
for (Map.Entry<String, PersistentSession> entry : m_persistentSessions.entrySet()) { for (Map.Entry<String, PersistentSession> entry : m_persistentSessions.entrySet()) {
result.add(new ClientSession(entry.getKey(), m_messagesStore, this, entry.getValue().cleanSession)); result.add(new ClientSession(entry.getKey(), this, this, entry.getValue().cleanSession));
} }
return result; return result;
} }
@Override @Override
public void updateCleanStatus(String clientID, boolean cleanSession) { public void updateCleanStatus(String clientID, boolean cleanSession) {
LOG.info("Updating cleanSession flag. ClientId={}, cleanSession={}", clientID, cleanSession); LOG.info("Updating cleanSession flag. CId={}, cleanSession={}", clientID, cleanSession);
m_persistentSessions.put(clientID, new PersistentSession(cleanSession)); m_persistentSessions.put(clientID, new PersistentSession(cleanSession));
} }
@@ -186,9 +187,7 @@ class MapDBSessionsStore implements ISessionsStore {
*/ */
@Override @Override
public int nextPacketID(String clientID) { public int nextPacketID(String clientID) {
if (LOG.isDebugEnabled()) { LOG.debug("Generating next packet ID CId={}", clientID);
LOG.debug("Generating next packet ID. ClientId={}", clientID);
}
Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID); Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID);
if (inFlightForClient == null) { if (inFlightForClient == null) {
int nextPacketId = 1; int nextPacketId = 1;
@@ -202,39 +201,37 @@ class MapDBSessionsStore implements ISessionsStore {
int maxId = inFlightForClient.isEmpty() ? 0 : Collections.max(inFlightForClient); int maxId = inFlightForClient.isEmpty() ? 0 : Collections.max(inFlightForClient);
int nextPacketId = (maxId % 0xFFFF) + 1; int nextPacketId = (maxId % 0xFFFF) + 1;
inFlightForClient.add(nextPacketId); inFlightForClient.add(nextPacketId);
if (LOG.isDebugEnabled()) { LOG.debug("Next packet ID has been generated CId={}, result={}", clientID, nextPacketId);
LOG.debug("The next packet ID has been generated. ClientId={}, result={}", clientID, nextPacketId);
}
return nextPacketId; return nextPacketId;
} }
@Override @Override
public void inFlightAck(String clientID, int messageID) { public StoredMessage inFlightAck(String clientID, int messageID) {
LOG.debug("Acknowledging inflight message. ClientId={}, messageId={}", clientID, messageID); LOG.debug("Acknowledging inflight message CId={}, messageId={}", clientID, messageID);
Map<Integer, MessageGUID> m = this.m_inflightStore.get(clientID); ConcurrentMap<Integer, StoredMessage> m = this.outboundFlightMessages.get(clientID);
if (m == null) { if (m == null) {
LOG.warn("Unable to retrieve inflight message record. ClientId={}, messageId={}", clientID, messageID); LOG.error("Can't find the inFlight record for client <{}>", clientID);
return; throw new RuntimeException("Can't find the inFlight record for client <" + clientID + ">");
} }
m.remove(messageID); StoredMessage msg = m.remove(messageID);
this.outboundFlightMessages.put(clientID, m);
// remove from the ids store // remove from the ids store
Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID); Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID);
if (inFlightForClient != null) { if (inFlightForClient != null) {
inFlightForClient.remove(messageID); inFlightForClient.remove(messageID);
} }
return msg;
} }
@Override @Override
public void inFlight(String clientID, int messageID, MessageGUID guid) { public void inFlight(String clientID, int messageID, StoredMessage msg) {
LOG.debug("Storing inflight message. ClientId={}, messageId={}, guid={}", clientID, messageID, guid); ConcurrentMap<Integer, StoredMessage> messages = outboundFlightMessages.get(clientID);
ConcurrentMap<Integer, MessageGUID> m = this.m_inflightStore.get(clientID); if (messages == null) {
if (m == null) { messages = new ConcurrentHashMap<>();
m = new ConcurrentHashMap<>();
} }
m.put(messageID, guid); messages.put(messageID, msg);
LOG.info("storing inflight clientID <{}> messageID {} guid <{}>", clientID, messageID, guid); outboundFlightMessages.put(clientID, messages);
this.m_inflightStore.put(clientID, m);
} }
@Override @Override
@@ -250,78 +247,67 @@ class MapDBSessionsStore implements ISessionsStore {
} }
@Override @Override
public void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID) { public void moveInFlightToSecondPhaseAckWaiting(String clientID, int messageID, StoredMessage msg) {
if (LOG.isDebugEnabled()) { LOG.debug("Moving inflight message to 2nd phase ack state. ClientId={}, messageID={}", clientID, messageID);
LOG.debug("Moving inflight message to 2nd phase ack state. ClientId={}, messageID={}", clientID, messageID); ConcurrentMap<Integer, StoredMessage> m = this.m_secondPhaseStore.get(clientID);
}
Map<Integer, MessageGUID> m = this.m_inflightStore.get(clientID);
if (m == null) { if (m == null) {
LOG.warn("Unable to retrieve inflight message record. ClientId={}, messageId={}", clientID, messageID); String error = String.format("Can't find the inFlight record for client <%s> during the second phase of " +
return; "QoS2 pub", clientID);
LOG.error(error);
throw new RuntimeException(error);
} }
MessageGUID guid = m.remove(messageID); m.put(messageID, msg);
this.outboundFlightMessages.put(clientID, m);
// remove from the ids store
Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID);
if (inFlightForClient != null) {
inFlightForClient.remove(messageID);
}
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
Map<Integer, MessageGUID> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, emptyGuids);
messageIDs.put(messageID, guid);
m_secondPhaseStore.put(clientID, messageIDs);
} }
@Override @Override
public MessageGUID secondPhaseAcknowledged(String clientID, int messageID) { public StoredMessage secondPhaseAcknowledged(String clientID, int messageID) {
if (LOG.isDebugEnabled()) { LOG.debug("Processing second phase ACK CId={}, messageId={}", clientID, messageID);
LOG.debug("Processing second phase ACK CId={}, messageId={}", clientID, messageID); final ConcurrentMap<Integer, StoredMessage> m = this.m_secondPhaseStore.get(clientID);
if (m == null) {
String error = String.format("Can't find the inFlight record for client <%s> during the second phase " +
"acking of QoS2 pub", clientID);
LOG.error(error);
throw new RuntimeException(error);
} }
final HashMap<Integer, MessageGUID> emptyGuids = new HashMap<>();
Map<Integer, MessageGUID> messageIDs = Utils.defaultGet(m_secondPhaseStore, clientID, emptyGuids);
MessageGUID guid = messageIDs.remove(messageID);
m_secondPhaseStore.put(clientID, messageIDs);
return guid;
}
@Override StoredMessage msg = m.remove(messageID);
public StoredMessage getInflightMessage(String clientID, int messageID) { m_secondPhaseStore.put(clientID, m);
LOG.info("Retrieving inflight message CId={}, messageId={}", clientID, messageID); return msg;
Map<Integer, MessageGUID> clientEntries = m_inflightStore.get(clientID);
if (clientEntries == null) {
LOG.warn("The client has no inflight messages CId={}, messageId={}", clientID, messageID);
return null;
}
MessageGUID guid = clientEntries.get(messageID);
if (guid == null) {
LOG.warn("The message ID does not have an associated GUID. ClientId={}, messageId={}", clientID, messageID);
return null;
}
return m_messagesStore.getMessageByGuid(guid);
} }
@Override @Override
public int getInflightMessagesNo(String clientID) { public int getInflightMessagesNo(String clientID) {
if (!m_inflightStore.containsKey(clientID)) int totalInflight = 0;
return 0; ConcurrentMap<Integer, StoredMessage> inflightPerClient = m_db.getHashMap(inboundMessageId2MessagesMapName(clientID));
else if (inflightPerClient != null) {
return m_inflightStore.get(clientID).size(); totalInflight += inflightPerClient.size();
}
Map<Integer, StoredMessage> secondPhaseInFlight = this.m_secondPhaseStore.get(clientID);
if (secondPhaseInFlight != null) {
totalInflight += secondPhaseInFlight.size();
}
Map<Integer, StoredMessage> outboundPerClient = outboundFlightMessages.get(clientID);
if (outboundPerClient != null) {
totalInflight += outboundPerClient.size();
}
return totalInflight;
} }
@Override @Override
public StoredMessage inboundInflight(String clientID, int messageID) { public StoredMessage inboundInflight(String clientID, int messageID) {
LOG.debug("Mapping inbound message ID to GUID CId={}, messageId={}", clientID, messageID); LOG.debug("Mapping inbound message ID to GUID CId={}, messageId={}", clientID, messageID);
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(inboundMessageId2GuidsMapName(clientID)); ConcurrentMap<Integer, StoredMessage> messageIdToGuid = m_db.getHashMap(inboundMessageId2MessagesMapName(clientID));
final MessageGUID guid = messageIdToGuid.get(messageID); return messageIdToGuid.get(messageID);
LOG.debug("Inbound message ID has been mapped CId={}, messageId={}, guid={}", clientID, messageID, guid);
return m_messagesStore.getMessageByGuid(guid);
} }
@Override @Override
public void markAsInboundInflight(String clientID, int messageID, MessageGUID guid) { public void markAsInboundInflight(String clientID, int messageID, StoredMessage msg) {
ConcurrentMap<Integer, MessageGUID> messageIdToGuid = m_db.getHashMap(inboundMessageId2GuidsMapName(clientID)); ConcurrentMap<Integer, StoredMessage> messageIdToGuid = m_db.getHashMap(inboundMessageId2MessagesMapName(clientID));
messageIdToGuid.put(messageID, guid); messageIdToGuid.put(messageID, msg);
} }
@Override @Override
@@ -333,25 +319,16 @@ class MapDBSessionsStore implements ISessionsStore {
public int getSecondPhaseAckPendingMessages(String clientID) { public int getSecondPhaseAckPendingMessages(String clientID) {
if (!m_secondPhaseStore.containsKey(clientID)) if (!m_secondPhaseStore.containsKey(clientID))
return 0; return 0;
else return m_secondPhaseStore.get(clientID).size();
return m_secondPhaseStore.get(clientID).size();
} }
@Override @Override
public Collection<MessageGUID> pendingAck(String clientID) { public void dropInFlightMessagesInSession(String clientID) {
ConcurrentMap<Integer, MessageGUID> messageGUIDMap = m_db.getHashMap(messageId2GuidsMapName(clientID)); m_secondPhaseStore.remove(clientID);
if (messageGUIDMap == null || messageGUIDMap.isEmpty()) { outboundFlightMessages.remove(clientID);
return Collections.emptyList();
}
return new ArrayList<>(messageGUIDMap.values());
} }
static String messageId2GuidsMapName(String clientID) { static String inboundMessageId2MessagesMapName(String clientID) {
return "guidsMapping_" + clientID; return "inboundInflight_" + clientID;
}
static String inboundMessageId2GuidsMapName(String clientID) {
return "inboundInflightGuidsMapping_" + clientID;
} }
} }
@@ -17,40 +17,30 @@
package io.moquette.persistence.mapdb; package io.moquette.persistence.mapdb;
import io.moquette.BrokerConstants; import io.moquette.BrokerConstants;
import io.moquette.persistence.MessageStoreTCK;
import io.moquette.server.config.IConfig; import io.moquette.server.config.IConfig;
import io.moquette.server.config.MemoryConfig; import io.moquette.server.config.MemoryConfig;
import io.moquette.spi.ClientSession; import io.moquette.spi.IMessagesStore.StoredMessage;
import io.moquette.spi.IMessagesStore; import io.netty.handler.codec.mqtt.MqttQoS;
import io.moquette.spi.ISessionsStore;
import io.moquette.spi.ISessionsStore.ClientTopicCouple;
import io.moquette.spi.MessageGUID;
import io.moquette.spi.impl.subscriptions.Subscription;
import io.moquette.spi.impl.subscriptions.Topic;
import static io.netty.handler.codec.mqtt.MqttQoS.*;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.File; import java.io.File;
import java.util.List;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static java.util.Collections.singletonList;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
* *
* @author andrea * @author andrea
*/ */
public class MapDBPersistentStoreTest { public class MapDBPersistentStoreTest extends MessageStoreTCK {
public static final String TEST_CLIENT = "TestClient";
MapDBPersistentStore m_storageService; MapDBPersistentStore m_storageService;
ISessionsStore m_sessionsStore;
IMessagesStore m_messagesStore;
private ScheduledExecutorService scheduler; private ScheduledExecutorService scheduler;
@@ -64,8 +54,8 @@ public class MapDBPersistentStoreTest {
IConfig conf = new MemoryConfig(props); IConfig conf = new MemoryConfig(props);
m_storageService = new MapDBPersistentStore(conf, scheduler); m_storageService = new MapDBPersistentStore(conf, scheduler);
m_storageService.initStore(); m_storageService.initStore();
m_messagesStore = m_storageService.messagesStore(); messagesStore = m_storageService.messagesStore();
m_sessionsStore = m_storageService.sessionsStore(); sessionsStore = m_storageService.sessionsStore();
} }
@After @After
@@ -88,56 +78,38 @@ public class MapDBPersistentStoreTest {
assertFalse(dbFile.exists()); assertFalse(dbFile.exists());
} }
@Test
public void overridingSubscriptions() {
ClientSession session1 = m_sessionsStore.createNewSession("SESSION_ID_1", true);
// Subscribe on /topic with QOSType.MOST_ONE
Subscription oldSubscription = new Subscription(session1.clientID, new Topic("/topic"), AT_MOST_ONCE);
session1.subscribe(oldSubscription);
// Subscribe on /topic again that overrides the previous subscription.
Subscription overridingSubscription = new Subscription(session1.clientID, new Topic("/topic"), EXACTLY_ONCE);
session1.subscribe(overridingSubscription);
// Verify
List<ClientTopicCouple> subscriptions = m_sessionsStore.listAllSubscriptions();
assertEquals(1, subscriptions.size());
Subscription sub = m_sessionsStore.getSubscription(subscriptions.get(0));
assertEquals(overridingSubscription.getRequestedQos(), sub.getRequestedQos());
}
@Test @Test
public void testNextPacketID_notExistingClientSession() { public void testNextPacketID_notExistingClientSession() {
int packetId = m_sessionsStore.nextPacketID("NOT_EXISTING_CLI"); int packetId = sessionsStore.nextPacketID("NOT_EXISTING_CLI");
assertEquals(1, packetId); assertEquals(1, packetId);
} }
@Test @Test
public void testNextPacketID_existingClientSession() { public void testNextPacketID_existingClientSession() {
// Force creation of inflight map for the CLIENT session // Force creation of inflight map for the CLIENT session
int packetId = m_sessionsStore.nextPacketID("CLIENT"); int packetId = sessionsStore.nextPacketID("CLIENT");
assertEquals(1, packetId); assertEquals(1, packetId);
// request a second packetID // request a second packetID
packetId = m_sessionsStore.nextPacketID("CLIENT"); packetId = sessionsStore.nextPacketID("CLIENT");
assertEquals(2, packetId); assertEquals(2, packetId);
} }
@Test @Test
public void testNextPacketID() { public void testNextPacketID() {
// request a first ID StoredMessage msgStored = new StoredMessage("Hello".getBytes(), MqttQoS.AT_LEAST_ONCE, "/topic");
msgStored.setClientID(TEST_CLIENT);
int packetId = m_sessionsStore.nextPacketID("CLIENT"); // request a first ID
m_sessionsStore.inFlight("CLIENT", packetId, new MessageGUID("ABCDE")); // simulate an int packetId = sessionsStore.nextPacketID("CLIENT");
// inflight sessionsStore.inFlight("CLIENT", packetId, msgStored); // simulate an inflight
assertEquals(1, packetId); assertEquals(1, packetId);
// release the ID // release the ID
m_sessionsStore.inFlightAck("CLIENT", packetId); sessionsStore.inFlightAck("CLIENT", packetId);
// request a second packetID, counter restarts from 0 // request a second packetID, counter restarts from 0
packetId = m_sessionsStore.nextPacketID("CLIENT"); packetId = sessionsStore.nextPacketID("CLIENT");
assertEquals(1, packetId); assertEquals(1, packetId);
} }
@@ -146,44 +118,8 @@ public class MapDBPersistentStoreTest {
m_storageService.close(); m_storageService.close();
// verify the executor is shutdown // verify the executor is shutdown
assertTrue( assertTrue("Storage service scheduler can't be stopped in 3 seconds",
"Storage service scheduler can't be stopped in 3 seconds",
m_storageService.m_scheduler.awaitTermination(3, TimeUnit.SECONDS)); m_storageService.m_scheduler.awaitTermination(3, TimeUnit.SECONDS));
assertTrue(m_storageService.m_scheduler.isTerminated()); assertTrue(m_storageService.m_scheduler.isTerminated());
} }
@Test
public void testDropMessagesInSessionCleanAllNotRetainedStoredMessages() {
m_sessionsStore.createNewSession(TEST_CLIENT, true);
IMessagesStore.StoredMessage publishToStore = new IMessagesStore.StoredMessage("Hello".getBytes(), EXACTLY_ONCE,
"/topic");
publishToStore.setClientID(TEST_CLIENT);
publishToStore.setRetained(false);
MessageGUID guid = m_messagesStore.storePublishForFuture(publishToStore);
// Exercise
m_messagesStore.dropInFlightMessagesInSession(singletonList(guid));
// Verify the message store for session is empty.
IMessagesStore.StoredMessage storedPublish = m_messagesStore.getMessageByGuid(guid);
assertNull("The stored message must'n be present anymore", storedPublish);
}
@Test
public void testDropMessagesInSessionDoesntCleanAnyRetainedStoredMessages() {
m_sessionsStore.createNewSession(TEST_CLIENT, true);
IMessagesStore.StoredMessage publishToStore = new IMessagesStore.StoredMessage("Hello".getBytes(), EXACTLY_ONCE,
"/topic");
publishToStore.setClientID(TEST_CLIENT);
publishToStore.setRetained(true);
MessageGUID guid = m_messagesStore.storePublishForFuture(publishToStore);
m_messagesStore.storeRetained(new Topic("/topic"), guid);
// Exercise
m_messagesStore.dropInFlightMessagesInSession(singletonList(guid));
// Verify the message store for session is empty.
IMessagesStore.StoredMessage storedPublish = m_messagesStore.getMessageByGuid(guid);
assertNotNull("The stored retained message must be present after client's session drop", storedPublish);
}
} }
@@ -34,7 +34,7 @@ public final class PerformanceTest {
cpufreq-set -g performance -u 800MHz -c 3 cpufreq-set -g performance -u 800MHz -c 3
*/ */
public static void main(String[] args) throws IOException, InterruptedException { public static void main(String[] args) throws IOException, InterruptedException {
SubscriptionsStore store = new SubscriptionsStore(); SubscriptionsDirectory store = new SubscriptionsDirectory();
MemoryStorageService memStore = new MemoryStorageService(); MemoryStorageService memStore = new MemoryStorageService();
ISessionsStore aSessionsStore = memStore.sessionsStore(); ISessionsStore aSessionsStore = memStore.sessionsStore();
store.init(aSessionsStore); store.init(aSessionsStore);
@@ -56,7 +56,7 @@ public final class PerformanceTest {
+ ((i / (users * devices * values)) % subs)); + ((i / (users * devices * values)) % subs));
Subscription sub = new Subscription("CLI_ID_" + (i % users), topics[i], MqttQoS.AT_MOST_ONCE); Subscription sub = new Subscription("CLI_ID_" + (i % users), topics[i], MqttQoS.AT_MOST_ONCE);
aSessionsStore.addNewSubscription(sub); aSessionsStore.subscriptionStore().addNewSubscription(sub);
store.add(sub.asClientTopicCouple()); store.add(sub.asClientTopicCouple());
} }
+1
View File
@@ -110,6 +110,7 @@
<modules> <modules>
<module>broker</module> <module>broker</module>
<module>mapdb_storage</module> <module>mapdb_storage</module>
<module>h2_storage</module>
<module>distribution</module> <module>distribution</module>
<module>embedding_moquette</module> <module>embedding_moquette</module>
<module>osgi_test</module> <module>osgi_test</module>