Introduced 'fat' ClientSession class responsible to model the concept of an MQTT client session

This commit is contained in:
andsel
2015-11-08 18:42:03 +01:00
parent 0b5c95ee57
commit c793ded63e
11 changed files with 184 additions and 106 deletions
@@ -96,8 +96,8 @@ public class ServerIntegrationFuseTest {
}
@Test
public void checkWillTestmaentIsPublishedOnConnectionKill_noRetain() throws Exception {
LOG.info("checkWillTestmaentIsPublishedOnConnectionKill");
public void checkWillTestamentIsPublishedOnConnectionKill_noRetain() throws Exception {
LOG.info("checkWillTestamentIsPublishedOnConnectionKill");
String willTestamentTopic = "/will/test";
String willTestamentMsg = "Bye bye";
@@ -15,6 +15,8 @@
*/
package org.eclipse.moquette.spi.impl;
import org.eclipse.moquette.spi.ClientSession;
import org.eclipse.moquette.spi.IMessagesStore;
import org.eclipse.moquette.spi.ISessionsStore;
import org.eclipse.moquette.spi.impl.subscriptions.Subscription;
import org.slf4j.Logger;
@@ -24,13 +26,19 @@ import java.util.*;
/**
*
* @author andrea
* @author andream_messagesStore
*/
public class MemorySessionStore implements ISessionsStore {
private static final Logger LOG = LoggerFactory.getLogger(MemorySessionStore.class);
private Map<String, Set<Subscription>> m_persistentSubscriptions = new HashMap<>();
private final IMessagesStore m_messagesStore;
public MemorySessionStore(IMessagesStore messagesStore) {
this.m_messagesStore = messagesStore;
}
@Override
public void removeSubscription(String topic, String clientID) {
LOG.debug("removeSubscription topic filter: {} for clientID: {}", topic, clientID);
@@ -82,12 +90,24 @@ public class MemorySessionStore implements ISessionsStore {
}
@Override
public void createNewSession(String clientID) {
public ClientSession createNewSession(String clientID) {
LOG.debug("createNewSession for client <{}>", clientID);
if (m_persistentSubscriptions.containsKey(clientID)) {
LOG.error("already exists a session for client <{}>", clientID);
return;
LOG.error("already exists a session for client <{}>, bad condition", clientID);
throw new IllegalArgumentException("Can't create a session with the ID of an already existing" + clientID);
}
LOG.debug("clientID {} is a newcome, creating it's empty subscriptions set", clientID);
m_persistentSubscriptions.put(clientID, new HashSet<Subscription>());
return new ClientSession(clientID, m_messagesStore);
}
@Override
public ClientSession sessionForClient(String clientID) {
if (!m_persistentSubscriptions.containsKey(clientID)) {
return null;
}
return new ClientSession(clientID, m_messagesStore);
}
@Override
@@ -0,0 +1,222 @@
/*
* Copyright (c) 2012-2015 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 org.eclipse.moquette.spi.impl;
import java.nio.ByteBuffer;
import java.util.*;
import jdk.nashorn.internal.objects.NativeJava;
import org.eclipse.moquette.spi.ClientSession;
import org.eclipse.moquette.spi.IMatchingCondition;
import org.eclipse.moquette.spi.IMessagesStore;
import org.eclipse.moquette.spi.impl.events.PublishEvent;
import org.eclipse.moquette.spi.impl.subscriptions.Subscription;
import org.eclipse.moquette.proto.messages.AbstractMessage;
import org.eclipse.moquette.spi.ISessionsStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.eclipse.moquette.spi.impl.Utils.defaultGet;
/**
*/
public class MemoryStorageService implements IMessagesStore, ISessionsStore {
private Map<String, StoredMessage> m_retainedStore = new HashMap<>();
//TODO move in a multimap because only Qos1 and QoS2 are stored here and they have messageID(key of secondary map)
private Map<String, List<PublishEvent>> m_persistentMessageStore = new HashMap<>();
private Map<String, PublishEvent> m_inflightStore = new HashMap<>();
private Map<String, Set<Integer>> m_inflightIDs = new HashMap<>();
private Map<String, PublishEvent> m_qos2Store = new HashMap<>();
private MemorySessionStore m_sessionsStore;
private static final Logger LOG = LoggerFactory.getLogger(MemoryStorageService.class);
public void initStore() {
m_sessionsStore = new MemorySessionStore(this);
}
@Override
public void cleanRetained(String topic) {
m_retainedStore.remove(topic);
}
@Override
public void storeRetained(String topic, ByteBuffer message, AbstractMessage.QOSType qos) {
if (!message.hasRemaining()) {
//clean the message from topic
m_retainedStore.remove(topic);
} else {
//store the message to the topic
byte[] raw = new byte[message.remaining()];
message.get(raw);
m_retainedStore.put(topic, new StoredMessage(raw, qos, topic));
}
}
@Override
public Collection<StoredMessage> searchMatching(IMatchingCondition condition) {
LOG.debug("searchMatching scanning all retained messages, presents are {}", m_retainedStore.size());
List<StoredMessage> results = new ArrayList<>();
for (Map.Entry<String, StoredMessage> entry : m_retainedStore.entrySet()) {
StoredMessage storedMsg = entry.getValue();
if (condition.match(entry.getKey())) {
results.add(storedMsg);
}
}
return results;
}
@Override
public void storePublishForFuture(PublishEvent evt) {
LOG.debug("storePublishForFuture store evt {}", evt);
String clientID = evt.getClientID();
List<PublishEvent> storedEvents = defaultGet(m_persistentMessageStore, clientID, new ArrayList<PublishEvent>());
storedEvents.add(evt);
m_persistentMessageStore.put(clientID, storedEvents);
}
@Override
public List<PublishEvent> listMessagesInSession(String clientID) {
return new ArrayList<>(defaultGet(m_persistentMessageStore, clientID, Collections.<PublishEvent>emptyList()));
}
@Override
public void removeMessageInSession(String clientID, Integer messageID) {
List<PublishEvent> events = m_persistentMessageStore.get(clientID);
if (events == null) {
return;
}
PublishEvent toRemoveEvt = null;
for (PublishEvent evt : events) {
if (evt.getMessageID() == null && messageID == null) {
//was a qos0 message (no ID)
toRemoveEvt = evt;
}
if (evt.getMessageID() == messageID) {
toRemoveEvt = evt;
}
}
events.remove(toRemoveEvt);
m_persistentMessageStore.put(clientID, events);
}
@Override
public void dropMessagesInSession(String clientID) {
m_persistentMessageStore.remove(clientID);
}
@Override
public void cleanTemporaryPublish(String clientID, int packetID) {
String publishKey = String.format("%s%d", clientID, packetID);
m_inflightStore.remove(publishKey);
Set<Integer> inFlightForClient = m_inflightIDs.get(clientID);
if (inFlightForClient != null) {
inFlightForClient.remove(packetID);
}
}
@Override
public void storeTemporaryPublish(PublishEvent evt, String clientID, int packetID) {
String publishKey = String.format("%s%d", clientID, packetID);
m_inflightStore.put(publishKey, evt);
}
/**
* Return the next valid packetIdentifier for the given client session.
* */
@Override
public int nextPacketID(String clientID) {
Set<Integer> inFlightForClient = m_inflightIDs.get(clientID);
if (inFlightForClient == null) {
int nextPacketId = 1;
inFlightForClient = new HashSet<>();
inFlightForClient.add(nextPacketId);
m_inflightIDs.put(clientID, inFlightForClient);
return nextPacketId;
}
int maxId = Collections.max(inFlightForClient);
int nextPacketId = (maxId + 1) % 0xFFFF;
inFlightForClient.add(nextPacketId);
return nextPacketId;
}
@Override
public void close() {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void persistQoS2Message(String publishKey, PublishEvent evt) {
LOG.debug("persistQoS2Message store pubKey {}, evt {}", publishKey, evt);
m_qos2Store.put(publishKey, evt);
}
@Override
public void removeQoS2Message(String publishKey) {
m_qos2Store.remove(publishKey);
}
@Override
public PublishEvent retrieveQoS2Message(String publishKey) {
return m_qos2Store.get(publishKey);
}
@Override
public void addNewSubscription(Subscription newSubscription) {
m_sessionsStore.addNewSubscription(newSubscription);
}
@Override
public void removeSubscription(String topic, String clientID) {
m_sessionsStore.removeSubscription(topic, clientID);
}
@Override
public void wipeSubscriptions(String sessionID) {
m_sessionsStore.wipeSubscriptions(sessionID);
}
@Override
public void updateSubscriptions(String clientID, Set<Subscription> subscriptions) {
m_sessionsStore.updateSubscriptions(clientID, subscriptions);
}
@Override
public List<Subscription> listAllSubscriptions() {
return m_sessionsStore.listAllSubscriptions();
}
@Override
public boolean contains(String clientID) {
return m_sessionsStore.contains(clientID);
}
@Override
public ClientSession createNewSession(String clientID) {
return m_sessionsStore.createNewSession(clientID);
}
@Override
public ClientSession sessionForClient(String clientID) {
return m_sessionsStore.sessionForClient(clientID);
}
}
@@ -75,6 +75,7 @@ public class ProtocolProcessorTest {
//sleep to let the messaging batch processor to process the initEvent
Thread.sleep(300);
MemoryStorageService memStorage = new MemoryStorageService();
memStorage.initStore();
m_storageService = memStorage;
m_sessionStore = memStorage;
//m_storageService.initStore();
@@ -84,7 +85,7 @@ public class ProtocolProcessorTest {
m_mockAuthenticator = new MockAuthenticator(users);
subscriptions = new SubscriptionsStore();
subscriptions.init(new MemoryStorageService());
subscriptions.init(memStorage);
m_processor = new ProtocolProcessor();
m_processor.init(subscriptions, m_storageService, m_sessionStore, m_mockAuthenticator, true,
new PermitAllAuthorizator(), NO_OBSERVERS_INTERCEPTOR);
@@ -109,7 +110,9 @@ public class ProtocolProcessorTest {
};
//simulate a connect that register a clientID to an IoSession
subs.init(new MemoryStorageService());
MemoryStorageService storageService = new MemoryStorageService();
storageService.initStore();
subs.init(storageService);
m_processor.init(subs, m_storageService, m_sessionStore, null, true, new PermitAllAuthorizator(), NO_OBSERVERS_INTERCEPTOR);
ConnectMessage connectMessage = new ConnectMessage();
connectMessage.setProtocolVersion((byte) 3);
@@ -153,7 +156,9 @@ public class ProtocolProcessorTest {
};
//simulate a connect that register a clientID to an IoSession
subs.init(new MemoryStorageService());
MemoryStorageService storageService = new MemoryStorageService();
storageService.initStore();
subs.init(storageService);
m_processor.init(subs, m_storageService, m_sessionStore, null, true, new PermitAllAuthorizator(), NO_OBSERVERS_INTERCEPTOR);
MockReceiverChannel firstReceiverSession = new MockReceiverChannel();
@@ -306,8 +311,10 @@ public class ProtocolProcessorTest {
}
}
};
subs.init(new MemoryStorageService());
MemoryStorageService storageService = new MemoryStorageService();
storageService.initStore();
subs.init(storageService);
//simulate a connect that register a clientID to an IoSession
m_processor.init(subs, m_storageService, m_sessionStore, null, true, new PermitAllAuthorizator(), NO_OBSERVERS_INTERCEPTOR);
ConnectMessage connectMessage = new ConnectMessage();
@@ -457,7 +464,7 @@ public class ProtocolProcessorTest {
Subscription subQos1 = new Subscription("Sub A", "a/b", QOSType.LEAST_ONE, false);
Subscription subQos2 = new Subscription("Sub B", "a/+", QOSType.EXACTLY_ONCE, false);
SubscriptionsStore subscriptions = new SubscriptionsStore();
subscriptions.init(new MemorySessionStore());
subscriptions.init(new MemorySessionStore(memoryMessageStore));
subscriptions.add(subQos1);
subscriptions.add(subQos2);
@@ -59,6 +59,7 @@ public class ProtocolProcessor_CONNECT_Test {
//sleep to let the messaging batch processor to process the initEvent
Thread.sleep(300);
MemoryStorageService memStorage = new MemoryStorageService();
memStorage.initStore();
m_storageService = memStorage;
m_sessionStore = memStorage;
//m_storageService.initStore();
@@ -68,7 +69,7 @@ public class ProtocolProcessor_CONNECT_Test {
m_mockAuthenticator = new MockAuthenticator(users);
subscriptions = new SubscriptionsStore();
subscriptions.init(new MemoryStorageService());
subscriptions.init(memStorage);
m_processor = new ProtocolProcessor();
m_processor.init(subscriptions, m_storageService, m_sessionStore, m_mockAuthenticator, true,
new PermitAllAuthorizator(), ProtocolProcessorTest.NO_OBSERVERS_INTERCEPTOR);
@@ -41,7 +41,9 @@ public class SubscriptionsStoreTest {
@Before
public void setUp() throws IOException {
store = new SubscriptionsStore();
store.init(new MemoryStorageService());
MemoryStorageService storageService = new MemoryStorageService();
storageService.initStore();
store.init(storageService);
}
@Test