MQTTSuite
Loading...
Searching...
No Matches
SSEDistributor.cpp
Go to the documentation of this file.
1/*
2 * MQTTSuite - A lightweight MQTT Integration System
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2022, 2023, 2024, 2025, 2026
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the Free
8 * Software Foundation, either version 3 of the License, or (at your option)
9 * any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 * more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20/*
21 * MIT License
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#include "SSEDistributor.h"
43
44#include <express/Response.h>
45#include <web/http/server/SocketContext.h>
46
47// IWYU pragma: no_include <nlohmann/detail/json_ref.hpp>
48
49struct tm;
50
51#ifndef DOXYGEN_SHOULD_SKIP_THIS
52
53#include <ctime>
54#include <functional>
55#include <iomanip>
56#include <log/Logger.h>
57#include <nlohmann/json.hpp>
58#include <sstream>
59
60#endif // DOXYGEN_SHOULD_SKIP_THIS
61
62namespace mqtt::bridge::lib {
63
65 : onlineSinceTimePoint(std::chrono::system_clock::now()) {
66 }
67
69 static SSEDistributor sseDistributor;
70
71 return sseDistributor;
72 }
73
74 void SSEDistributor::addEventReceiver(const std::shared_ptr<express::Response>& response,
75 [[maybe_unused]] const std::string& lastEventId) {
76 const std::uint64_t eventReceiverId = nextEventReceiverId++;
77
78 eventReceiverList.emplace_back(eventReceiverId, response);
79
80 response->getSocketContext()->onDisconnected([this, eventReceiverId]() {
81 eventReceiverList.remove_if([eventReceiverId](const EventReceiver& eventReceiver) {
82 return eventReceiver.getId() == eventReceiverId;
83 });
84 });
85
86 for (const auto& event : replayEvents) {
87 sendEvent(response, event.getData(), event.getEvent(), event.getId());
88 }
89 }
90
91 void SSEDistributor::sendEvent(const std::shared_ptr<express::Response>& response,
92 const std::string& data,
93 const std::string& event,
94 const std::string& id) {
95 if (response->isConnected()) {
96 if (!event.empty()) {
97 response->sendFragment("event:" + event);
98 }
99 if (!id.empty()) {
100 response->sendFragment("id:" + id);
101 }
102 response->sendFragment("data:" + data);
103 response->sendFragment();
104 }
105 }
106
107 void SSEDistributor::sendJsonEvent1(const std::shared_ptr<express::Response>& response,
108 const nlohmann::json& json,
109 const std::string& event,
110 const std::string& id) {
111 sendEvent(response, json.dump(), event, id);
112 }
113
114 void SSEDistributor::sendEvent(const std::string& data, const std::string& event, const std::string& id) {
115 VLOG(0) << "Server sent event: " << event << "\n" << data;
116
117 for (const auto& eventReceiver : eventReceiverList) {
118 if (const auto& response = eventReceiver.getResponse()) {
119 sendEvent(response, data, event, id);
120 }
121 }
122
123 replayEvents.emplace_back(data, event, id);
124 }
125
126 void SSEDistributor::sendJsonEvent(const nlohmann::json& json, const std::string& event, const std::string& id) {
127 sendEvent(json.dump(), event, id);
128 }
129
131 replayEvents.clear();
132
133 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}}, "bridges_starting", std::to_string(id++));
134 }
135
137 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}}, "bridges_started", std::to_string(id++));
138 }
139
141 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}}, "bridges_stopping", std::to_string(id++));
142 }
143
145 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}}, "bridges_stopped", std::to_string(id++));
146 }
147
148 void SSEDistributor::bridgeDisabled(const std::string& bridgeName) {
150 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_disabled", std::to_string(id++));
151 }
152
153 void SSEDistributor::bridgeStarting(const std::string& bridgeName) {
155 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_starting", std::to_string(id++));
156 }
157
158 void SSEDistributor::bridgeStarted(const std::string& bridgeName) {
160 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_started", std::to_string(id++));
161 }
162
163 void SSEDistributor::bridgeStopping(const std::string& bridgeName) {
165 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_stopping", std::to_string(id++));
166 }
167
168 void SSEDistributor::bridgeStopped(const std::string& bridgeName) {
170 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_stopped", std::to_string(id++));
171 }
172
173 void SSEDistributor::brokerDisabled(const std::string& bridgeName, const std::string& instanceName) {
174 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
175 "broker_disabled",
176 std::to_string(id++));
177 }
178
179 void SSEDistributor::brokerConnecting(const std::string& bridgeName, const std::string& instanceName) {
180 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
181 "broker_connecting",
182 std::to_string(id++));
183 }
184
185 void SSEDistributor::brokerConnected(const std::string& bridgeName, const std::string& instanceName) {
186 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
187 "broker_connected",
188 std::to_string(id++));
189 }
190
191 void SSEDistributor::brokerDisconnecting(const std::string& bridgeName, const std::string& instanceName) {
192 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
193 "broker_disconnecting",
194 std::to_string(id++));
195 }
196
197 void SSEDistributor::brokerDisconnected(const std::string& bridgeName, const std::string& instanceName) {
198 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
199 "broker_disconnected",
200 std::to_string(id++));
201 }
202
206
207 std::string SSEDistributor::timePointToString(const std::chrono::time_point<std::chrono::system_clock>& timePoint) {
208 std::time_t time = std::chrono::system_clock::to_time_t(timePoint);
209 const std::tm* tm_ptr = std::gmtime(&time);
210
211 char buffer[100];
212 std::string onlineSince = "Formatting error";
213
214 // Format: "2025-02-02 14:30:00"
215 if (std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_ptr)) {
216 onlineSince = std::string(buffer) + " UTC";
217 }
218
219 return onlineSince;
220 }
221
222 std::string SSEDistributor::durationToString(const std::chrono::time_point<std::chrono::system_clock>& bevore,
223 const std::chrono::time_point<std::chrono::system_clock>& later) {
224 using seconds_duration_type = std::chrono::duration<std::chrono::seconds::rep>::rep;
225
226 seconds_duration_type totalSeconds = std::chrono::duration_cast<std::chrono::seconds>(later - bevore).count();
227
228 // Compute days, hours, minutes, and seconds
229 seconds_duration_type days = totalSeconds / 86400; // 86400 seconds in a day
230 seconds_duration_type remainder = totalSeconds % 86400;
231 seconds_duration_type hours = remainder / 3600;
232 remainder = remainder % 3600;
233 seconds_duration_type minutes = remainder / 60;
234 seconds_duration_type seconds = remainder % 60;
235
236 // Format the components into a string using stringstream
237 std::ostringstream oss;
238 if (days > 0) {
239 oss << days << " day" << (days == 1 ? "" : "s") << ", ";
240 }
241 oss << std::setw(2) << std::setfill('0') << hours << ":" << std::setw(2) << std::setfill('0') << minutes << ":" << std::setw(2)
242 << std::setfill('0') << seconds;
243
244 return oss.str();
245 }
246
247 SSEDistributor::EventReceiver::EventReceiver(std::uint64_t id, const std::shared_ptr<express::Response>& response)
248 : id(id)
249 , response(response)
250 , heartbeatTimer(core::timer::Timer::intervalTimer(
251 [response] {
252 response->sendFragment(":keep-alive");
253 response->sendFragment();
254 },
255 39)) {
256 }
257
261
262 std::shared_ptr<express::Response> SSEDistributor::EventReceiver::getResponse() const {
263 return response.lock();
264 }
265
266 SSEDistributor::Event::Event(const std::string& data, const std::string& event, const std::string& id)
267 : data(data)
268 , event(event)
269 , id(id) {
270 }
271
272 const std::string& SSEDistributor::Event::getData() const {
273 return data;
274 }
275
276 const std::string& SSEDistributor::Event::getEvent() const {
277 return event;
278 }
279
280 const std::string& SSEDistributor::Event::getId() const {
281 return id;
282 }
283
284} // namespace mqtt::bridge::lib
std::weak_ptr< express::Response > response
std::shared_ptr< express::Response > getResponse() const
EventReceiver(std::uint64_t id, const std::shared_ptr< express::Response > &response)
Event(const std::string &data, const std::string &event, const std::string &id)
static void sendJsonEvent1(const std::shared_ptr< express::Response > &response, const nlohmann::json &json, const std::string &event="", const std::string &id="")
void sendEvent(const std::string &data, const std::string &event="", const std::string &id="")
static std::string durationToString(const std::chrono::time_point< std::chrono::system_clock > &bevore, const std::chrono::time_point< std::chrono::system_clock > &later=std::chrono::system_clock::now())
void bridgeStopped(const std::string &bridgeName)
void addEventReceiver(const std::shared_ptr< express::Response > &response, const std::string &lastEventId)
void brokerConnected(const std::string &bridgeName, const std::string &instanceName)
std::chrono::time_point< std::chrono::system_clock > bridgesStartTimePoint
void brokerConnecting(const std::string &bridgeName, const std::string &instanceName)
void brokerDisabled(const std::string &bridgeName, const std::string &instanceName)
void bridgeDisabled(const std::string &bridgeName)
static void sendEvent(const std::shared_ptr< express::Response > &response, const std::string &data, const std::string &event, const std::string &id)
void bridgeStarting(const std::string &bridgeName)
void bridgeStarted(const std::string &bridgeName)
static SSEDistributor & instance()
std::list< EventReceiver > eventReceiverList
std::chrono::time_point< std::chrono::system_clock > onlineSinceTimePoint
void brokerDisconnected(const std::string &bridgeName, const std::string &instanceName)
void brokerDisconnecting(const std::string &bridgeName, const std::string &instanceName)
static std::string timePointToString(const std::chrono::time_point< std::chrono::system_clock > &timePoint)
void sendJsonEvent(const nlohmann::json &json, const std::string &event="", const std::string &id="")
void bridgeStopping(const std::string &bridgeName)