summaryrefslogtreecommitdiff
path: root/src/debug/log/RollingLogFollow.hpp
blob: c1cce9eb6600d42dfa4e978e1f6cdfba83115f90 (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
60
61
62
63
64
65
66
67
68
69
70
#pragma once

#include <shared_mutex>
#include <unordered_map>
#include <format>
#include <vector>

namespace Log {
    struct SRollingLogFollow {
        std::unordered_map<int, std::string> m_socketToRollingLogFollowQueue;
        std::shared_mutex                    m_mutex;
        bool                                 m_running                  = false;
        static constexpr size_t              ROLLING_LOG_FOLLOW_TOO_BIG = 8192;

        // Returns true if the queue is empty for the given socket
        bool isEmpty(int socket) {
            std::shared_lock<std::shared_mutex> r(m_mutex);
            return m_socketToRollingLogFollowQueue[socket].empty();
        }

        std::string debugInfo() {
            std::shared_lock<std::shared_mutex> r(m_mutex);
            return std::format("RollingLogFollow, got {} connections", m_socketToRollingLogFollowQueue.size());
        }

        std::string getLog(int socket) {
            std::unique_lock<std::shared_mutex> w(m_mutex);

            const std::string                   ret = m_socketToRollingLogFollowQueue[socket];
            m_socketToRollingLogFollowQueue[socket] = "";

            return ret;
        };

        void addLog(const std::string_view& log) {
            std::unique_lock<std::shared_mutex> w(m_mutex);
            m_running = true;
            std::vector<int> to_erase;
            for (const auto& p : m_socketToRollingLogFollowQueue) {
                m_socketToRollingLogFollowQueue[p.first] += log;
                m_socketToRollingLogFollowQueue[p.first] += "\n";
            }
        }

        bool isRunning() {
            std::shared_lock<std::shared_mutex> r(m_mutex);
            return m_running;
        }

        void stopFor(int socket) {
            std::unique_lock<std::shared_mutex> w(m_mutex);
            m_socketToRollingLogFollowQueue.erase(socket);
            if (m_socketToRollingLogFollowQueue.empty())
                m_running = false;
        }

        void startFor(int socket) {
            std::unique_lock<std::shared_mutex> w(m_mutex);
            m_socketToRollingLogFollowQueue[socket] = std::format("[LOG] Following log to socket: {} started\n", socket);
            m_running                               = true;
        }

        static SRollingLogFollow& get() {
            static SRollingLogFollow    instance;
            static std::mutex           gm;
            std::lock_guard<std::mutex> lock(gm);
            return instance;
        };
    };
}