2018-08-26 19:15:48 +08:00
|
|
|
//
|
|
|
|
// Copyright (c) 2018
|
|
|
|
// Mainflux
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
//
|
|
|
|
|
2018-05-21 22:28:52 +08:00
|
|
|
package writers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/gogo/protobuf/proto"
|
|
|
|
"github.com/mainflux/mainflux"
|
|
|
|
log "github.com/mainflux/mainflux/logger"
|
|
|
|
nats "github.com/nats-io/go-nats"
|
|
|
|
)
|
|
|
|
|
|
|
|
type consumer struct {
|
2019-05-10 20:36:27 +08:00
|
|
|
nc *nats.Conn
|
2019-05-16 19:19:06 +08:00
|
|
|
channels map[string]bool
|
2019-05-10 20:36:27 +08:00
|
|
|
repo MessageRepository
|
|
|
|
logger log.Logger
|
2018-05-21 22:28:52 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start method starts to consume normalized messages received from NATS.
|
2019-05-16 19:19:06 +08:00
|
|
|
func Start(nc *nats.Conn, repo MessageRepository, queue string, channels map[string]bool, logger log.Logger) error {
|
2018-06-08 20:25:55 +08:00
|
|
|
c := consumer{
|
2019-05-10 20:36:27 +08:00
|
|
|
nc: nc,
|
|
|
|
channels: channels,
|
|
|
|
repo: repo,
|
|
|
|
logger: logger,
|
2018-05-21 22:28:52 +08:00
|
|
|
}
|
|
|
|
|
2018-09-13 16:06:34 +08:00
|
|
|
_, err := nc.QueueSubscribe(mainflux.OutputSenML, queue, c.consume)
|
2018-05-21 22:28:52 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *consumer) consume(m *nats.Msg) {
|
|
|
|
msg := &mainflux.Message{}
|
|
|
|
if err := proto.Unmarshal(m.Data, msg); err != nil {
|
2018-06-08 20:25:55 +08:00
|
|
|
c.logger.Warn(fmt.Sprintf("Failed to unmarshal received message: %s", err))
|
2018-05-21 22:28:52 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-05-10 20:36:27 +08:00
|
|
|
if !c.channelExists(msg.GetChannel()) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-05-21 22:28:52 +08:00
|
|
|
if err := c.repo.Save(*msg); err != nil {
|
2018-06-08 20:25:55 +08:00
|
|
|
c.logger.Warn(fmt.Sprintf("Failed to save message: %s", err))
|
2018-05-21 22:28:52 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2019-05-10 20:36:27 +08:00
|
|
|
|
|
|
|
func (c *consumer) channelExists(channel string) bool {
|
2019-05-16 19:19:06 +08:00
|
|
|
if _, ok := c.channels["*"]; ok {
|
2019-05-10 20:36:27 +08:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-05-16 19:19:06 +08:00
|
|
|
_, found := c.channels[channel]
|
2019-05-10 20:36:27 +08:00
|
|
|
return found
|
|
|
|
}
|