Ring Daemon 16.0.0
Loading...
Searching...
No Matches
message_engine.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2004-2025 Savoir-faire Linux Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18#include "message_engine.h"
19#include "sip/sipaccountbase.h"
20#include "manager.h"
21#include "fileutils.h"
22
23#include "client/ring_signal.h"
24#include "jami/account_const.h"
25
26#include <opendht/thread_pool.h>
27#include <fmt/std.h>
28
29#include <fstream>
30
31namespace jami {
32namespace im {
33
34MessageEngine::MessageEngine(SIPAccountBase& acc, const std::filesystem::path& path)
35 : account_(acc)
36 , savePath_(path)
37 , ioContext_(Manager::instance().ioContext())
38 , saveTimer_(*ioContext_)
39{
40 dhtnet::fileutils::check_dir(savePath_.parent_path());
41}
42
44MessageEngine::sendMessage(const std::string& to,
45 const std::string& deviceId,
46 const std::map<std::string, std::string>& payloads,
48{
49 if (payloads.empty() or to.empty())
50 return 0;
51 MessageToken token = 0;
52 {
53 std::lock_guard lock(messagesMutex_);
54 auto& peerMessages = deviceId.empty() ? messages_[to] : messagesDevices_[deviceId];
55 if (refreshToken != 0) {
56 for (auto& m : peerMessages) {
57 if (m.token == refreshToken) {
58 token = refreshToken;
59 m.to = to;
60 m.payloads = payloads;
61 m.status = MessageStatus::IDLE;
62 break;
63 }
64 }
65 }
66 if (token == 0) {
67 token = std::uniform_int_distribution<MessageToken> {1, JAMI_ID_MAX_VAL}(account_.rand);
68 auto& m = peerMessages.emplace_back(Message {token});
69 m.to = to;
70 m.payloads = payloads;
71 }
72 scheduleSave();
73 }
74 ioContext_->post([this, to, deviceId]() { retrySend(to, deviceId, true); });
75 return token;
76}
77
78void
79MessageEngine::onPeerOnline(const std::string& peer,
80 const std::string& deviceId,
81 bool retryOnTimeout)
82{
83 retrySend(peer, deviceId, retryOnTimeout);
84}
85
86void
87MessageEngine::retrySend(const std::string& peer, const std::string& deviceId, bool retryOnTimeout)
88{
89 struct PendingMsg {
90 MessageToken token;
91 std::string to;
92 std::map<std::string, std::string> payloads;
93 };
94 std::vector<PendingMsg> pending {};
95 auto now = clock::now();
96 {
97 std::lock_guard lock(messagesMutex_);
98 auto& m = deviceId.empty() ? messages_ : messagesDevices_;
99 auto p = m.find(deviceId.empty() ? peer : deviceId);
100 if (p == m.end())
101 return;
102 auto& messages = p->second;
103
104 for (auto& m: messages) {
105 if (m.status == MessageStatus::IDLE) {
106 m.status = MessageStatus::SENDING;
107 m.retried++;
108 m.last_op = now;
109 pending.emplace_back(PendingMsg {m.token, m.to, m.payloads});
110 }
111 }
112 }
113 // avoid locking while calling callback
114 for (const auto& p : pending) {
115 JAMI_DEBUG("[Account {:s}] [message {:d}] Reattempt sending", account_.getAccountID(), p.token);
116 if (p.payloads.find("application/im-gitmessage-id") == p.payloads.end())
118 account_.getAccountID(),
119 "",
120 p.to,
121 std::to_string(p.token),
123 account_.sendMessage(p.to, deviceId, p.payloads, p.token, retryOnTimeout, false);
124 }
125}
126
129{
130 std::lock_guard lock(messagesMutex_);
131 for (const auto& p : messages_) {
132 for (const auto& m : p.second) {
133 if (m.token == t)
134 return m.status;
135 }
136 }
138}
139
140void
141MessageEngine::onMessageSent(const std::string& peer,
142 MessageToken token,
143 bool ok,
144 const std::string& deviceId)
145{
146 JAMI_DEBUG("[Account {:s}] [message {:d}] Message sent: {:s}", account_.getAccountID(), token, ok ? "success"sv : "failure"sv);
147 std::lock_guard lock(messagesMutex_);
148 auto& m = deviceId.empty() ? messages_ : messagesDevices_;
149
150 auto p = m.find(deviceId.empty() ? peer : deviceId);
151 if (p == m.end()) {
152 JAMI_WARNING("[Account {:s}] onMessageSent: Peer not found: id:{} device:{}", account_.getAccountID(), peer, deviceId);
153 return;
154 }
155
156 auto f = std::find_if(p->second.begin(), p->second.end(), [&](const Message& m) {
157 return m.token == token;
158 });
159 if (f != p->second.end()) {
160 auto emit = f->payloads.find("application/im-gitmessage-id")
161 == f->payloads.end();
162 if (f->status == MessageStatus::SENDING) {
163 if (ok) {
164 f->status = MessageStatus::SENT;
165 JAMI_LOG("[Account {:s}] [message {:d}] Status changed to SENT", account_.getAccountID(), token);
166 if (emit)
168 account_.getAccountID(),
169 "",
170 f->to,
171 std::to_string(token),
172 static_cast<int>(libjami::Account::MessageStates::SENT));
173 p->second.erase(f);
174 scheduleSave();
175 } else if (f->retried >= MAX_RETRIES) {
176 f->status = MessageStatus::FAILURE;
177 JAMI_WARNING("[Account {:s}] [message {:d}] Status changed to FAILURE", account_.getAccountID(), token);
178 if (emit)
180 account_.getAccountID(),
181 "",
182 f->to,
183 std::to_string(token),
185 p->second.erase(f);
186 scheduleSave();
187 } else {
188 f->status = MessageStatus::IDLE;
189 JAMI_DEBUG("[Account {:s}] [message {:d}] Status changed to IDLE", account_.getAccountID(), token);
190 }
191 } else {
192 JAMI_DEBUG("[Account {:s}] [message {:d}] State is not SENDING", account_.getAccountID(), token);
193 }
194 } else {
195 JAMI_DEBUG("[Account {:s}] [message {:d}] Unable to find message", account_.getAccountID(), token);
196 }
197}
198
199void
201{
202 try {
203 decltype(messages_) root;
204 {
205 std::lock_guard lock(dhtnet::fileutils::getFileLock(savePath_));
206 std::ifstream file;
207 file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
208 file.open(savePath_);
209 if (file.is_open()) {
210 msgpack::unpacker up;
211 up.reserve_buffer(UINT16_MAX);
212 while (file.read(up.buffer(), UINT16_MAX)) {
213 up.buffer_consumed(file.gcount());
214 msgpack::object_handle oh;
215 if (up.next(oh)) {
216 root = oh.get().as<std::map<std::string, std::list<Message>>>();
217 break;
218 }
219 up.reserve_buffer(UINT16_MAX);
220 }
221 }
222 }
223 std::lock_guard lock(messagesMutex_);
224 messages_ = std::move(root);
225 if (not messages_.empty()) {
226 JAMI_LOG("[Account {}] Loaded {} messages from {}",
227 account_.getAccountID(),
228 messages_.size(),
229 savePath_);
230 }
231 } catch (const std::exception& e) {
232 JAMI_LOG("[Account {}] Unable to load messages from {}: {}",
233 account_.getAccountID(),
234 savePath_,
235 e.what());
236 }
237}
238
239void
241{
242 std::lock_guard lock(messagesMutex_);
243 save_();
244}
245
246void
247MessageEngine::scheduleSave()
248{
249 saveTimer_.expires_after(std::chrono::seconds(5));
250 saveTimer_.async_wait([this, w = account_.weak_from_this()](const std::error_code& ec) {
251 if (!ec)
252 if (auto acc = w.lock())
253 save();
254 });
255}
256
257void
258MessageEngine::save_() const
259{
260 try {
261 std::ofstream file;
262 file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
263 file.open(savePath_, std::ios::trunc);
264 if (file.is_open())
265 msgpack::pack(file, messages_);
266 } catch (const std::exception& e) {
267 JAMI_ERROR("[Account {}] Unable to serialize pending messages: {}",
268 account_.getAccountID(), e.what());
269 }
270}
271
272} // namespace im
273} // namespace jami
const std::string & getAccountID() const
Get the account ID.
Definition account.h:154
std::mt19937_64 rand
Random generator engine Logical account state shall never rely on the state of the random generator.
Definition account.h:349
Manager (controller) of daemon.
Definition manager.h:67
virtual void sendMessage(const std::string &to, const std::string &deviceId, const std::map< std::string, std::string > &payloads, uint64_t id, bool retryOnTimeout=true, bool onlyConnected=false)=0
void load()
Load persisted messages.
MessageToken sendMessage(const std::string &to, const std::string &deviceId, const std::map< std::string, std::string > &payloads, uint64_t refreshToken)
Add a message to the engine and try to send it.
void onPeerOnline(const std::string &peer, const std::string &deviceId={}, bool retryOnTimeout=true)
@TODO change MessageEngine by a queue, @NOTE retryOnTimeout is used for failing SIP messages (jamiAcc...
void onMessageSent(const std::string &peer, MessageToken t, bool success, const std::string &deviceId={})
void save() const
Persist messages.
MessageStatus getStatus(MessageToken t) const
MessageEngine(SIPAccountBase &, const std::filesystem::path &path)
#define JAMI_ERROR(formatstr,...)
Definition logger.h:228
#define JAMI_DEBUG(formatstr,...)
Definition logger.h:226
#define JAMI_WARNING(formatstr,...)
Definition logger.h:227
#define JAMI_LOG(formatstr,...)
Definition logger.h:225
uint64_t MessageToken
void emitSignal(Args... args)
Definition ring_signal.h:64
static constexpr uint64_t JAMI_ID_MAX_VAL
Definition account.h:62