catchunks: add metadata-based version discovery

refs: #4556
Change-Id: I1100d1a4f14da8e66d190a7909185d67f7aa92a7
diff --git a/tests/chunks/discover-version-realtime.t.cpp b/tests/chunks/discover-version-realtime.t.cpp
new file mode 100644
index 0000000..630594b
--- /dev/null
+++ b/tests/chunks/discover-version-realtime.t.cpp
@@ -0,0 +1,158 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2016-2019, Regents of the University of California,
+ *                          Colorado State University,
+ *                          University Pierre & Marie Curie, Sorbonne University.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ *
+ * @author Chavoosh Ghasemi
+ */
+
+#include "tools/chunks/catchunks/discover-version-realtime.hpp"
+
+#include "discover-version-fixture.hpp"
+#include "tests/identity-management-fixture.hpp"
+
+#include <ndn-cxx/metadata-object.hpp>
+
+
+namespace ndn {
+namespace chunks {
+namespace tests {
+
+class DiscoverVersionRealtimeFixture : public DiscoverVersionFixture,
+                                       public IdentityManagementFixture,
+                                       protected DiscoverVersionRealtimeOptions
+{
+public:
+  typedef DiscoverVersionRealtimeOptions Options;
+
+public:
+  explicit
+  DiscoverVersionRealtimeFixture(const Options& opt = makeOptionsRealtime())
+    : chunks::Options(opt)
+    , DiscoverVersionFixture(opt)
+    , Options(opt)
+  {
+    setDiscover(make_unique<DiscoverVersionRealtime>(Name(name), face, opt));
+  }
+
+protected:
+  static Options
+  makeOptionsRealtime()
+  {
+    Options options;
+    options.isVerbose = false;
+    options.maxRetriesOnTimeoutOrNack = 3;
+    return options;
+  }
+};
+
+BOOST_AUTO_TEST_SUITE(Chunks)
+BOOST_FIXTURE_TEST_SUITE(TestDiscoverVersionRealtime, DiscoverVersionRealtimeFixture)
+
+BOOST_AUTO_TEST_CASE(Success)
+{
+  // issue a discovery Interest to learn Data version
+  discover->run();
+  advanceClocks(io, time::nanoseconds(1), 1);
+
+  BOOST_REQUIRE_EQUAL(face.sentInterests.size(), 1);
+
+  Interest discoveryInterest = MetadataObject::makeDiscoveryInterest(name);
+  auto lastInterest = face.sentInterests.back();
+  BOOST_CHECK_EQUAL(lastInterest.getName(), discoveryInterest.getName());
+
+  // Send back a metadata packet with a valid versioned name
+  uint64_t version = 1449241767037;
+
+  MetadataObject mobject;
+  mobject.setVersionedName(Name(name).appendVersion(version));
+  face.receive(mobject.makeData(lastInterest.getName(), m_keyChain));
+  advanceClocks(io, time::nanoseconds(1), 1);
+
+  BOOST_CHECK(isDiscoveryFinished);
+  BOOST_CHECK_EQUAL(discoveredVersion, version);
+}
+
+BOOST_AUTO_TEST_CASE(InvalidVersionedName)
+{
+  // issue a discovery Interest to learn Data version
+  discover->run();
+  advanceClocks(io, time::nanoseconds(1), 1);
+
+  BOOST_REQUIRE_EQUAL(face.sentInterests.size(), 1);
+
+  // Send back a metadata packet with an invalid versioned name
+  MetadataObject mobject;
+  mobject.setVersionedName(name);
+  face.receive(mobject.makeData(face.sentInterests.back().getName(), m_keyChain));
+
+  // finish discovery process without a resolved version number
+  BOOST_CHECK(isDiscoveryFinished);
+  BOOST_CHECK_EQUAL(discoveredVersion, 0);
+}
+
+BOOST_AUTO_TEST_CASE(InvalidMetadataPacket)
+{
+  // issue a discovery Interest to learn Data version
+  discover->run();
+  advanceClocks(io, time::nanoseconds(1), 1);
+
+  BOOST_REQUIRE_EQUAL(face.sentInterests.size(), 1);
+
+  // Send back an invalid metadata packet
+  Data data(face.sentInterests.back().getName());
+  data.setContentType(tlv::ContentType_Key);
+  face.receive(signData(data));
+
+  // finish discovery process without a resolved version number
+  BOOST_CHECK(isDiscoveryFinished);
+  BOOST_CHECK_EQUAL(discoveredVersion, 0);
+}
+
+BOOST_AUTO_TEST_CASE(Timeout)
+{
+  // issue a discovery Interest to learn Data version
+  discover->run();
+  advanceClocks(io, time::nanoseconds(1), 1);
+
+  BOOST_REQUIRE_EQUAL(face.sentInterests.size(), 1);
+
+  // timeout discovery Interests
+  for (int retries = 0; retries < maxRetriesOnTimeoutOrNack; ++retries) {
+    advanceClocks(io, interestLifetime, 1);
+
+    BOOST_CHECK_EQUAL(isDiscoveryFinished, false);
+    BOOST_REQUIRE_EQUAL(face.sentInterests.size(), retries + 2);
+  }
+
+  // timeout the last sent Interest
+  advanceClocks(io, interestLifetime, 1);
+
+  // finish discovery process without a resolved version number
+  BOOST_CHECK(isDiscoveryFinished);
+  BOOST_CHECK_EQUAL(discoveredVersion, 0);
+}
+
+BOOST_AUTO_TEST_SUITE_END() // TestDiscoverVersionRealtime
+BOOST_AUTO_TEST_SUITE_END() // Chunks
+
+} // namespace tests
+} // namespace chunks
+} // namespace ndn
diff --git a/tools/chunks/catchunks/discover-version-realtime.cpp b/tools/chunks/catchunks/discover-version-realtime.cpp
new file mode 100644
index 0000000..7175211
--- /dev/null
+++ b/tools/chunks/catchunks/discover-version-realtime.cpp
@@ -0,0 +1,79 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2016-2019, Regents of the University of California,
+ *                          Colorado State University,
+ *                          University Pierre & Marie Curie, Sorbonne University.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ *
+ * @author Chavoosh Ghasemi <chghasemi@cs.arizona.edu>
+ */
+
+#include "discover-version-realtime.hpp"
+
+#include <ndn-cxx/metadata-object.hpp>
+
+namespace ndn {
+namespace chunks {
+
+DiscoverVersionRealtime::DiscoverVersionRealtime(const Name& prefix,
+                                                 Face& face,
+                                                 const Options& options)
+  : chunks::Options(options)
+  , DiscoverVersion(prefix, face)
+  , Options(options)
+{
+}
+
+void
+DiscoverVersionRealtime::run()
+{
+  expressInterest(MetadataObject::makeDiscoveryInterest(m_prefix)
+                  .setInterestLifetime(discoveryTimeout),
+                  maxRetriesOnTimeoutOrNack, maxRetriesOnTimeoutOrNack);
+}
+
+void
+DiscoverVersionRealtime::handleData(const Interest& interest, const Data& data)
+{
+  if (isVerbose)
+    std::cerr << "Data: " << data << std::endl;
+
+  // make a metadata object from received metadata packet
+  MetadataObject mobject;
+  try {
+    mobject = MetadataObject(data);
+  }
+  catch (const tlv::Error& e) {
+    this->emitSignal(onDiscoveryFailure, "Invalid metadata packet: "s + e.what());
+    return;
+  }
+
+  if (mobject.getVersionedName().empty() || !mobject.getVersionedName()[-1].isVersion()) {
+    this->emitSignal(onDiscoveryFailure, mobject.getVersionedName().toUri() +
+                                         " is not a valid versioned name");
+    return;
+  }
+
+  if (isVerbose) {
+    std::cerr << "Discovered Data version: " << mobject.getVersionedName()[-1].toVersion() << std::endl;
+  }
+  this->emitSignal(onDiscoverySuccess, mobject.getVersionedName());
+}
+
+} // namespace chunks
+} // namespace ndn
diff --git a/tools/chunks/catchunks/discover-version-realtime.hpp b/tools/chunks/catchunks/discover-version-realtime.hpp
new file mode 100644
index 0000000..2e3f975
--- /dev/null
+++ b/tools/chunks/catchunks/discover-version-realtime.hpp
@@ -0,0 +1,85 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2016-2019, Regents of the University of California,
+ *                          Colorado State University,
+ *                          University Pierre & Marie Curie, Sorbonne University.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-tools is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE.  See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ *
+ * @author Chavoosh Ghasemi <chghasemi@cs.arizona.edu>
+ */
+
+#ifndef NDN_TOOLS_CHUNKS_CATCHUNKS_DISCOVER_VERSION_REALTIME_HPP
+#define NDN_TOOLS_CHUNKS_CATCHUNKS_DISCOVER_VERSION_REALTIME_HPP
+
+#include "discover-version.hpp"
+
+namespace ndn {
+namespace chunks {
+
+/**
+ * @brief Options for discover version realtime
+ *
+ * The canonical name to use is DiscoverVersionRealtime::Options
+ */
+class DiscoverVersionRealtimeOptions : public virtual Options
+{
+public:
+  explicit
+  DiscoverVersionRealtimeOptions(const Options& opts = Options())
+    : Options(opts)
+  {
+  }
+
+public:
+  time::milliseconds discoveryTimeout{DEFAULT_INTEREST_LIFETIME}; ///< timeout for version discovery
+};
+
+/**
+ * @brief Service for discovering Data version by sending discovery interests
+ *
+ * This service employs RDR-style metadata class for version discovery.
+ * @see https://redmine.named-data.net/projects/ndn-tlv/wiki/RDR
+ */
+class DiscoverVersionRealtime : public DiscoverVersion, protected DiscoverVersionRealtimeOptions
+{
+public:
+  typedef DiscoverVersionRealtimeOptions Options;
+
+public:
+  /**
+   * @param prefix Name of solicited data
+   * @param face The face through which discovery Interests are expressed
+   * @param options Additional information about the service
+   */
+  DiscoverVersionRealtime(const Name& prefix, Face& face, const Options& options);
+
+  /**
+   * @brief Send a discovery Interest out
+   */
+  void
+  run() final;
+
+private:
+  void
+  handleData(const Interest& interest, const Data& data) final;
+};
+
+} // namespace chunks
+} // namespace ndn
+
+#endif // NDN_TOOLS_CHUNKS_CATCHUNKS_DISCOVER_VERSION_REALTIME_HPP
diff --git a/tools/chunks/catchunks/ndncatchunks.cpp b/tools/chunks/catchunks/ndncatchunks.cpp
index 497197f..2224f48 100644
--- a/tools/chunks/catchunks/ndncatchunks.cpp
+++ b/tools/chunks/catchunks/ndncatchunks.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2016-2018, Regents of the University of California,
+ * Copyright (c) 2016-2019, Regents of the University of California,
  *                          Colorado State University,
  *                          University Pierre & Marie Curie, Sorbonne University.
  *
@@ -34,6 +34,7 @@
 #include "consumer.hpp"
 #include "discover-version-fixed.hpp"
 #include "discover-version-iterative.hpp"
+#include "discover-version-realtime.hpp"
 #include "pipeline-interests-aimd.hpp"
 #include "pipeline-interests-fixed-window.hpp"
 #include "options.hpp"
@@ -70,7 +71,7 @@
   basicDesc.add_options()
     ("help,h",      "print this help message and exit")
     ("discover-version,d", po::value<std::string>(&discoverType)->default_value(discoverType),
-                            "version discovery algorithm to use; valid values are: 'fixed', 'iterative'")
+                            "version discovery algorithm to use; valid values are: 'fixed', 'iterative', 'realtime'")
     ("pipeline-type,p", po::value<std::string>(&pipelineType)->default_value(pipelineType),
                          "type of Interest pipeline to use; valid values are: 'fixed', 'aimd'")
     ("fresh,f",     po::bool_switch(&options.mustBeFresh), "only return fresh content")
@@ -229,6 +230,10 @@
       optionsIterative.discoveryTimeout = time::milliseconds(discoveryTimeoutMs);
       discover = make_unique<DiscoverVersionIterative>(prefix, face, optionsIterative);
     }
+    else if (discoverType == "realtime") {
+      DiscoverVersionRealtime::Options optionsRealtime(options);
+      discover = make_unique<DiscoverVersionRealtime>(prefix, face, optionsRealtime);
+    }
     else {
       std::cerr << "ERROR: discover version type not valid" << std::endl;
       return 2;