Implementing RIT (also using Boost.MultiIndex)

Repair the bug with Name::Components::operator ==
diff --git a/examples/ccnx-test.cc b/examples/ccnx-test.cc
index 0d32793..174d29e 100644
--- a/examples/ccnx-test.cc
+++ b/examples/ccnx-test.cc
@@ -14,6 +14,7 @@
 {
   LogComponentEnable ("CcnxTest", LOG_ALL);
   LogComponentEnable ("CcnxStackHelper", LOG_ALL);
+  LogComponentEnable ("CcnxRit", LOG_ALL);
   
   // Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (210));
   // Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("448kb/s"));
@@ -46,6 +47,29 @@
   CcnxStackHelper ccnx;
   Ptr<CcnxFaceContainer> cf = ccnx.Install (c);
 
+  // test RIT
+  NS_LOG_INFO ("Creating RIT");
+  Ptr<CcnxRit> rit = CreateObject<CcnxRit> ();
+
+  CcnxInterestHeader header;
+  Ptr<Name::Components> testname = Create<Name::Components> ();
+  (*testname) ("test") ("test2");
+  header.SetName (testname);
+  header.SetNonce (1);
+
+  rit->SetRecentlySatisfied (header);
+
+  NS_LOG_INFO (rit->WasRecentlySatisfied (header));
+
+  (*testname) ("test3"); // should have a side effect of changing name in the packet
+  rit->SetRecentlySatisfied (header);
+
+  NS_LOG_INFO (rit->WasRecentlySatisfied (header));
+
+  header.SetNonce (2);
+  NS_LOG_INFO (rit->WasRecentlySatisfied (header));
+
+  // rit->SetRecentlySatisfied (header);
   // ? set up forwarding
   
   
diff --git a/model/ccnx-content-store.cc b/model/ccnx-content-store.cc
index b526308..c47159e 100644
--- a/model/ccnx-content-store.cc
+++ b/model/ccnx-content-store.cc
@@ -33,7 +33,7 @@
 
 NS_OBJECT_ENSURE_REGISTERED (CcnxContentStore);
 
-using namespace __ccnx_private;
+using namespace __ccnx_private_content_store;
 
 TypeId 
 CcnxContentStore::GetTypeId (void)
@@ -55,6 +55,51 @@
 
 CcnxContentObjectTail CcnxContentStoreEntry::m_tail;
 
+//////////////////////////////////////////////////////////////////////
+// Helper classes
+//////////////////////////////////////////////////////////////////////
+/**
+ * \ingroup ccnx
+ * \brief Typedef for hash index of content store container
+ */
+struct CcnxContentStoreByPrefix
+{
+  typedef
+  CcnxContentStoreContainer::type::index<hash>::type
+  type;
+};
+
+/**
+ * \ingroup ccnx
+ * \brief Typedef for MRU index of content store container
+ */
+struct CcnxContentStoreByMru
+{
+  typedef
+  CcnxContentStoreContainer::type::index<mru>::type
+  type;
+};
+
+#ifdef _DEBUG
+#define DUMP_INDEX_TAG ordered
+#define DUMP_INDEX     CcnxContentStoreOrderedPrefix
+/**
+ * \ingroup ccnx
+ * \brief Typedef for ordered index of content store container
+ */
+struct CcnxContentStoreOrderedPrefix
+{
+  typedef
+  CcnxContentStoreContainer::type::index<ordered>::type
+  type;
+};
+#else
+#define DUMP_INDEX_TAG mru
+#define DUMP_INDEX     CcnxContentStoreByMru
+#endif
+
+//////////////////////////////////////////////////////////////////////
+
 CcnxContentStoreEntry::CcnxContentStoreEntry (Ptr<CcnxContentObjectHeader> header, Ptr<const Packet> packet)
   : m_header (header)
 {
diff --git a/model/ccnx-content-store.h b/model/ccnx-content-store.h
index 29b838a..fb68981 100644
--- a/model/ccnx-content-store.h
+++ b/model/ccnx-content-store.h
@@ -110,8 +110,11 @@
   static CcnxContentObjectTail m_tail; ///< \internal for optimization purposes
 };
 
-/// \brief Private namespace for CCNx implementation
-namespace __ccnx_private
+/**
+ * \ingroup ccnx
+ * \brief Private namespace for CCNx content store implementation
+ */
+namespace __ccnx_private_content_store
 {
 class hash {}; ///< tag for Boost.Multiindex container (hashed prefix)
 class mru {}; ///< tag for Boost.Multiindex container (most recent used index)
@@ -137,16 +140,16 @@
     CcnxContentStoreEntry,
     boost::multi_index::indexed_by<
       boost::multi_index::hashed_unique<
-        boost::multi_index::tag<__ccnx_private::hash>,
+        boost::multi_index::tag<__ccnx_private_content_store::hash>,
         boost::multi_index::const_mem_fun<CcnxContentStoreEntry,
                                           const Name::Components&,
                                           &CcnxContentStoreEntry::GetName>,
         CcnxPrefixHash>,
-      boost::multi_index::sequenced<boost::multi_index::tag<__ccnx_private::mru> >
+      boost::multi_index::sequenced<boost::multi_index::tag<__ccnx_private_content_store::mru> >
 #ifdef _DEBUG
       ,
       boost::multi_index::ordered_unique<
-        boost::multi_index::tag<__ccnx_private::ordered>,
+        boost::multi_index::tag<__ccnx_private_content_store::ordered>,
         boost::multi_index::const_mem_fun<CcnxContentStoreEntry,
                                           const Name::Components&,
                                           &CcnxContentStoreEntry::GetName>
@@ -158,46 +161,6 @@
 
 /**
  * \ingroup ccnx
- * \brief Typedef for hash index of content store container
- */
-struct CcnxContentStoreByPrefix
-{
-  typedef
-  CcnxContentStoreContainer::type::index<__ccnx_private::hash>::type
-  type;
-};
-
-/**
- * \ingroup ccnx
- * \brief Typedef for MRU index of content store container
- */
-struct CcnxContentStoreByMru
-{
-  typedef
-  CcnxContentStoreContainer::type::index<__ccnx_private::mru>::type
-  type;
-};
-
-#ifdef _DEBUG
-#define DUMP_INDEX_TAG ordered
-#define DUMP_INDEX     CcnxContentStoreOrderedPrefix
-/**
- * \ingroup ccnx
- * \brief Typedef for ordered index of content store container
- */
-struct CcnxContentStoreOrderedPrefix
-{
-  typedef
-  CcnxContentStoreContainer::type::index<__ccnx_private::ordered>::type
-  type;
-};
-#else
-#define DUMP_INDEX_TAG mru
-#define DUMP_INDEX     CcnxContentStoreByMru
-#endif
-  
-/**
- * \ingroup ccnx
  * \brief NDN content store entry
  */
 class CcnxContentStore : public Object
diff --git a/model/ccnx-interest-header.h b/model/ccnx-interest-header.h
index 44ffa6b..0e13bb8 100644
--- a/model/ccnx-interest-header.h
+++ b/model/ccnx-interest-header.h
@@ -125,7 +125,7 @@
    - InterestLifetime: ?
    - Nonce: 32 bit random integer.  If value is 0, will not be serialized
  */
-  class CcnxInterestHeader : public Header
+class CcnxInterestHeader : public Header
 {
 public:
   /**
diff --git a/model/ccnx-rit.cc b/model/ccnx-rit.cc
new file mode 100644
index 0000000..3fac6fe
--- /dev/null
+++ b/model/ccnx-rit.cc
@@ -0,0 +1,187 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2011 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program 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 this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "ccnx-rit.h"
+
+#include "ns3/log.h"
+#include "ns3/simulator.h"
+#include "ns3/ccnx-interest-header.h"
+#include "ns3/assert.h"
+
+#include <utility>
+
+NS_LOG_COMPONENT_DEFINE ("CcnxRit");
+
+namespace ns3 {
+
+using namespace __ccnx_private_rit;
+
+NS_OBJECT_ENSURE_REGISTERED (CcnxRit);
+
+TypeId 
+CcnxRit::GetTypeId (void)
+{
+  static TypeId tid = TypeId ("ns3::CcnxRit")
+    .SetGroupName ("Ccnx")
+    .SetParent<Object> ()
+    .AddConstructor<CcnxRit> ()
+    .AddAttribute ("RitTimeout",
+                   "Timeout defining how long records should be kept in RIT",
+                   TimeValue (Seconds (1)),
+                   MakeTimeAccessor (&CcnxRit::GetRitTimeout, &CcnxRit::SetRitTimeout),
+                   MakeTimeChecker ())
+    .AddAttribute ("CleanupTimeout",
+                   "Timeout defining how frequent RIT should be cleaned up",
+                   TimeValue (Seconds (1)),
+                   MakeTimeAccessor (&CcnxRit::GetCleanupTimeout, &CcnxRit::SetCleanupTimeout),
+                   MakeTimeChecker ())
+    ;
+
+  return tid;
+}
+
+
+//////////////////////////////////////////////////////////////////////
+// Helper classes
+//////////////////////////////////////////////////////////////////////
+/**
+ * \ingroup ccnx
+ * \brief Typedef for nonce hash index of RIT container
+ */
+struct CcnxRitByNonce
+{
+  typedef
+  CcnxRitContainer::type::index<nonce>::type
+  type;
+};
+
+// /**
+//  * \ingroup ccnx
+//  * \brief Typedef for prefix hash index of RIT container
+//  */
+// struct CcnxRitByTimestamp
+// {
+//   typedef
+//   CcnxRitContainer::type::index<timestamp>::type
+//   type;
+// };
+
+//////////////////////////////////////////////////////////////////////
+
+
+CcnxRit::CcnxRit( )
+{
+}
+
+CcnxRit::~CcnxRit( ) { }
+
+void
+CcnxRit::SetRitTimeout (const Time &timeout)
+{
+  m_ritTimeout = timeout;
+}
+
+Time
+CcnxRit::GetRitTimeout () const
+{
+  return m_ritTimeout;
+}
+
+void
+CcnxRit::SetCleanupTimeout (const Time &timeout)
+{
+  m_cleanupTimeout = timeout;
+  if (m_cleanupEvent.IsRunning ())
+    m_cleanupEvent.Cancel (); // cancel any scheduled cleanup events
+
+  // schedule even with new timeout
+  m_cleanupEvent = Simulator::Schedule (Simulator::Now () + m_cleanupTimeout,
+                                        &CcnxRit::CleanExpired, this); 
+}
+
+Time
+CcnxRit::GetCleanupTimeout () const
+{
+  return m_cleanupTimeout;
+}
+
+bool
+CcnxRit::WasRecentlySatisfied (const CcnxInterestHeader &header)
+{
+  std::pair<CcnxRitByNonce::type::iterator,CcnxRitByNonce::type::iterator>
+    entries = m_rit.get<nonce> ().equal_range (header.GetNonce ());
+  
+  if (entries.first == m_rit.end ())
+    return false;
+
+  // check all entries if the name of RIT entry matches the name of interest
+  for (CcnxRitByNonce::type::iterator it = entries.first; it != entries.second; it++)
+    {
+      // NS_LOG_DEBUG (it->m_prefix << " vs " << header.GetName () << " = " << (it->m_prefix == header.GetName ()));
+      if (it->m_prefix == header.GetName ())
+        return true;
+    }
+
+  return false;
+}
+
+void
+CcnxRit::SetRecentlySatisfied (const CcnxInterestHeader &header)
+{
+  NS_ASSERT_MSG (!WasRecentlySatisfied (header), "Duplicate recent interest should not be added to RIT");
+  
+  m_rit.get<timestamp> ().push_back (
+                                     CcnxRitEntry(header.GetName (),
+                                                  header.GetNonce (),
+                                                  Simulator::Now ()+m_ritTimeout)
+                                     );
+}
+
+
+void CcnxRit::CleanExpired ()
+{
+  NS_LOG_LOGIC ("Cleaning RIT");
+  Time now = Simulator::Now ();
+#ifdef _DEBUG
+  uint32_t count = 0;
+#endif
+  
+  while( !m_rit.empty() )
+    {
+      if( m_rit.get<timestamp> ().front ().m_expireTime <= now ) // is the record stale?
+        {
+         m_rit.get<timestamp> ().pop_front( );
+#ifdef _DEBUG
+         count++;
+#endif
+        }
+      else
+        break; // nothing else to do. All later records will not be stale
+    }
+#ifdef _DEBUG
+  NS_LOG_DEBUG (count << " records cleaned");
+#endif
+  
+  // schedule next even
+  m_cleanupEvent = Simulator::Schedule (Simulator::Now () + m_cleanupTimeout,
+                                        &CcnxRit::CleanExpired, this); 
+}
+
+} //namespace ns3
diff --git a/model/ccnx-rit.h b/model/ccnx-rit.h
new file mode 100644
index 0000000..8220759
--- /dev/null
+++ b/model/ccnx-rit.h
@@ -0,0 +1,207 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2011 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program 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 this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef _CCNX_RIT_H_
+#define	_CCNX_RIT_H_
+
+#include <list>
+#include "ns3/nstime.h"
+#include "ns3/name-components.h"
+#include "ns3/object.h"
+#include "ns3/nstime.h"
+#include "ns3/event-id.h"
+
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/tag.hpp>
+#include <boost/multi_index/ordered_index.hpp>
+#include <boost/multi_index/sequenced_index.hpp>
+#include <boost/multi_index/hashed_index.hpp>
+#include <boost/multi_index/member.hpp>
+
+namespace ns3 {
+
+class CcnxInterestHeader;
+
+/**
+ * \ingroup ccnx
+ * \brief Recently satisfied interest 
+ *
+ * This entry holds information about recently satisfied interest
+ *
+ * RIT entries will stay in the table for a while before being cleaned out
+ */
+struct CcnxRitEntry
+{
+  Name::Components m_prefix; ///< \brief Prefix of the recently satisfied interest
+  uint32_t m_nonce; ///< \brief Nonce of the recently satisfied interest
+  Time m_expireTime;  ///< \brief Time when the record should be removed
+
+  CcnxRitEntry (const Name::Components &prefix, uint32_t nonce, const Time &timeout)
+    : m_prefix (prefix)
+    , m_nonce (nonce)
+    , m_expireTime (timeout)
+  { }
+};
+
+/**
+ * \ingroup ccnx
+ * \brief Private namespace for CCNx RIT implementation
+ */
+namespace __ccnx_private_rit
+{
+class nonce {}; ///< tag for nonce hash
+class timestamp {}; ///< tag for timestamp-ordered records (for cleanup optimization)  
+};
+
+/**
+ * \ingroup ccnx
+ * \brief Typedef for RIT container implemented as a Boost.MultiIndex container
+ *
+ * - First index (tag<nonce>) is a non-unique hash index based on
+ *   nonce (there could be several records with the same nonce,
+ *   provided that the prefixes are different
+ * - Second index (tag<timestamp>) is a sequenced index based on
+ *   arrival order (for clean-up optimizations)
+ *
+ * Container allows having non-unique nonce values.  In the
+ * implementation it is allowed only if prefixes are different. During
+ * the lookup process, the nonce field is checked first and, if a
+ * match found, the prefix field will be checked to match prefix of
+ * the interest.
+ *
+ * \see http://www.boost.org/doc/libs/1_46_1/libs/multi_index/doc/ for more information on Boost.MultiIndex library
+ */
+struct CcnxRitContainer
+{
+  typedef
+  boost::multi_index::multi_index_container<
+    CcnxRitEntry,
+    boost::multi_index::indexed_by<
+      boost::multi_index::hashed_non_unique<
+        boost::multi_index::tag<__ccnx_private_rit::nonce>,
+        boost::multi_index::member<CcnxRitEntry, uint32_t, &CcnxRitEntry::m_nonce>
+        >,
+      boost::multi_index::sequenced<
+        boost::multi_index::tag<__ccnx_private_rit::timestamp> >
+      >
+    > type;
+};
+
+
+/**
+ * \ingroup ccnx
+ * \brief Recently satisfied interest storage
+ *
+ * This storage holds information about all recently satisfied
+ * interests (prefix and nonce).
+ *
+ * There is no hard limit on number of entries (limited by the amount
+ * of the available memory).  Entries are removed after preconfigured
+ * amount of time (RitTimeout, default is 1 second).
+ */
+class CcnxRit : public Object
+{
+public:
+  /**
+   * \brief Interface ID
+   *
+   * \return interface ID
+   */
+  static TypeId GetTypeId ();
+
+  /**
+   * \brief Default constructor
+   */
+  CcnxRit ();
+  virtual ~CcnxRit( );
+
+  /**
+   * \brief Find corresponding RIT entry for the given content name
+   *
+   * This check consists of two steps.  First, we find records with
+   * the same nonce.  Then check prefixes of all found records and if
+   * prefix of any of them matched prefix of the interest, this
+   * function returns true.  In all other cases, it will return false.
+   *
+   * \param header header of the interest packet in question
+   *
+   * \returns true if the same interest was recently satisfied
+   */
+  bool WasRecentlySatisfied (const CcnxInterestHeader &header);
+
+  /**
+   * \brief Add a new RIT entry
+   *
+   * This function asserts (only in debug) if the same interest is
+   * already present in RIT.  The caller is responsible of calling
+   * WasRecentlySatisfied before calling SetRecentlySatisfied.
+   * 
+   * \param header header of the interest packet in question
+   */
+  void SetRecentlySatisfied (const CcnxInterestHeader &header);
+
+  /**
+   * \brief Set RIT entries lifetime
+   *
+   * \param lifetime of RIT entries timeout
+   */
+  void SetRitTimeout (const Time &timeout);
+
+  /**
+   * \brief Get RIT entries lifetime
+   *
+   * \returns lifetime of RIT entries timeout
+   */
+  Time GetRitTimeout () const;
+  
+  /**
+   * \brief Set cleanup timeout
+   *
+   * Side effect: current clean up even (if any) will be cancelled and a new event started
+   *
+   * \param timeout cleanup timeout
+   */
+  void SetCleanupTimeout (const Time &timeout);
+
+  /**
+   * \brief Get cleanup timeout
+   *
+   * \returns cleanup timeout
+   */
+  Time GetCleanupTimeout () const;
+
+private:
+  /**
+   * \brief Periodic even to clean up stalled entries
+   */
+  void CleanExpired ();
+	
+private:
+  Time    m_ritTimeout; ///< \brief Configurable timeout of RIT entries
+  Time    m_cleanupTimeout; ///< \brief Configurable timeout of how often cleanup events are working
+  EventId m_cleanupEvent; ///< \brief Cleanup event
+  
+  CcnxRitContainer::type m_rit; ///< \brief Actual RIT container
+};
+
+} // namespace ns3
+
+#endif // _CCNX_RIT_H_
+
diff --git a/model/name-components.h b/model/name-components.h
index 097152e..5749fcc 100644
--- a/model/name-components.h
+++ b/model/name-components.h
@@ -94,6 +94,9 @@
 bool
 Components::operator== (const Components &prefix) const
 {
+  if (m_prefix.size () != prefix.m_prefix.size ())
+    return false;
+  
   return std::equal (m_prefix.begin (), m_prefix.end (), prefix.m_prefix.begin ());
 }