2020-05-07 15:34:09 +08:00
|
|
|
// Copyright (c) Mainflux
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package mqtt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
log "github.com/mainflux/mainflux/logger"
|
2020-06-03 21:16:19 +08:00
|
|
|
"github.com/mainflux/mainflux/pkg/messaging"
|
2020-05-07 15:34:09 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
channels = "channels"
|
|
|
|
messages = "messages"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Forwarder specifies MQTT forwarder interface API.
|
|
|
|
type Forwarder interface {
|
|
|
|
// Forward subscribes to the Subscriber and
|
|
|
|
// publishes messages using provided Publisher.
|
2022-05-04 00:02:19 +08:00
|
|
|
Forward(id string, sub messaging.Subscriber, pub messaging.Publisher) error
|
2020-05-07 15:34:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type forwarder struct {
|
|
|
|
topic string
|
|
|
|
logger log.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewForwarder returns new Forwarder implementation.
|
|
|
|
func NewForwarder(topic string, logger log.Logger) Forwarder {
|
|
|
|
return forwarder{
|
|
|
|
topic: topic,
|
|
|
|
logger: logger,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-04 00:02:19 +08:00
|
|
|
func (f forwarder) Forward(id string, sub messaging.Subscriber, pub messaging.Publisher) error {
|
|
|
|
return sub.Subscribe(id, f.topic, handle(pub, f.logger))
|
2020-05-07 15:34:09 +08:00
|
|
|
}
|
|
|
|
|
2022-05-04 00:02:19 +08:00
|
|
|
func handle(pub messaging.Publisher, logger log.Logger) handleFunc {
|
2020-05-07 15:34:09 +08:00
|
|
|
return func(msg messaging.Message) error {
|
|
|
|
if msg.Protocol == protocol {
|
|
|
|
return nil
|
|
|
|
}
|
2022-05-04 00:02:19 +08:00
|
|
|
// Use concatenation instead of fmt.Sprintf for the
|
2020-05-07 15:34:09 +08:00
|
|
|
// sake of simplicity and performance.
|
|
|
|
topic := channels + "/" + msg.Channel + "/" + messages
|
|
|
|
if msg.Subtopic != "" {
|
|
|
|
topic += "/" + strings.ReplaceAll(msg.Subtopic, ".", "/")
|
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
if err := pub.Publish(topic, msg); err != nil {
|
2022-05-04 00:02:19 +08:00
|
|
|
logger.Warn(fmt.Sprintf("Failed to forward message: %s", err))
|
2020-05-07 15:34:09 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2022-05-04 00:02:19 +08:00
|
|
|
|
|
|
|
type handleFunc func(msg messaging.Message) error
|
|
|
|
|
|
|
|
func (h handleFunc) Handle(msg messaging.Message) error {
|
|
|
|
return h(msg)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h handleFunc) Cancel() error {
|
|
|
|
return nil
|
|
|
|
}
|