Ring Daemon
Loading...
Searching...
No Matches
message_engine.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2004-2026 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
22#include "client/jami_signal.h"
23#include "jami/account_const.h"
24
25#include <dhtnet/fileutils.h>
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 asio::post(*ioContext_, [this, to, deviceId]() { retrySend(to, deviceId, true); });
75 return token;
76}
77
78void
79MessageEngine::onPeerOnline(const std::string& peer, const std::string& deviceId, bool retryOnTimeout)
80{
81 retrySend(peer, deviceId, retryOnTimeout);
82}
83
84void
85MessageEngine::retrySend(const std::string& peer, const std::string& deviceId, bool retryOnTimeout)
86{
87 struct PendingMsg
88 {
89 MessageToken token;
90 std::string to;
91 std::map<std::string, std::string> payloads;
92 };
93 std::vector<PendingMsg> pending {};
94 auto now = clock::now();
95 {
96 std::lock_guard lock(messagesMutex_);
97 auto& m = deviceId.empty() ? messages_ : messagesDevices_;
98 auto p = m.find(deviceId.empty() ? peer : deviceId);
99 if (p == m.end())
100 return;
101 auto& messages = p->second;
102
103 for (auto& m : messages) {
104 if (m.status == MessageStatus::IDLE) {
105 m.status = MessageStatus::SENDING;
106 m.retried++;
107 m.last_op = now;
108 pending.emplace_back(PendingMsg {m.token, m.to, m.payloads});
109 }
110 }
111 }
112 // avoid locking while calling callback
113 for (const auto& p : pending) {
114 JAMI_DEBUG("[Account {:s}] [message {:d}] Reattempt sending", account_.getAccountID(), p.token);
115 if (p.payloads.find("application/im-gitmessage-id") == p.payloads.end())
117 account_.getAccountID(),
118 "",
119 p.to,
120 std::to_string(p.token),
122 account_.sendMessage(p.to, deviceId, p.payloads, p.token, retryOnTimeout, false);
123 }
124}
125
128{
129 std::lock_guard lock(messagesMutex_);
130 for (const auto& p : messages_) {
131 for (const auto& m : p.second) {
132 if (m.token == t)
133 return m.status;
134 }
135 }
137}
138
139void
140MessageEngine::onMessageSent(const std::string& peer, MessageToken token, bool ok, const std::string& deviceId)
141{
142 JAMI_DEBUG("[Account {:s}] [message {:d}] Message sent: {:s}",
143 account_.getAccountID(),
144 token,
145 ok ? "success"sv : "failure"sv);
146 std::lock_guard lock(messagesMutex_);
147 auto& m = deviceId.empty() ? messages_ : messagesDevices_;
148
149 auto p = m.find(deviceId.empty() ? peer : deviceId);
150 if (p == m.end()) {
151 JAMI_WARNING("[Account {:s}] onMessageSent: Peer not found: id:{} device:{}",
152 account_.getAccountID(),
153 peer,
154 deviceId);
155 return;
156 }
157
158 auto f = std::find_if(p->second.begin(), p->second.end(), [&](const Message& m) { return m.token == token; });
159 if (f != p->second.end()) {
160 auto emit = f->payloads.find("application/im-gitmessage-id") == f->payloads.end();
161 if (f->status == MessageStatus::SENDING) {
162 if (ok) {
163 f->status = MessageStatus::SENT;
164 JAMI_LOG("[Account {:s}] [message {:d}] Status changed to SENT", account_.getAccountID(), token);
165 if (emit)
167 account_.getAccountID(),
168 "",
169 f->to,
170 std::to_string(token),
171 static_cast<int>(libjami::Account::MessageStates::SENT));
172 p->second.erase(f);
173 scheduleSave();
174 } else if (f->retried >= MAX_RETRIES) {
175 f->status = MessageStatus::FAILURE;
176 JAMI_WARNING("[Account {:s}] [message {:d}] Status changed to FAILURE", account_.getAccountID(), token);
177 if (emit)
179 account_.getAccountID(),
180 "",
181 f->to,
182 std::to_string(token),
184 p->second.erase(f);
185 scheduleSave();
186 } else {
187 f->status = MessageStatus::IDLE;
188 JAMI_DEBUG("[Account {:s}] [message {:d}] Status changed to IDLE", account_.getAccountID(), token);
189 }
190 } else {
191 JAMI_DEBUG("[Account {:s}] [message {:d}] State is not SENDING", account_.getAccountID(), token);
192 }
193 } else {
194 JAMI_DEBUG("[Account {:s}] [message {:d}] Unable to find message", account_.getAccountID(), token);
195 }
196}
197
198void
200{
201 try {
202 decltype(messages_) root;
203 {
204 std::lock_guard lock(dhtnet::fileutils::getFileLock(savePath_));
205 std::ifstream file;
206 file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
207 file.open(savePath_);
208 if (file.is_open()) {
209 msgpack::unpacker up;
210 up.reserve_buffer(UINT16_MAX);
211 while (file.read(up.buffer(), UINT16_MAX)) {
212 up.buffer_consumed(file.gcount());
213 msgpack::object_handle oh;
214 if (up.next(oh)) {
215 root = oh.get().as<std::map<std::string, std::list<Message>>>();
216 break;
217 }
218 up.reserve_buffer(UINT16_MAX);
219 }
220 }
221 }
222 std::lock_guard lock(messagesMutex_);
223 messages_ = std::move(root);
224 if (not messages_.empty()) {
225 JAMI_LOG("[Account {}] Loaded {} messages from {}", account_.getAccountID(), messages_.size(), savePath_);
226 }
227 } catch (const std::exception& e) {
228 JAMI_LOG("[Account {}] Unable to load messages from {}: {}", account_.getAccountID(), savePath_, e.what());
229 }
230}
231
232void
234{
235 std::lock_guard lock(messagesMutex_);
236 save_();
237}
238
239void
240MessageEngine::scheduleSave()
241{
242 saveTimer_.expires_after(std::chrono::seconds(5));
243 saveTimer_.async_wait([this, w = account_.weak_from_this()](const std::error_code& ec) {
244 if (!ec)
245 if (auto acc = w.lock())
246 save();
247 });
248}
249
250void
251MessageEngine::save_() const
252{
253 try {
254 std::ofstream file;
255 file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
256 file.open(savePath_, std::ios::trunc);
257 if (file.is_open())
258 msgpack::pack(file, messages_);
259 } catch (const std::exception& e) {
260 JAMI_ERROR("[Account {}] Unable to serialize pending messages: {}", account_.getAccountID(), e.what());
261 }
262}
263
264} // namespace im
265} // namespace jami
const std::string & getAccountID() const
Get the account ID.
Definition account.h:149
std::mt19937_64 rand
Random generator engine Logical account state shall never rely on the state of the random generator.
Definition account.h:334
Manager (controller) of daemon.
Definition manager.h:66
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:243
#define JAMI_DEBUG(formatstr,...)
Definition logger.h:238
#define JAMI_WARNING(formatstr,...)
Definition logger.h:242
#define JAMI_LOG(formatstr,...)
Definition logger.h:237
uint64_t MessageToken
void emitSignal(Args... args)
Definition jami_signal.h:64
static constexpr uint64_t JAMI_ID_MAX_VAL
Definition account.h:57