summaryrefslogtreecommitdiff
path: root/src/KingSystem/Utils/Thread/MessageProcessor.cpp
blob: 296d24a896c3859ad9878899123402ad45f22210 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "KingSystem/Utils/Thread/MessageProcessor.h"
#include <tuple>
#include "KingSystem/Utils/Thread/Message.h"
#include "KingSystem/Utils/Thread/MessageAck.h"
#include "KingSystem/Utils/Thread/MessageReceiver.h"

namespace ksys {

MessageProcessor::MessageProcessor(Logger* logger) : mLogger(logger) {}

MessageProcessor::~MessageProcessor() = default;

static bool checkTransceiver(const MesTransceiverId& id) {
    if (!id.next)
        return false;

    MesTransceiverId* next = *id.next;
    if (!next)
        return false;

    const auto& fields = [](const MesTransceiverId& i) { return std::tie(i.queue_id, i.id); };
    return fields(id) == fields(*next);
}

bool MessageProcessor::process(Message* message) {
    message->decrementDelay();

    if (!message->shouldBeProcessed())
        return false;

    bool success = false;
    bool dest_valid = false;

    const auto& dest = message->getDestination();
    if (checkTransceiver(dest)) {
        success = dest.receiver->receive(*message) & 1;
        mLogger->log(*message, success);
        dest_valid = true;
    }

    const auto& src = message->getSource();
    if (!message->hasDelayer() || checkTransceiver(src)) {
        if (message->shouldAck()) {
            const auto& source = message->getSource();
            if (checkTransceiver(source)) {
                auto* receiver = source.receiver;
                const MessageAck ack{dest_valid, success, message->getDestination(),
                                     message->getType(), message->getUserData()};
                receiver->receive(ack);
            }
        }
    } else {
        mLogger->log(*message, false);
    }

    return true;
}

}  // namespace ksys