DongyuanPan commented on code in PR #131:
URL: https://github.com/apache/rocketmq-mqtt/pull/131#discussion_r947382051
##########
mqtt-cs/src/test/java/org/apache/rocketmq/mqtt/cs/test/session/infly/TestPushAction.java:
##########
@@ -176,6 +178,10 @@ public void testPushWhenQosZero() {
doNothing().when(spyPushAction).rollNextByAck(any(), anyInt());
when(inFlyCache.getPendingDownCache()).thenReturn(new
InFlyCache().getPendingDownCache());
+ if(message.getPayload()==null){
Review Comment:
format code
##########
mqtt-ds/src/main/java/org/apache/rocketmq/mqtt/ds/retain/RetainedMsgClient.java:
##########
@@ -0,0 +1,210 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.rocketmq.mqtt.ds.retain;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import com.alipay.sofa.jraft.RouteTable;
+import com.alipay.sofa.jraft.conf.Configuration;
+import com.alipay.sofa.jraft.entity.PeerId;
+import com.alipay.sofa.jraft.error.RemotingException;
+import com.alipay.sofa.jraft.option.CliOptions;
+import com.alipay.sofa.jraft.rpc.InvokeCallback;
+import com.alipay.sofa.jraft.rpc.impl.GrpcRaftRpcFactory;
+import com.alipay.sofa.jraft.rpc.impl.MarshallerRegistry;
+import com.alipay.sofa.jraft.rpc.impl.cli.CliClientServiceImpl;
+import com.alipay.sofa.jraft.util.RpcFactoryHelper;
+import com.google.protobuf.ByteString;
+import org.apache.rocketmq.mqtt.common.model.Message;
+import org.apache.rocketmq.mqtt.common.model.consistency.ReadRequest;
+import org.apache.rocketmq.mqtt.common.model.consistency.Response;
+import org.apache.rocketmq.mqtt.common.model.consistency.WriteRequest;
+import org.apache.rocketmq.mqtt.ds.config.ServiceConf;
+import org.apache.rocketmq.mqtt.meta.raft.processor.Constants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.TimeoutException;
+
+
+@Service
+public class RetainedMsgClient {
+
+ private static Logger logger =
LoggerFactory.getLogger(RetainedMsgClient.class);
+ private static final String GROUP_SEQ_NUM_SPLIT = "-";
+ final String groupId = Constants.RETAINEDMSG + GROUP_SEQ_NUM_SPLIT + 0;
+ final Configuration conf = new Configuration();
+ static final CliClientServiceImpl CLICLIENTSERVICE = new
CliClientServiceImpl();
+
+ static final String GROUPNAME = "retainedMsg";
+ static PeerId leader;
+
+ @Resource
+ private ServiceConf serviceConf;
+
+ @PostConstruct
+ public void init() throws InterruptedException, TimeoutException {
+ initRpcServer();
+ if (!conf.parse(serviceConf.getMetaAddr())) { //from service.conf
+ throw new IllegalArgumentException("Fail to parse conf:" +
serviceConf.getMetaAddr());
+ }
+ RouteTable.getInstance().updateConfiguration(groupId, conf);
+
+ CLICLIENTSERVICE.init(new CliOptions());
+
+ if (!RouteTable.getInstance().refreshLeader(CLICLIENTSERVICE, groupId,
3000).isOk()) {
+ throw new IllegalStateException("Refresh leader failed");
+ }
+
+ leader = RouteTable.getInstance().selectLeader(groupId);
+ logger.info("--------------------- Leader is " + leader + "
---------------------------");
+ }
+
+ public static void initRpcServer() {
+ GrpcRaftRpcFactory raftRpcFactory = (GrpcRaftRpcFactory)
RpcFactoryHelper.rpcFactory();
+
raftRpcFactory.registerProtobufSerializer(WriteRequest.class.getName(),
WriteRequest.getDefaultInstance());
+ raftRpcFactory.registerProtobufSerializer(ReadRequest.class.getName(),
ReadRequest.getDefaultInstance());
+ raftRpcFactory.registerProtobufSerializer(Response.class.getName(),
Response.getDefaultInstance());
+
+ MarshallerRegistry registry = raftRpcFactory.getMarshallerRegistry();
+ registry.registerResponseInstance(WriteRequest.class.getName(),
Response.getDefaultInstance());
+ registry.registerResponseInstance(ReadRequest.class.getName(),
Response.getDefaultInstance());
+ }
+
+ public static void SetRetainedMsg(String topic, Message msg,
CompletableFuture<Boolean> future) throws RemotingException,
InterruptedException {
+
+ HashMap<String, String> option = new HashMap<>();
+ option.put("topic", topic);
+ option.put("firstTopic", msg.getFirstTopic());
+ option.put("isEmpty", String.valueOf(msg.isEmpty()));
+
+ logger.debug("SetRetainedMsg option:" + option);
+
+ final WriteRequest request =
WriteRequest.newBuilder().setGroup(GROUPNAME + GROUP_SEQ_NUM_SPLIT +
"0").setData(ByteString.copyFrom(JSON.toJSONBytes(msg,
SerializerFeature.WriteClassName))).putAllExtData(option).build();
+
+ CLICLIENTSERVICE.getRpcClient().invokeAsync(leader.getEndpoint(),
request, new InvokeCallback() {
+ @Override
+ public void complete(Object result, Throwable err) {
+ if (err == null) {
+ Response rsp = (Response) result;
+ if (!rsp.getSuccess()) {
+ logger.info("SetRetainedMsg failed. {}",
rsp.getErrMsg());
+ return;
+ }
+ logger.info("-------------------------------SetRetainedMsg
success.----------------------------------");
+ future.complete(true);
+ } else {
+
logger.debug("-------------------------------SetRetainedMsg
fail.-------------------------------------");
+ logger.error("", err);
+ future.complete(false);
+ }
+ }
+
+ @Override
+ public Executor executor() {
+ return null;
+ }
+ }, 5000);
+
+ }
+
+ public static void GetRetainedMsgsFromTrie(String firstTopic, String
topic, CompletableFuture<ArrayList<String>> future) throws RemotingException,
InterruptedException {
+ HashMap<String, String> option = new HashMap<>();
+
+ option.put("firstTopic", firstTopic);
+ option.put("topic", topic);
+
+ logger.debug("GetRetainedMsgsFromTrie option:" + option);
+
+ final ReadRequest request =
ReadRequest.newBuilder().setGroup(GROUPNAME + GROUP_SEQ_NUM_SPLIT +
"0").setOperation("trie").setType(Constants.READ_INDEX_TYPE).putAllExtData(option).build();
+
+ CLICLIENTSERVICE.getRpcClient().invokeAsync(leader.getEndpoint(),
request, new InvokeCallback() {
+ @Override
+ public void complete(Object result, Throwable err) {
+ if (err == null) {
+ Response rsp = (Response) result;
+ if (!rsp.getSuccess()) {
+ logger.info("GetRetainedTopicTrie failed. {}",
rsp.getErrMsg());
+ return;
+ }
+ byte[] bytes = rsp.getData().toByteArray();
+ ArrayList<String> resultList = JSON.parseObject(new
String(bytes), ArrayList.class);
Review Comment:
ArrayList<String> resultList can be ArrayList<Mesage>. In this way, there
is no need to deserialize outside
##########
mqtt-ds/src/main/java/org/apache/rocketmq/mqtt/ds/meta/RetainedPersistManagerImpl.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.rocketmq.mqtt.ds.meta;
+
+
+import com.alipay.sofa.jraft.error.RemotingException;
+
+import org.apache.rocketmq.mqtt.common.facade.MetaPersistManager;
+import org.apache.rocketmq.mqtt.common.facade.RetainedPersistManager;
+import org.apache.rocketmq.mqtt.common.model.Message;
+import org.apache.rocketmq.mqtt.common.model.Subscription;
+
+import org.apache.rocketmq.mqtt.ds.retain.RetainedMsgClient;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+
+
+import java.util.concurrent.CompletableFuture;
+
+
+public class RetainedPersistManagerImpl implements RetainedPersistManager {
+
+ private static Logger logger =
LoggerFactory.getLogger(RetainedPersistManagerImpl.class);
+ @Resource
+ private MetaPersistManager metaPersistManager;
+
+ public CompletableFuture<Boolean> storeRetainedMessage(String topic,
Message message) {
+ CompletableFuture<Boolean> result = new CompletableFuture<>();
+
+ if
(!metaPersistManager.getAllFirstTopics().contains(message.getFirstTopic())) {
+ logger.info("Put retained message of topic {} into meta failed.
Because first topic {} does not exist...", topic, message.getFirstTopic());
+ result.complete(false);
+ return result;
+ }
+ logger.debug("Start store retain msg...");
+
+ try {
+ RetainedMsgClient.SetRetainedMsg(topic, message, result);
+ } catch (RemotingException | InterruptedException e) {
+ logger.error("", e);
+ result.completeExceptionally(e);
+ }
+
+ return result;
+ }
+
+ public CompletableFuture<Message> getRetainedMessage(String preciseTopic)
{ //precise preciseTopic
+ CompletableFuture<Message> future = new CompletableFuture<>();
+ logger.debug("topic:" + preciseTopic);
+ try {
+ RetainedMsgClient.GetRetainedMsg(preciseTopic, future);
+ } catch (RemotingException | InterruptedException e) {
+ logger.error("", e);
+ future.completeExceptionally(e);
+ }
+ return future;
+ }
+
+ public CompletableFuture<ArrayList<String>> getMsgsFromTrie(Subscription
subscription) {
+ String firstTopic = subscription.toFirstTopic();
+ String originTopicFilter = subscription.getTopicFilter();
+ logger.debug("firstTopic={} originTopicFilter={}", firstTopic,
originTopicFilter);
+
+ CompletableFuture<ArrayList<String>> future = new
CompletableFuture<>();
+ try {
+ RetainedMsgClient.GetRetainedMsgsFromTrie(firstTopic,
originTopicFilter,future);
Review Comment:
originTopicFilter,future format code
##########
mqtt-cs/src/main/java/org/apache/rocketmq/mqtt/cs/protocol/mqtt/handler/MqttSubscribeHandler.java:
##########
@@ -128,4 +160,66 @@ private MqttSubAckMessage getResponse(MqttSubscribeMessage
mqttSubscribeMessage)
return mqttSubAckMessage;
}
+
+ @SuppressWarnings("checkstyle:Indentation")
+ private void sendRetainMessage(ChannelHandlerContext ctx,
Set<Subscription> subscriptions) throws InterruptedException,
RemotingException, org.apache.rocketmq.remoting.exception.RemotingException {
+
+ String clientId = ChannelInfo.getClientId(ctx.channel());
+ Session session =
sessionLoop.getSession(ChannelInfo.getId(ctx.channel()));
+ Set<Subscription> preciseTopics = new HashSet<>();
+ Set<Subscription> wildcardTopics = new HashSet<>();
+
+ for (Subscription subscription : subscriptions) {
+ if (!TopicUtils.isWildCard(subscription.getTopicFilter())) {
+ preciseTopics.add(subscription);
+ } else {
+ wildcardTopics.add(subscription);
+ }
+ }
+
+ for (Subscription subscription : preciseTopics) {
+ CompletableFuture<Message> retainedMessage =
retainedPersistManager.getRetainedMessage(subscription.getTopicFilter());
+ retainedMessage.whenComplete((msg, throwable) -> {
+ if (msg == null) {
+ return;
+ }
+ _sendMessage(session, clientId, subscription, msg);
+ });
+ }
+
+ for (Subscription subscription : wildcardTopics) {
+
+ CompletableFuture<ArrayList<String>> future =
retainedPersistManager.getMsgsFromTrie(subscription);
+ future.whenComplete((msgsList,throwable) -> {
+ ArrayList<Message> results = new ArrayList<>();
+ for (String strMsg:msgsList) {
+ results.add(JSON.parseObject(strMsg,Message.class));
Review Comment:
results.add(JSON.parseObject(strMsg,Message.class)); Can it be optimized
here?
##########
mqtt-cs/src/main/java/org/apache/rocketmq/mqtt/cs/protocol/mqtt/handler/MqttSubscribeHandler.java:
##########
@@ -128,4 +160,66 @@ private MqttSubAckMessage getResponse(MqttSubscribeMessage
mqttSubscribeMessage)
return mqttSubAckMessage;
}
+
+ @SuppressWarnings("checkstyle:Indentation")
+ private void sendRetainMessage(ChannelHandlerContext ctx,
Set<Subscription> subscriptions) throws InterruptedException,
RemotingException, org.apache.rocketmq.remoting.exception.RemotingException {
+
+ String clientId = ChannelInfo.getClientId(ctx.channel());
+ Session session =
sessionLoop.getSession(ChannelInfo.getId(ctx.channel()));
+ Set<Subscription> preciseTopics = new HashSet<>();
+ Set<Subscription> wildcardTopics = new HashSet<>();
+
+ for (Subscription subscription : subscriptions) {
+ if (!TopicUtils.isWildCard(subscription.getTopicFilter())) {
+ preciseTopics.add(subscription);
+ } else {
+ wildcardTopics.add(subscription);
+ }
+ }
+
+ for (Subscription subscription : preciseTopics) {
+ CompletableFuture<Message> retainedMessage =
retainedPersistManager.getRetainedMessage(subscription.getTopicFilter());
+ retainedMessage.whenComplete((msg, throwable) -> {
+ if (msg == null) {
+ return;
+ }
+ _sendMessage(session, clientId, subscription, msg);
+ });
+ }
+
+ for (Subscription subscription : wildcardTopics) {
+
+ CompletableFuture<ArrayList<String>> future =
retainedPersistManager.getMsgsFromTrie(subscription);
+ future.whenComplete((msgsList,throwable) -> {
+ ArrayList<Message> results = new ArrayList<>();
+ for (String strMsg:msgsList) {
+ results.add(JSON.parseObject(strMsg,Message.class));
Review Comment:
format code
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]