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 auto& eventReceiver = eventReceiverList.emplace_back(response);
77
78 response->getSocketContext()->onDisconnected([this, &eventReceiver]() {
79 eventReceiverList.remove(eventReceiver);
80 });
81
82 for (const auto& event : replayEvents) {
83 sendEvent(response, event.getData(), event.getEvent(), event.getId());
84 }
85 }
86
87 void SSEDistributor::sendEvent(const std::shared_ptr<express::Response>& response,
88 const std::string& data,
89 const std::string& event,
90 const std::string& id) {
91 if (response->isConnected()) {
92 if (!event.empty()) {
93 response->sendFragment("event:" + event);
94 }
95 if (!id.empty()) {
96 response->sendFragment("id:" + id);
97 }
98 response->sendFragment("data:" + data);
99 response->sendFragment();
100 }
101 }
102
103 void SSEDistributor::sendJsonEvent(const std::shared_ptr<express::Response>& response,
104 const nlohmann::json& json,
105 const std::string& event,
106 const std::string& id) {
107 sendEvent(response, json.dump(), event, id);
108 }
109
110 void SSEDistributor::sendEvent(const std::string& data, const std::string& event, const std::string& id) {
111 VLOG(0) << "Server sent event: " << event << "\n" << data;
112
113 for (const auto& eventReceiver : eventReceiverList) {
114 if (const auto& response = eventReceiver.getResponse()) {
115 sendEvent(response, data, event, id);
116 }
117 }
118
119 replayEvents.emplace_back(data, event, id);
120 }
121
122 void SSEDistributor::sendJsonEvent(const nlohmann::json& json, const std::string& event, const std::string& id) {
123 sendEvent(json.dump(), event, id);
124 }
125
127 replayEvents.clear();
128
129 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}}, "bridges_starting", std::to_string(id++));
130 }
131
133 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}}, "bridges_started", std::to_string(id++));
134 }
135
137 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}}, "bridges_stopping", std::to_string(id++));
138 }
139
141 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}}, "bridges_stopped", std::to_string(id++));
142 }
143
144 void SSEDistributor::bridgeDisabled(const std::string& bridgeName) {
146 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_disabled", std::to_string(id++));
147 }
148
149 void SSEDistributor::bridgeStarting(const std::string& bridgeName) {
151 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_starting", std::to_string(id++));
152 }
153
154 void SSEDistributor::bridgeStarted(const std::string& bridgeName) {
156 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_started", std::to_string(id++));
157 }
158
159 void SSEDistributor::bridgeStopping(const std::string& bridgeName) {
161 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_stopping", std::to_string(id++));
162 }
163
164 void SSEDistributor::bridgeStopped(const std::string& bridgeName) {
166 {{"at", timePointToString(std::chrono::system_clock::now())}, {"name", bridgeName}}, "bridge_stopped", std::to_string(id++));
167 }
168
169 void SSEDistributor::brokerDisabled(const std::string& bridgeName, const std::string& instanceName) {
170 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
171 "broker_disabled",
172 std::to_string(id++));
173 }
174
175 void SSEDistributor::brokerConnecting(const std::string& bridgeName, const std::string& instanceName) {
176 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
177 "broker_connecting",
178 std::to_string(id++));
179 }
180
181 void SSEDistributor::brokerConnected(const std::string& bridgeName, const std::string& instanceName) {
182 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
183 "broker_connected",
184 std::to_string(id++));
185 }
186
187 void SSEDistributor::brokerDisconnecting(const std::string& bridgeName, const std::string& instanceName) {
188 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
189 "broker_disconnecting",
190 std::to_string(id++));
191 }
192
193 void SSEDistributor::brokerDisconnected(const std::string& bridgeName, const std::string& instanceName) {
194 sendJsonEvent({{"at", timePointToString(std::chrono::system_clock::now())}, {"bridge", bridgeName}, {"instance", instanceName}},
195 "broker_disconnected",
196 std::to_string(id++));
197 }
198
202
203 std::string SSEDistributor::timePointToString(const std::chrono::time_point<std::chrono::system_clock>& timePoint) {
204 std::time_t time = std::chrono::system_clock::to_time_t(timePoint);
205 const std::tm* tm_ptr = std::gmtime(&time);
206
207 char buffer[100];
208 std::string onlineSince = "Formatting error";
209
210 // Format: "2025-02-02 14:30:00"
211 if (std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_ptr)) {
212 onlineSince = std::string(buffer) + " UTC";
213 }
214
215 return onlineSince;
216 }
217
218 std::string SSEDistributor::durationToString(const std::chrono::time_point<std::chrono::system_clock>& bevore,
219 const std::chrono::time_point<std::chrono::system_clock>& later) {
220 using seconds_duration_type = std::chrono::duration<std::chrono::seconds::rep>::rep;
221
222 seconds_duration_type totalSeconds = std::chrono::duration_cast<std::chrono::seconds>(later - bevore).count();
223
224 // Compute days, hours, minutes, and seconds
225 seconds_duration_type days = totalSeconds / 86400; // 86400 seconds in a day
226 seconds_duration_type remainder = totalSeconds % 86400;
227 seconds_duration_type hours = remainder / 3600;
228 remainder = remainder % 3600;
229 seconds_duration_type minutes = remainder / 60;
230 seconds_duration_type seconds = remainder % 60;
231
232 // Format the components into a string using stringstream
233 std::ostringstream oss;
234 if (days > 0) {
235 oss << days << " day" << (days == 1 ? "" : "s") << ", ";
236 }
237 oss << std::setw(2) << std::setfill('0') << hours << ":" << std::setw(2) << std::setfill('0') << minutes << ":" << std::setw(2)
238 << std::setfill('0') << seconds;
239
240 return oss.str();
241 }
242
243 SSEDistributor::EventReceiver::EventReceiver(const std::shared_ptr<express::Response>& response)
244 : response(response)
245 , heartbeatTimer(core::timer::Timer::intervalTimer(
246 [response] {
247 response->sendFragment(":keep-alive");
248 response->sendFragment();
249 },
250 39)) {
251 }
252
256
257 std::shared_ptr<express::Response> SSEDistributor::EventReceiver::getResponse() const {
258 return response.lock();
259 }
260
262 return response.lock() == other.response.lock();
263 }
264
265 SSEDistributor::Event::Event(const std::string& data, const std::string& event, const std::string& id)
266 : data(data)
267 , event(event)
268 , id(id) {
269 }
270
271 const std::string& SSEDistributor::Event::getData() const {
272 return data;
273 }
274
275 const std::string& SSEDistributor::Event::getEvent() const {
276 return event;
277 }
278
279 const std::string& SSEDistributor::Event::getId() const {
280 return id;
281 }
282
283} // namespace mqtt::bridge::lib
std::weak_ptr< express::Response > response
std::shared_ptr< express::Response > getResponse() const
EventReceiver(const std::shared_ptr< express::Response > &response)
Event(const std::string &data, 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)
static void sendJsonEvent(const std::shared_ptr< express::Response > &response, const nlohmann::json &json, const std::string &event="", const std::string &id="")
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)