Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -274,13 +274,16 @@ public MeterRegistry getRegistry() {
serverConfiguration.setAuthenticationCacheSize(0);
serverConfiguration.setAuthorizationCacheSize(0);

// Load custom handlers
// Load custom handlers, discarding any that have been replaced by another handler
this.customHandlers =
stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false)
.sorted(Comparator.comparingInt(MQTTHandler::getPriority))
.collect(Collectors.toList());
selectHandlers(stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false).toList());

// Init each custom handler
initHandlers(container, serverConfiguration);
}

/** Initializes the selected handlers in priority order. */
protected void initHandlers(Container container, Configuration serverConfiguration)
throws Exception {
for (MQTTHandler handler : customHandlers) {
try {
handler.init(container, serverConfiguration);
Expand Down Expand Up @@ -361,7 +364,11 @@ public void start(Container container) throws Exception {
serverLocator = ActiveMQClient.createServerLocator("vm://0").setProducerWindowSize(-1);
sessionFactory = serverLocator.createSessionFactory();

// Start each custom handler
startHandlers(container);
}

/** Starts the selected handlers in priority order. */
protected void startHandlers(Container container) throws Exception {
for (MQTTHandler handler : customHandlers) {
try {
handler.start(container);
Expand Down Expand Up @@ -455,8 +462,16 @@ public void stop(Container container) throws Exception {
server.stop();
LOG.log(DEBUG, "Stopped MQTT broker");

stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false)
.sorted(Comparator.comparingInt(MQTTHandler::getPriority).reversed())
stopHandlers();
}

/**
* Stops the selected handlers in reverse priority order; an exception from one handler is logged
* and does not prevent the others from stopping.
*/
protected void stopHandlers() {
customHandlers
.reversed()
.forEach(
handler -> {
try {
Expand Down Expand Up @@ -588,6 +603,96 @@ public void onUnsubscribe(RemotingConnection connection, String topicStr) {
}
}

/**
* Selects the handlers to run from those loaded, sorted by priority. A handler is discarded when
* another loaded handler declares its class in {@link MQTTHandler#getReplacedHandlers}; extending
* a handler does not replace it. A handler declaring its own class is ignored.
*
* @throws IllegalStateException if the replacement declarations form a cycle, as no handler in
* the cycle could otherwise run
*/
protected static List<MQTTHandler> selectHandlers(List<MQTTHandler> loadedHandlers) {
Map<Class<? extends MQTTHandler>, List<Class<? extends MQTTHandler>>> replacements =
new LinkedHashMap<>();
for (MQTTHandler handler : loadedHandlers) {
replacements.putIfAbsent(handler.getClass(), new ArrayList<>());
}
for (MQTTHandler handler : loadedHandlers) {
for (Class<? extends MQTTHandler> replaced : handler.getReplacedHandlers()) {
if (replaced != handler.getClass() && replacements.containsKey(replaced)) {
replacements.get(handler.getClass()).add(replaced);
}
}
}

throwIfReplacementCycle(replacements);

Map<Class<? extends MQTTHandler>, MQTTHandler> replacedBy = new HashMap<>();
for (MQTTHandler handler : loadedHandlers) {
for (Class<? extends MQTTHandler> replaced : replacements.get(handler.getClass())) {
replacedBy.putIfAbsent(replaced, handler);
}
}

return loadedHandlers.stream()
.filter(
handler -> {
MQTTHandler replacement = replacedBy.get(handler.getClass());
if (replacement != null) {
LOG.log(
INFO,
"MQTT handler '"
+ handler.getName()
+ "' replaced by '"
+ replacement.getName()
+ "'");
}
return replacement == null;
})
.sorted(Comparator.comparingInt(MQTTHandler::getPriority))
.collect(Collectors.toList());
}

protected static void throwIfReplacementCycle(
Map<Class<? extends MQTTHandler>, List<Class<? extends MQTTHandler>>> replacements) {
Set<Class<? extends MQTTHandler>> visited = new HashSet<>();
for (Class<? extends MQTTHandler> start : replacements.keySet()) {
findReplacementCycle(start, replacements, visited, new ArrayList<>())
.ifPresent(
cycle -> {
throw new IllegalStateException(
"MQTT handlers declare a replacement cycle, so none of them could run: "
+ cycle.stream().map(Class::getName).collect(Collectors.joining(" -> ")));
});
}
}

private static Optional<List<Class<? extends MQTTHandler>>> findReplacementCycle(
Class<? extends MQTTHandler> current,
Map<Class<? extends MQTTHandler>, List<Class<? extends MQTTHandler>>> replacements,
Set<Class<? extends MQTTHandler>> visited,
List<Class<? extends MQTTHandler>> path) {
int index = path.indexOf(current);
if (index >= 0) {
List<Class<? extends MQTTHandler>> cycle = new ArrayList<>(path.subList(index, path.size()));
cycle.add(current);
return Optional.of(cycle);
}
if (!visited.add(current)) {
return Optional.empty();
}
path.add(current);
for (Class<? extends MQTTHandler> replaced : replacements.get(current)) {
Optional<List<Class<? extends MQTTHandler>>> cycle =
findReplacementCycle(replaced, replacements, visited, path);
if (cycle.isPresent()) {
return cycle;
}
}
path.remove(path.size() - 1);
return Optional.empty();
}

public Iterable<MQTTHandler> getCustomHandlers() {
return customHandlers;
}
Expand Down
12 changes: 12 additions & 0 deletions manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ public int getPriority() {
return 0;
}

/**
* Gets the handlers that this handler replaces, allowing a custom project to take over a topic of
* a built-in handler. Replaced handlers are discarded when the handlers are loaded, so they are
* never initialized or started and never consume any messages. Replacement must be declared here:
* extending a handler does not replace it, so a subclass serving another topic can run alongside
* its parent. Handlers that replace each other, directly or through others, stop the broker from
* initializing.
*/
public Set<Class<? extends MQTTHandler>> getReplacedHandlers() {
return Set.of();
}

/** Provides a name to identify this custom handler for logging purposes etc. */
public String getName() {
return this.getClass().getSimpleName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public void configure() throws Exception {

protected static final Logger LOG =
SyslogCategory.getLogger(API, UserAssetProvisioningMQTTHandler.class);
public static final String PROVISIONING_TOKEN = "provisioningv2";
public static final String PROVISIONING_TOKEN = "provisioning";
public static final String REQUEST_TOKEN = "request";
public static final String RESPONSE_TOKEN = "response";
public static final String UNIQUE_ID_PLACEHOLDER = "%UNIQUE_ID%";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
/*
* Copyright 2026, OpenRemote Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package org.openremote.manager.mqtt

import io.netty.buffer.ByteBuf
import org.apache.activemq.artemis.core.config.Configuration
import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection
import org.openremote.container.security.AuthContext
import org.openremote.model.Container
import org.openremote.model.protocol.mqtt.Topic
import org.openremote.model.util.Debouncer
import spock.lang.Specification

import java.util.logging.Logger

class MQTTHandlerReplacementTest extends Specification {

def "only the selected handlers are initialized and started, and the same instances stop once in reverse order"() {
given: "a built-in handler, a replacement for it and an unrelated peer"
def events = []
def builtIn = new BuiltInHandler(events: events)
def replacement = new ReplacementHandler(events: events)
def peer = new PeerHandler(events: events)
def broker = new MQTTBrokerService()
def container = Stub(Container)
def configuration = Stub(Configuration)
broker.server = Stub(EmbeddedActiveMQ)
broker.userAssetDisconnectDebouncer = Stub(Debouncer)

when: "the handlers are selected and taken through their lifecycle, stopping through the broker as the container does"
broker.customHandlers = MQTTBrokerService.selectHandlers([builtIn, peer, replacement])
broker.initHandlers(container, configuration)
broker.startHandlers(container)
broker.stop(container)

then: "the replaced handler is discarded and the others run in priority order"
broker.customHandlers == [replacement, peer]

and: "only the selected instances receive lifecycle callbacks, stopping once in reverse order"
events == [
[replacement, "init"],
[peer, "init"],
[replacement, "start"],
[peer, "start"],
[peer, "stop"],
[replacement, "stop"]
]
}

def "a handler that extends another without declaring it runs alongside its parent"() {
given:
def parent = new BuiltInHandler(events: [])
def subclass = new BuiltInSubclassHandler(events: [])

expect:
MQTTBrokerService.selectHandlers([parent, subclass]) as Set == [parent, subclass] as Set
}

def "a handler declaring its own class is not discarded"() {
given:
def handler = new SelfReplacingHandler(events: [])

expect:
MQTTBrokerService.selectHandlers([handler]) == [handler]
}

def "a replacement cycle is rejected naming the participating handlers"() {
when:
MQTTBrokerService.selectHandlers([new CycleAHandler(events: []), new CycleBHandler(events: []), new PeerHandler(events: [])])

then:
IllegalStateException ex = thrown()
ex.message.contains(CycleAHandler.name)
ex.message.contains(CycleBHandler.name)
!ex.message.contains(PeerHandler.name)
}

def "a declared replacement that is not loaded is ignored"() {
given:
def replacement = new ReplacementHandler(events: [])

expect:
MQTTBrokerService.selectHandlers([replacement]) == [replacement]
}

static abstract class RecordingHandler extends MQTTHandler {
List events

@Override
void init(Container container, Configuration serverConfiguration) {
events << [this, "init"]
}

@Override
void start(Container container) {
events << [this, "start"]
}

@Override
void stop() {
events << [this, "stop"]
}

@Override
protected boolean topicMatches(Topic topic) {
false
}

@Override
protected Logger getLogger() {
Logger.getLogger(getClass().name)
}

@Override
boolean canSubscribe(RemotingConnection connection, AuthContext authContext, Topic topic) {
false
}

@Override
boolean canPublish(RemotingConnection connection, AuthContext authContext, Topic topic) {
false
}

@Override
void onSubscribe(RemotingConnection connection, Topic topic) {}

@Override
void onUnsubscribe(RemotingConnection connection, Topic topic) {}

@Override
Set<String> getPublishListenerTopics() {
[] as Set
}

@Override
void onPublish(RemotingConnection connection, Topic topic, ByteBuf body) {}
}

static class BuiltInHandler extends RecordingHandler {}

static class BuiltInSubclassHandler extends BuiltInHandler {}

static class ReplacementHandler extends RecordingHandler {
@Override
Set<Class<? extends MQTTHandler>> getReplacedHandlers() {
[BuiltInHandler] as Set
}
}

static class PeerHandler extends RecordingHandler {
@Override
int getPriority() {
10
}
}

static class SelfReplacingHandler extends RecordingHandler {
@Override
Set<Class<? extends MQTTHandler>> getReplacedHandlers() {
[SelfReplacingHandler] as Set
}
}

static class CycleAHandler extends RecordingHandler {
@Override
Set<Class<? extends MQTTHandler>> getReplacedHandlers() {
[CycleBHandler] as Set
}
}

static class CycleBHandler extends RecordingHandler {
@Override
Set<Class<? extends MQTTHandler>> getReplacedHandlers() {
[CycleAHandler] as Set
}
}
}
Loading
Loading