Loading...
Searching...
No Matches
consumer.cpp
Go to the documentation of this file.
1/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/*
3 * Copyright (c) 2014-2023, The University of Memphis
4 *
5 * This file is part of PSync.
6 * See AUTHORS.md for complete list of PSync authors and contributors.
7 *
8 * PSync is free software: you can redistribute it and/or modify it under the terms
9 * of the GNU Lesser General Public License as published by the Free Software Foundation,
10 * either version 3 of the License, or (at your option) any later version.
11 *
12 * PSync is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
13 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License along with
17 * PSync, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include "PSync/consumer.hpp"
22
23#include <ndn-cxx/security/validator-null.hpp>
24#include <ndn-cxx/util/logger.hpp>
25
26namespace psync {
27
28NDN_LOG_INIT(psync.Consumer);
29
30Consumer::Consumer(ndn::Face& face, const ndn::Name& syncPrefix, const Options& opts)
31 : m_face(face)
32 , m_scheduler(m_face.getIoContext())
33 , m_syncPrefix(syncPrefix)
34 , m_helloInterestPrefix(ndn::Name(m_syncPrefix).append("hello"))
35 , m_syncInterestPrefix(ndn::Name(m_syncPrefix).append("sync"))
36 , m_syncDataContentType(ndn::tlv::ContentType_Blob)
37 , m_onReceiveHelloData(opts.onHelloData)
38 , m_onUpdate(opts.onUpdate)
39 , m_bloomFilter(opts.bfCount, opts.bfFalsePositive)
40 , m_helloInterestLifetime(opts.helloInterestLifetime)
41 , m_syncInterestLifetime(opts.syncInterestLifetime)
42 , m_rng(ndn::random::getRandomNumberEngine())
43 , m_rangeUniformRandom(100, 500)
44{
45}
46
47Consumer::Consumer(const ndn::Name& syncPrefix,
48 ndn::Face& face,
49 const ReceiveHelloCallback& onReceiveHelloData,
50 const UpdateCallback& onUpdate,
51 unsigned int count,
52 double falsePositive,
53 ndn::time::milliseconds helloInterestLifetime,
54 ndn::time::milliseconds syncInterestLifetime)
55 : Consumer(face, syncPrefix,
56 Options{onReceiveHelloData, onUpdate, static_cast<uint32_t>(count), falsePositive,
57 helloInterestLifetime, syncInterestLifetime})
58{
59}
60
61bool
62Consumer::addSubscription(const ndn::Name& prefix, uint64_t seqNo, bool callSyncDataCb)
63{
64 auto it = m_prefixes.emplace(prefix, seqNo);
65 if (!it.second) {
66 return false;
67 }
68
69 NDN_LOG_DEBUG("Subscribing prefix: " << prefix);
70
71 m_subscriptionList.emplace(prefix);
72 m_bloomFilter.insert(prefix);
73
74 if (callSyncDataCb && seqNo != 0) {
75 m_onUpdate({{prefix, seqNo, seqNo, 0}});
76 }
77
78 return true;
79}
80
81bool
82Consumer::removeSubscription(const ndn::Name& prefix)
83{
84 if (!isSubscribed(prefix))
85 return false;
86
87 NDN_LOG_DEBUG("Unsubscribing prefix: " << prefix);
88
89 m_prefixes.erase(prefix);
90 m_subscriptionList.erase(prefix);
91
92 // Clear and reconstruct the bloom filter
93 m_bloomFilter.clear();
94
95 for (const auto& item : m_subscriptionList)
96 m_bloomFilter.insert(item);
97
98 return true;
99}
100
101void
103{
104 NDN_LOG_DEBUG("Canceling all the scheduled events");
105 m_scheduler.cancelAllEvents();
106
107 if (m_syncFetcher) {
108 m_syncFetcher->stop();
109 m_syncFetcher.reset();
110 }
111
112 if (m_helloFetcher) {
113 m_helloFetcher->stop();
114 m_helloFetcher.reset();
115 }
116}
117
118void
120{
121 ndn::Interest helloInterest(m_helloInterestPrefix);
122 NDN_LOG_DEBUG("Send Hello Interest " << helloInterest);
123
124 if (m_helloFetcher) {
125 m_helloFetcher->stop();
126 }
127
128 using ndn::SegmentFetcher;
129 SegmentFetcher::Options options;
130 options.interestLifetime = m_helloInterestLifetime;
131 options.maxTimeout = m_helloInterestLifetime;
132 options.rttOptions.initialRto = m_syncInterestLifetime;
133
134 m_helloFetcher = SegmentFetcher::start(m_face, helloInterest,
135 ndn::security::getAcceptAllValidator(), options);
136
137 m_helloFetcher->afterSegmentValidated.connect([this] (const ndn::Data& data) {
138 if (data.getFinalBlock()) {
139 m_helloDataName = data.getName().getPrefix(-2);
140 }
141 });
142
143 m_helloFetcher->onComplete.connect([this] (const ndn::ConstBufferPtr& bufferPtr) {
144 onHelloData(bufferPtr);
145 });
146
147 m_helloFetcher->onError.connect([this] (uint32_t errorCode, const std::string& msg) {
148 NDN_LOG_TRACE("Cannot fetch hello data, error: " << errorCode << " message: " << msg);
149 ndn::time::milliseconds after(m_rangeUniformRandom(m_rng));
150 NDN_LOG_TRACE("Scheduling after " << after);
151 m_scheduler.schedule(after, [this] { sendHelloInterest(); });
152 });
153}
154
155void
156Consumer::onHelloData(const ndn::ConstBufferPtr& bufferPtr)
157{
158 NDN_LOG_DEBUG("On Hello Data");
159
160 // Extract IBF from name which is the last element in hello data's name
161 m_iblt = m_helloDataName.getSubName(m_helloDataName.size() - 1, 1);
162
163 NDN_LOG_TRACE("m_iblt: " << std::hash<ndn::Name>{}(m_iblt));
164
165 detail::State state{ndn::Block(bufferPtr)};
166 std::vector<MissingDataInfo> updates;
167 std::map<ndn::Name, uint64_t> availableSubscriptions;
168
169 NDN_LOG_DEBUG("Hello Data: " << state);
170
171 for (const auto& content : state) {
172 const ndn::Name& prefix = content.getPrefix(-1);
173 uint64_t seq = content.get(content.size() - 1).toNumber();
174 // If consumer is subscribed then prefix must already be present in
175 // m_prefixes (see addSubscription). So [] operator is safe to use.
176 if (isSubscribed(prefix) && seq > m_prefixes[prefix]) {
177 // In case we are behind on this prefix and consumer is subscribed to it
178 updates.push_back({prefix, m_prefixes[prefix] + 1, seq, 0});
179 m_prefixes[prefix] = seq;
180 }
181 availableSubscriptions.emplace(prefix, seq);
182 }
183
184 m_onReceiveHelloData(availableSubscriptions);
185
186 if (!updates.empty()) {
187 NDN_LOG_DEBUG("Updating application with missed updates");
188 m_onUpdate(updates);
189 }
190}
191
192void
194{
195 BOOST_ASSERT(!m_iblt.empty());
196
197 ndn::Name syncInterestName(m_syncInterestPrefix);
198
199 // Append subscription list
200 m_bloomFilter.appendToName(syncInterestName);
201
202 // Append IBF received in hello/sync data
203 syncInterestName.append(m_iblt);
204
205 ndn::Interest syncInterest(syncInterestName);
206
207 NDN_LOG_DEBUG("sendSyncInterest, nonce: " << syncInterest.getNonce() <<
208 " hash: " << std::hash<ndn::Name>{}(syncInterest.getName()));
209
210 if (m_syncFetcher) {
211 m_syncFetcher->stop();
212 }
213
214 using ndn::SegmentFetcher;
215 SegmentFetcher::Options options;
216 options.interestLifetime = m_syncInterestLifetime;
217 options.maxTimeout = m_syncInterestLifetime;
218 options.rttOptions.initialRto = m_syncInterestLifetime;
219
220 m_syncFetcher = SegmentFetcher::start(m_face, syncInterest,
221 ndn::security::getAcceptAllValidator(), options);
222
223 m_syncFetcher->afterSegmentValidated.connect([this] (const ndn::Data& data) {
224 if (data.getFinalBlock()) {
225 m_syncDataName = data.getName().getPrefix(-2);
226 m_syncDataContentType = data.getContentType();
227 }
228
229 if (m_syncDataContentType == ndn::tlv::ContentType_Nack) {
230 NDN_LOG_DEBUG("Received application Nack from producer, sending hello again");
232 }
233 });
234
235 m_syncFetcher->onComplete.connect([this] (const ndn::ConstBufferPtr& bufferPtr) {
236 if (m_syncDataContentType == ndn::tlv::ContentType_Nack) {
237 m_syncDataContentType = ndn::tlv::ContentType_Blob;
238 return;
239 }
240 NDN_LOG_TRACE("Segment fetcher got sync data");
241 onSyncData(bufferPtr);
242 });
243
244 m_syncFetcher->onError.connect([this] (uint32_t errorCode, const std::string& msg) {
245 NDN_LOG_TRACE("Cannot fetch sync data, error: " << errorCode << " message: " << msg);
246 if (errorCode == SegmentFetcher::ErrorCode::INTEREST_TIMEOUT) {
248 }
249 else {
250 ndn::time::milliseconds after(m_rangeUniformRandom(m_rng));
251 NDN_LOG_TRACE("Scheduling sync Interest after: " << after);
252 m_scheduler.schedule(after, [this] { sendSyncInterest(); });
253 }
254 });
255}
256
257void
258Consumer::onSyncData(const ndn::ConstBufferPtr& bufferPtr)
259{
260 // Extract IBF from sync data name which is the last component
261 m_iblt = m_syncDataName.getSubName(m_syncDataName.size() - 1, 1);
262
263 detail::State state{ndn::Block(bufferPtr)};
264 std::vector<MissingDataInfo> updates;
265
266 for (const auto& content : state) {
267 NDN_LOG_DEBUG(content);
268 const ndn::Name& prefix = content.getPrefix(-1);
269 uint64_t seq = content.get(content.size() - 1).toNumber();
270 if (m_prefixes.find(prefix) == m_prefixes.end() || seq > m_prefixes[prefix]) {
271 // If this is just the next seq number then we had already informed the consumer about
272 // the previous sequence number and hence seq low and seq high should be equal to current seq
273 updates.push_back({prefix, m_prefixes[prefix] + 1, seq, 0});
274 m_prefixes[prefix] = seq;
275 }
276 // Else updates will be empty and consumer will not be notified.
277 }
278
279 NDN_LOG_DEBUG("Sync Data: " << state);
280
281 if (!updates.empty()) {
282 m_onUpdate(updates);
283 }
284
286}
287
288} // namespace psync
Consumer logic to subscribe to producer's data.
Definition consumer.hpp:56
bool addSubscription(const ndn::Name &prefix, uint64_t seqNo, bool callSyncDataCb=true)
Add prefix to subscription list.
Definition consumer.cpp:62
bool removeSubscription(const ndn::Name &prefix)
Remove prefix from subscription list.
Definition consumer.cpp:82
void stop()
Stop segment fetcher to stop the sync and free resources.
Definition consumer.cpp:102
void sendHelloInterest()
send hello interest /<sync-prefix>/hello/
Definition consumer.cpp:119
Consumer(ndn::Face &face, const ndn::Name &syncPrefix, const Options &opts)
Constructor.
Definition consumer.cpp:30
void sendSyncInterest()
send sync interest /<sync-prefix>/sync/<BF>/<producers-IBF>
Definition consumer.cpp:193
bool isSubscribed(const ndn::Name &prefix) const
Definition consumer.hpp:143
void insert(const ndn::Name &key)
void appendToName(ndn::Name &name) const
Append our bloom filter to the given name.
std::function< void(const std::vector< MissingDataInfo > &)> UpdateCallback
Definition common.hpp:71
std::function< void(const std::map< ndn::Name, uint64_t > &)> ReceiveHelloCallback
Definition consumer.hpp:36
Constructor options.
Definition consumer.hpp:62