diff --git a/chromium/components/visitedlink/DEPS b/chromium/components/visitedlink/DEPS new file mode 100644 index 0000000000000000000000000000000000000000..1c40d981eb61603be29c8cbb5bd6f892d2d5b722 --- /dev/null +++ b/chromium/components/visitedlink/DEPS @@ -0,0 +1,3 @@ +include_rules = [ + "+ipc", +] diff --git a/chromium/components/visitedlink/OWNERS b/chromium/components/visitedlink/OWNERS new file mode 100644 index 0000000000000000000000000000000000000000..b221410c272fe614606b4a380362bf63827bf2eb --- /dev/null +++ b/chromium/components/visitedlink/OWNERS @@ -0,0 +1,2 @@ +brettw@chromium.org +sky@chromium.org diff --git a/chromium/components/visitedlink/browser/BUILD.gn b/chromium/components/visitedlink/browser/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4fce197308a3efe8cc7a70b1aeda032bdf220f61 --- /dev/null +++ b/chromium/components/visitedlink/browser/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright 2014 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +static_library("browser") { + output_name = "visitedlink_browser" + sources = [ + "visitedlink_delegate.h", + "visitedlink_event_listener.cc", + "visitedlink_event_listener.h", + "visitedlink_master.cc", + "visitedlink_master.h", + ] + + deps = [ + "//base", + "//components/visitedlink/common", + "//content/public/browser", + "//content/public/common", + ] +} diff --git a/chromium/components/visitedlink/browser/DEPS b/chromium/components/visitedlink/browser/DEPS new file mode 100644 index 0000000000000000000000000000000000000000..1c35d9ca694b7004e71670cd60a883ddbd8c808f --- /dev/null +++ b/chromium/components/visitedlink/browser/DEPS @@ -0,0 +1,3 @@ +include_rules = [ + "+content/public/browser", +] diff --git a/chromium/components/visitedlink/browser/visitedlink_delegate.h b/chromium/components/visitedlink/browser/visitedlink_delegate.h new file mode 100644 index 0000000000000000000000000000000000000000..6adf7de57180d5948707a28a27eaeed9db9d5c9c --- /dev/null +++ b/chromium/components/visitedlink/browser/visitedlink_delegate.h @@ -0,0 +1,51 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_DELEGATE_H_ +#define COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_DELEGATE_H_ + +#include "base/memory/ref_counted.h" + +class GURL; + +namespace content { +class BrowserContext; +} + +namespace visitedlink { + +// Delegate class that clients of VisitedLinkMaster must implement. +class VisitedLinkDelegate { + public: + // See RebuildTable. + class URLEnumerator : public base::RefCountedThreadSafe<URLEnumerator> { + public: + // Call this with each URL to rebuild the table. + virtual void OnURL(const GURL& url) = 0; + + // This must be called by Delegate after RebuildTable is called. |success| + // indicates all URLs have been returned successfully. The URLEnumerator + // object cannot be used by the delegate after this call. + virtual void OnComplete(bool success) = 0; + + protected: + virtual ~URLEnumerator() {} + + private: + friend class base::RefCountedThreadSafe<URLEnumerator>; + }; + + // Delegate class is responsible for persisting the list of visited URLs + // across browser runs. This is called by VisitedLinkMaster to repopulate + // its internal table. Note that methods on enumerator can be called on any + // thread but the delegate is responsible for synchronizating the calls. + virtual void RebuildTable(const scoped_refptr<URLEnumerator>& enumerator) = 0; + + protected: + virtual ~VisitedLinkDelegate() {} +}; + +} // namespace visitedlink + +#endif // COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_DELEGATE_H_ diff --git a/chromium/components/visitedlink/browser/visitedlink_event_listener.cc b/chromium/components/visitedlink/browser/visitedlink_event_listener.cc new file mode 100644 index 0000000000000000000000000000000000000000..a96a0e3aa558132f2e2c3d8e9729fbb8413f42a1 --- /dev/null +++ b/chromium/components/visitedlink/browser/visitedlink_event_listener.cc @@ -0,0 +1,219 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/visitedlink/browser/visitedlink_event_listener.h" + +#include "base/memory/shared_memory.h" +#include "components/visitedlink/browser/visitedlink_delegate.h" +#include "components/visitedlink/common/visitedlink_messages.h" +#include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_types.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/render_widget_host.h" + +using base::Time; +using base::TimeDelta; +using content::RenderWidgetHost; + +namespace { + +// The amount of time we wait to accumulate visited link additions. +const int kCommitIntervalMs = 100; + +// Size of the buffer after which individual link updates deemed not warranted +// and the overall update should be used instead. +const unsigned kVisitedLinkBufferThreshold = 50; + +} // namespace + +namespace visitedlink { + +// This class manages buffering and sending visited link hashes (fingerprints) +// to renderer based on widget visibility. +// As opposed to the VisitedLinkEventListener, which coalesces to +// reduce the rate of messages being sent to render processes, this class +// ensures that the updates occur only when explicitly requested. This is +// used for RenderProcessHostImpl to only send Add/Reset link events to the +// renderers when their tabs are visible and the corresponding RenderViews are +// created. +class VisitedLinkUpdater { + public: + explicit VisitedLinkUpdater(int render_process_id) + : reset_needed_(false), render_process_id_(render_process_id) { + } + + // Informs the renderer about a new visited link table. + void SendVisitedLinkTable(base::SharedMemory* table_memory) { + content::RenderProcessHost* process = + content::RenderProcessHost::FromID(render_process_id_); + if (!process) + return; // Happens in tests + base::SharedMemoryHandle handle_for_process; + table_memory->ShareToProcess(process->GetHandle(), &handle_for_process); + if (base::SharedMemory::IsHandleValid(handle_for_process)) + process->Send(new ChromeViewMsg_VisitedLink_NewTable( + handle_for_process)); + } + + // Buffers |links| to update, but doesn't actually relay them. + void AddLinks(const VisitedLinkCommon::Fingerprints& links) { + if (reset_needed_) + return; + + if (pending_.size() + links.size() > kVisitedLinkBufferThreshold) { + // Once the threshold is reached, there's no need to store pending visited + // link updates -- we opt for resetting the state for all links. + AddReset(); + return; + } + + pending_.insert(pending_.end(), links.begin(), links.end()); + } + + // Tells the updater that sending individual link updates is no longer + // necessary and the visited state for all links should be reset. + void AddReset() { + reset_needed_ = true; + pending_.clear(); + } + + // Sends visited link update messages: a list of links whose visited state + // changed or reset of visited state for all links. + void Update() { + content::RenderProcessHost* process = + content::RenderProcessHost::FromID(render_process_id_); + if (!process) + return; // Happens in tests + + if (!process->VisibleWidgetCount()) + return; + + if (reset_needed_) { + process->Send(new ChromeViewMsg_VisitedLink_Reset()); + reset_needed_ = false; + return; + } + + if (pending_.empty()) + return; + + process->Send(new ChromeViewMsg_VisitedLink_Add(pending_)); + + pending_.clear(); + } + + private: + bool reset_needed_; + int render_process_id_; + VisitedLinkCommon::Fingerprints pending_; +}; + +VisitedLinkEventListener::VisitedLinkEventListener( + VisitedLinkMaster* master, + content::BrowserContext* browser_context) + : master_(master), + browser_context_(browser_context) { + registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED, + content::NotificationService::AllBrowserContextsAndSources()); + registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, + content::NotificationService::AllBrowserContextsAndSources()); + registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, + content::NotificationService::AllBrowserContextsAndSources()); +} + +VisitedLinkEventListener::~VisitedLinkEventListener() { + if (!pending_visited_links_.empty()) + pending_visited_links_.clear(); +} + +void VisitedLinkEventListener::NewTable(base::SharedMemory* table_memory) { + if (!table_memory) + return; + + // Send to all RenderProcessHosts. + for (Updaters::iterator i = updaters_.begin(); i != updaters_.end(); ++i) { + // Make sure to not send to incognito renderers. + content::RenderProcessHost* process = + content::RenderProcessHost::FromID(i->first); + if (!process) + continue; + + i->second->SendVisitedLinkTable(table_memory); + } +} + +void VisitedLinkEventListener::Add(VisitedLinkMaster::Fingerprint fingerprint) { + pending_visited_links_.push_back(fingerprint); + + if (!coalesce_timer_.IsRunning()) { + coalesce_timer_.Start(FROM_HERE, + TimeDelta::FromMilliseconds(kCommitIntervalMs), this, + &VisitedLinkEventListener::CommitVisitedLinks); + } +} + +void VisitedLinkEventListener::Reset() { + pending_visited_links_.clear(); + coalesce_timer_.Stop(); + + for (Updaters::iterator i = updaters_.begin(); i != updaters_.end(); ++i) { + i->second->AddReset(); + i->second->Update(); + } +} + +void VisitedLinkEventListener::CommitVisitedLinks() { + // Send to all RenderProcessHosts. + for (Updaters::iterator i = updaters_.begin(); i != updaters_.end(); ++i) { + i->second->AddLinks(pending_visited_links_); + i->second->Update(); + } + + pending_visited_links_.clear(); +} + +void VisitedLinkEventListener::Observe( + int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + switch (type) { + case content::NOTIFICATION_RENDERER_PROCESS_CREATED: { + content::RenderProcessHost* process = + content::Source<content::RenderProcessHost>(source).ptr(); + if (browser_context_ != process->GetBrowserContext()) + return; + + // Happens on browser start up. + if (!master_->shared_memory()) + return; + + updaters_[process->GetID()] = + make_linked_ptr(new VisitedLinkUpdater(process->GetID())); + updaters_[process->GetID()]->SendVisitedLinkTable( + master_->shared_memory()); + break; + } + case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: { + content::RenderProcessHost* process = + content::Source<content::RenderProcessHost>(source).ptr(); + if (updaters_.count(process->GetID())) { + updaters_.erase(process->GetID()); + } + break; + } + case content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED: { + RenderWidgetHost* widget = + content::Source<RenderWidgetHost>(source).ptr(); + int child_id = widget->GetProcess()->GetID(); + if (updaters_.count(child_id)) + updaters_[child_id]->Update(); + break; + } + default: + NOTREACHED(); + break; + } +} + +} // namespace visitedlink diff --git a/chromium/components/visitedlink/browser/visitedlink_event_listener.h b/chromium/components/visitedlink/browser/visitedlink_event_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..c2de5d205d0dc14126ae7e25170bd4a64163992b --- /dev/null +++ b/chromium/components/visitedlink/browser/visitedlink_event_listener.h @@ -0,0 +1,70 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_EVENT_LISTENER_H_ +#define COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_EVENT_LISTENER_H_ + +#include <map> + +#include "base/memory/linked_ptr.h" +#include "base/timer/timer.h" +#include "components/visitedlink/browser/visitedlink_master.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" + +namespace base { +class SharedMemory; +} + +namespace content { +class BrowserContext; +} + +namespace visitedlink { + +class VisitedLinkUpdater; + +// VisitedLinkEventListener broadcasts link coloring database updates to all +// processes. It also coalesces the updates to avoid excessive broadcasting of +// messages to the renderers. +class VisitedLinkEventListener : public VisitedLinkMaster::Listener, + public content::NotificationObserver { + public: + VisitedLinkEventListener(VisitedLinkMaster* master, + content::BrowserContext* browser_context); + virtual ~VisitedLinkEventListener(); + + virtual void NewTable(base::SharedMemory* table_memory) OVERRIDE; + virtual void Add(VisitedLinkMaster::Fingerprint fingerprint) OVERRIDE; + virtual void Reset() OVERRIDE; + + private: + void CommitVisitedLinks(); + + // content::NotificationObserver implementation. + virtual void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) OVERRIDE; + + base::OneShotTimer<VisitedLinkEventListener> coalesce_timer_; + VisitedLinkCommon::Fingerprints pending_visited_links_; + + content::NotificationRegistrar registrar_; + + // Map between renderer child ids and their VisitedLinkUpdater. + typedef std::map<int, linked_ptr<VisitedLinkUpdater> > Updaters; + Updaters updaters_; + + VisitedLinkMaster* master_; + + // Used to filter RENDERER_PROCESS_CREATED notifications to renderers that + // belong to this BrowserContext. + content::BrowserContext* browser_context_; + + DISALLOW_COPY_AND_ASSIGN(VisitedLinkEventListener); +}; + +} // namespace visitedlink + +#endif // COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_EVENT_LISTENER_H_ diff --git a/chromium/components/visitedlink/browser/visitedlink_master.cc b/chromium/components/visitedlink/browser/visitedlink_master.cc new file mode 100644 index 0000000000000000000000000000000000000000..ca8c5710ca58ce4d5afc9a49e7763f1a1ccca8a5 --- /dev/null +++ b/chromium/components/visitedlink/browser/visitedlink_master.cc @@ -0,0 +1,987 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/visitedlink/browser/visitedlink_master.h" + +#if defined(OS_WIN) +#include <windows.h> +#include <io.h> +#include <shlobj.h> +#endif // defined(OS_WIN) +#include <stdio.h> + +#include <algorithm> + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/containers/stack_container.h" +#include "base/file_util.h" +#include "base/files/scoped_file.h" +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "base/path_service.h" +#include "base/rand_util.h" +#include "base/strings/string_util.h" +#include "base/threading/thread_restrictions.h" +#include "components/visitedlink/browser/visitedlink_delegate.h" +#include "components/visitedlink/browser/visitedlink_event_listener.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/browser_thread.h" +#include "url/gurl.h" + +using content::BrowserThread; + +namespace visitedlink { + +const int32 VisitedLinkMaster::kFileHeaderSignatureOffset = 0; +const int32 VisitedLinkMaster::kFileHeaderVersionOffset = 4; +const int32 VisitedLinkMaster::kFileHeaderLengthOffset = 8; +const int32 VisitedLinkMaster::kFileHeaderUsedOffset = 12; +const int32 VisitedLinkMaster::kFileHeaderSaltOffset = 16; + +const int32 VisitedLinkMaster::kFileCurrentVersion = 3; + +// the signature at the beginning of the URL table = "VLnk" (visited links) +const int32 VisitedLinkMaster::kFileSignature = 0x6b6e4c56; +const size_t VisitedLinkMaster::kFileHeaderSize = + kFileHeaderSaltOffset + LINK_SALT_LENGTH; + +// This value should also be the same as the smallest size in the lookup +// table in NewTableSizeForCount (prime number). +const unsigned VisitedLinkMaster::kDefaultTableSize = 16381; + +const size_t VisitedLinkMaster::kBigDeleteThreshold = 64; + +namespace { + +// Fills the given salt structure with some quasi-random values +// It is not necessary to generate a cryptographically strong random string, +// only that it be reasonably different for different users. +void GenerateSalt(uint8 salt[LINK_SALT_LENGTH]) { + DCHECK_EQ(LINK_SALT_LENGTH, 8) << "This code assumes the length of the salt"; + uint64 randval = base::RandUint64(); + memcpy(salt, &randval, 8); +} + +// Opens file on a background thread to not block UI thread. +void AsyncOpen(FILE** file, const base::FilePath& filename) { + *file = base::OpenFile(filename, "wb+"); + DLOG_IF(ERROR, !(*file)) << "Failed to open file " << filename.value(); +} + +// Returns true if the write was complete. +static bool WriteToFile(FILE* file, + off_t offset, + const void* data, + size_t data_len) { + if (fseek(file, offset, SEEK_SET) != 0) + return false; // Don't write to an invalid part of the file. + + size_t num_written = fwrite(data, 1, data_len, file); + + // The write may not make it to the kernel (stdlib may buffer the write) + // until the next fseek/fclose call. If we crash, it's easy for our used + // item count to be out of sync with the number of hashes we write. + // Protect against this by calling fflush. + int ret = fflush(file); + DCHECK_EQ(0, ret); + return num_written == data_len; +} + +// This task executes on a background thread and executes a write. This +// prevents us from blocking the UI thread doing I/O. Double pointer to FILE +// is used because file may still not be opened by the time of scheduling +// the task for execution. +void AsyncWrite(FILE** file, int32 offset, const std::string& data) { + if (*file) + WriteToFile(*file, offset, data.data(), data.size()); +} + +// Truncates the file to the current position asynchronously on a background +// thread. Double pointer to FILE is used because file may still not be opened +// by the time of scheduling the task for execution. +void AsyncTruncate(FILE** file) { + if (*file) + base::IgnoreResult(base::TruncateFile(*file)); +} + +// Closes the file on a background thread and releases memory used for storage +// of FILE* value. Double pointer to FILE is used because file may still not +// be opened by the time of scheduling the task for execution. +void AsyncClose(FILE** file) { + if (*file) + base::IgnoreResult(fclose(*file)); + free(file); +} + +} // namespace + +// TableBuilder --------------------------------------------------------------- + +// How rebuilding from history works +// --------------------------------- +// +// We mark that we're rebuilding from history by setting the table_builder_ +// member in VisitedLinkMaster to the TableBuilder we create. This builder +// will be called on the history thread by the history system for every URL +// in the database. +// +// The builder will store the fingerprints for those URLs, and then marshalls +// back to the main thread where the VisitedLinkMaster will be notified. The +// master then replaces its table with a new table containing the computed +// fingerprints. +// +// The builder must remain active while the history system is using it. +// Sometimes, the master will be deleted before the rebuild is complete, in +// which case it notifies the builder via DisownMaster(). The builder will +// delete itself once rebuilding is complete, and not execute any callback. +class VisitedLinkMaster::TableBuilder + : public VisitedLinkDelegate::URLEnumerator { + public: + TableBuilder(VisitedLinkMaster* master, + const uint8 salt[LINK_SALT_LENGTH]); + + // Called on the main thread when the master is being destroyed. This will + // prevent a crash when the query completes and the master is no longer + // around. We can not actually do anything but mark this fact, since the + // table will be being rebuilt simultaneously on the other thread. + void DisownMaster(); + + // VisitedLinkDelegate::URLEnumerator + virtual void OnURL(const GURL& url) OVERRIDE; + virtual void OnComplete(bool succeed) OVERRIDE; + + private: + virtual ~TableBuilder() {} + + // OnComplete mashals to this function on the main thread to do the + // notification. + void OnCompleteMainThread(); + + // Owner of this object. MAY ONLY BE ACCESSED ON THE MAIN THREAD! + VisitedLinkMaster* master_; + + // Indicates whether the operation has failed or not. + bool success_; + + // Salt for this new table. + uint8 salt_[LINK_SALT_LENGTH]; + + // Stores the fingerprints we computed on the background thread. + VisitedLinkCommon::Fingerprints fingerprints_; + + DISALLOW_COPY_AND_ASSIGN(TableBuilder); +}; + +// VisitedLinkMaster ---------------------------------------------------------- + +VisitedLinkMaster::VisitedLinkMaster(content::BrowserContext* browser_context, + VisitedLinkDelegate* delegate, + bool persist_to_disk) + : browser_context_(browser_context), + delegate_(delegate), + listener_(new VisitedLinkEventListener(this, browser_context)), + persist_to_disk_(persist_to_disk) { + InitMembers(); +} + +VisitedLinkMaster::VisitedLinkMaster(Listener* listener, + VisitedLinkDelegate* delegate, + bool persist_to_disk, + bool suppress_rebuild, + const base::FilePath& filename, + int32 default_table_size) + : browser_context_(NULL), + delegate_(delegate), + persist_to_disk_(persist_to_disk) { + listener_.reset(listener); + DCHECK(listener_.get()); + InitMembers(); + + database_name_override_ = filename; + table_size_override_ = default_table_size; + suppress_rebuild_ = suppress_rebuild; +} + +VisitedLinkMaster::~VisitedLinkMaster() { + if (table_builder_.get()) { + // Prevent the table builder from calling us back now that we're being + // destroyed. Note that we DON'T delete the object, since the history + // system is still writing into it. When that is complete, the table + // builder will destroy itself when it finds we are gone. + table_builder_->DisownMaster(); + } + FreeURLTable(); + // FreeURLTable() will schedule closing of the file and deletion of |file_|. + // So nothing should be done here. +} + +void VisitedLinkMaster::InitMembers() { + file_ = NULL; + shared_memory_ = NULL; + shared_memory_serial_ = 0; + used_items_ = 0; + table_size_override_ = 0; + suppress_rebuild_ = false; + sequence_token_ = BrowserThread::GetBlockingPool()->GetSequenceToken(); + +#ifndef NDEBUG + posted_asynchronous_operation_ = false; +#endif +} + +bool VisitedLinkMaster::Init() { + // We probably shouldn't be loading this from the UI thread, + // but it does need to happen early on in startup. + // http://code.google.com/p/chromium/issues/detail?id=24163 + base::ThreadRestrictions::ScopedAllowIO allow_io; + + if (persist_to_disk_) { + if (InitFromFile()) + return true; + } + return InitFromScratch(suppress_rebuild_); +} + +VisitedLinkMaster::Hash VisitedLinkMaster::TryToAddURL(const GURL& url) { + // Extra check that we are not incognito. This should not happen. + // TODO(boliu): Move this check to HistoryService when IsOffTheRecord is + // removed from BrowserContext. + if (browser_context_ && browser_context_->IsOffTheRecord()) { + NOTREACHED(); + return null_hash_; + } + + if (!url.is_valid()) + return null_hash_; // Don't add invalid URLs. + + Fingerprint fingerprint = ComputeURLFingerprint(url.spec().data(), + url.spec().size(), + salt_); + if (table_builder_.get()) { + // If we have a pending delete for this fingerprint, cancel it. + std::set<Fingerprint>::iterator found = + deleted_since_rebuild_.find(fingerprint); + if (found != deleted_since_rebuild_.end()) + deleted_since_rebuild_.erase(found); + + // A rebuild is in progress, save this addition in the temporary list so + // it can be added once rebuild is complete. + added_since_rebuild_.insert(fingerprint); + } + + // If the table is "full", we don't add URLs and just drop them on the floor. + // This can happen if we get thousands of new URLs and something causes + // the table resizing to fail. This check prevents a hang in that case. Note + // that this is *not* the resize limit, this is just a sanity check. + if (used_items_ / 8 > table_length_ / 10) + return null_hash_; // Table is more than 80% full. + + return AddFingerprint(fingerprint, true); +} + +void VisitedLinkMaster::PostIOTask(const tracked_objects::Location& from_here, + const base::Closure& task) { + DCHECK(persist_to_disk_); + BrowserThread::GetBlockingPool()->PostSequencedWorkerTask(sequence_token_, + from_here, task); +} + +void VisitedLinkMaster::AddURL(const GURL& url) { + Hash index = TryToAddURL(url); + if (!table_builder_.get() && index != null_hash_) { + // Not rebuilding, so we want to keep the file on disk up-to-date. + if (persist_to_disk_) { + WriteUsedItemCountToFile(); + WriteHashRangeToFile(index, index); + } + ResizeTableIfNecessary(); + } +} + +void VisitedLinkMaster::AddURLs(const std::vector<GURL>& url) { + for (std::vector<GURL>::const_iterator i = url.begin(); + i != url.end(); ++i) { + Hash index = TryToAddURL(*i); + if (!table_builder_.get() && index != null_hash_) + ResizeTableIfNecessary(); + } + + // Keeps the file on disk up-to-date. + if (!table_builder_.get() && persist_to_disk_) + WriteFullTable(); +} + +void VisitedLinkMaster::DeleteAllURLs() { + // Any pending modifications are invalid. + added_since_rebuild_.clear(); + deleted_since_rebuild_.clear(); + + // Clear the hash table. + used_items_ = 0; + memset(hash_table_, 0, this->table_length_ * sizeof(Fingerprint)); + + // Resize it if it is now too empty. Resize may write the new table out for + // us, otherwise, schedule writing the new table to disk ourselves. + if (!ResizeTableIfNecessary() && persist_to_disk_) + WriteFullTable(); + + listener_->Reset(); +} + +VisitedLinkDelegate* VisitedLinkMaster::GetDelegate() { + return delegate_; +} + +void VisitedLinkMaster::DeleteURLs(URLIterator* urls) { + if (!urls->HasNextURL()) + return; + + listener_->Reset(); + + if (table_builder_.get()) { + // A rebuild is in progress, save this deletion in the temporary list so + // it can be added once rebuild is complete. + while (urls->HasNextURL()) { + const GURL& url(urls->NextURL()); + if (!url.is_valid()) + continue; + + Fingerprint fingerprint = + ComputeURLFingerprint(url.spec().data(), url.spec().size(), salt_); + deleted_since_rebuild_.insert(fingerprint); + + // If the URL was just added and now we're deleting it, it may be in the + // list of things added since the last rebuild. Delete it from that list. + std::set<Fingerprint>::iterator found = + added_since_rebuild_.find(fingerprint); + if (found != added_since_rebuild_.end()) + added_since_rebuild_.erase(found); + + // Delete the URLs from the in-memory table, but don't bother writing + // to disk since it will be replaced soon. + DeleteFingerprint(fingerprint, false); + } + return; + } + + // Compute the deleted URLs' fingerprints and delete them + std::set<Fingerprint> deleted_fingerprints; + while (urls->HasNextURL()) { + const GURL& url(urls->NextURL()); + if (!url.is_valid()) + continue; + deleted_fingerprints.insert( + ComputeURLFingerprint(url.spec().data(), url.spec().size(), salt_)); + } + DeleteFingerprintsFromCurrentTable(deleted_fingerprints); +} + +// See VisitedLinkCommon::IsVisited which should be in sync with this algorithm +VisitedLinkMaster::Hash VisitedLinkMaster::AddFingerprint( + Fingerprint fingerprint, + bool send_notifications) { + if (!hash_table_ || table_length_ == 0) { + NOTREACHED(); // Not initialized. + return null_hash_; + } + + Hash cur_hash = HashFingerprint(fingerprint); + Hash first_hash = cur_hash; + while (true) { + Fingerprint cur_fingerprint = FingerprintAt(cur_hash); + if (cur_fingerprint == fingerprint) + return null_hash_; // This fingerprint is already in there, do nothing. + + if (cur_fingerprint == null_fingerprint_) { + // End of probe sequence found, insert here. + hash_table_[cur_hash] = fingerprint; + used_items_++; + // If allowed, notify listener that a new visited link was added. + if (send_notifications) + listener_->Add(fingerprint); + return cur_hash; + } + + // Advance in the probe sequence. + cur_hash = IncrementHash(cur_hash); + if (cur_hash == first_hash) { + // This means that we've wrapped around and are about to go into an + // infinite loop. Something was wrong with the hashtable resizing + // logic, so stop here. + NOTREACHED(); + return null_hash_; + } + } +} + +void VisitedLinkMaster::DeleteFingerprintsFromCurrentTable( + const std::set<Fingerprint>& fingerprints) { + bool bulk_write = (fingerprints.size() > kBigDeleteThreshold); + + // Delete the URLs from the table. + for (std::set<Fingerprint>::const_iterator i = fingerprints.begin(); + i != fingerprints.end(); ++i) + DeleteFingerprint(*i, !bulk_write); + + // These deleted fingerprints may make us shrink the table. + if (ResizeTableIfNecessary()) + return; // The resize function wrote the new table to disk for us. + + // Nobody wrote this out for us, write the full file to disk. + if (bulk_write && persist_to_disk_) + WriteFullTable(); +} + +bool VisitedLinkMaster::DeleteFingerprint(Fingerprint fingerprint, + bool update_file) { + if (!hash_table_ || table_length_ == 0) { + NOTREACHED(); // Not initialized. + return false; + } + if (!IsVisited(fingerprint)) + return false; // Not in the database to delete. + + // First update the header used count. + used_items_--; + if (update_file && persist_to_disk_) + WriteUsedItemCountToFile(); + + Hash deleted_hash = HashFingerprint(fingerprint); + + // Find the range of "stuff" in the hash table that is adjacent to this + // fingerprint. These are things that could be affected by the change in + // the hash table. Since we use linear probing, anything after the deleted + // item up until an empty item could be affected. + Hash end_range = deleted_hash; + while (true) { + Hash next_hash = IncrementHash(end_range); + if (next_hash == deleted_hash) + break; // We wrapped around and the whole table is full. + if (!hash_table_[next_hash]) + break; // Found the last spot. + end_range = next_hash; + } + + // We could get all fancy and move the affected fingerprints around, but + // instead we just remove them all and re-add them (minus our deleted one). + // This will mean there's a small window of time where the affected links + // won't be marked visited. + base::StackVector<Fingerprint, 32> shuffled_fingerprints; + Hash stop_loop = IncrementHash(end_range); // The end range is inclusive. + for (Hash i = deleted_hash; i != stop_loop; i = IncrementHash(i)) { + if (hash_table_[i] != fingerprint) { + // Don't save the one we're deleting! + shuffled_fingerprints->push_back(hash_table_[i]); + + // This will balance the increment of this value in AddFingerprint below + // so there is no net change. + used_items_--; + } + hash_table_[i] = null_fingerprint_; + } + + if (!shuffled_fingerprints->empty()) { + // Need to add the new items back. + for (size_t i = 0; i < shuffled_fingerprints->size(); i++) + AddFingerprint(shuffled_fingerprints[i], false); + } + + // Write the affected range to disk [deleted_hash, end_range]. + if (update_file && persist_to_disk_) + WriteHashRangeToFile(deleted_hash, end_range); + + return true; +} + +void VisitedLinkMaster::WriteFullTable() { + // This function can get called when the file is open, for example, when we + // resize the table. We must handle this case and not try to reopen the file, + // since there may be write operations pending on the file I/O thread. + // + // Note that once we start writing, we do not delete on error. This means + // there can be a partial file, but the short file will be detected next time + // we start, and will be replaced. + // + // This might possibly get corrupted if we crash in the middle of writing. + // We should pick up the most common types of these failures when we notice + // that the file size is different when we load it back in, and then we will + // regenerate the table. + DCHECK(persist_to_disk_); + + if (!file_) { + file_ = static_cast<FILE**>(calloc(1, sizeof(*file_))); + base::FilePath filename; + GetDatabaseFileName(&filename); + PostIOTask(FROM_HERE, base::Bind(&AsyncOpen, file_, filename)); + } + + // Write the new header. + int32 header[4]; + header[0] = kFileSignature; + header[1] = kFileCurrentVersion; + header[2] = table_length_; + header[3] = used_items_; + WriteToFile(file_, 0, header, sizeof(header)); + WriteToFile(file_, sizeof(header), salt_, LINK_SALT_LENGTH); + + // Write the hash data. + WriteToFile(file_, kFileHeaderSize, + hash_table_, table_length_ * sizeof(Fingerprint)); + + // The hash table may have shrunk, so make sure this is the end. + PostIOTask(FROM_HERE, base::Bind(&AsyncTruncate, file_)); +} + +bool VisitedLinkMaster::InitFromFile() { + DCHECK(file_ == NULL); + DCHECK(persist_to_disk_); + + base::FilePath filename; + GetDatabaseFileName(&filename); + base::ScopedFILE file_closer(base::OpenFile(filename, "rb+")); + if (!file_closer.get()) + return false; + + int32 num_entries, used_count; + if (!ReadFileHeader(file_closer.get(), &num_entries, &used_count, salt_)) + return false; // Header isn't valid. + + // Allocate and read the table. + if (!CreateURLTable(num_entries, false)) + return false; + if (!ReadFromFile(file_closer.get(), kFileHeaderSize, + hash_table_, num_entries * sizeof(Fingerprint))) { + FreeURLTable(); + return false; + } + used_items_ = used_count; + +#ifndef NDEBUG + DebugValidate(); +#endif + + file_ = static_cast<FILE**>(malloc(sizeof(*file_))); + *file_ = file_closer.release(); + return true; +} + +bool VisitedLinkMaster::InitFromScratch(bool suppress_rebuild) { + int32 table_size = kDefaultTableSize; + if (table_size_override_) + table_size = table_size_override_; + + // The salt must be generated before the table so that it can be copied to + // the shared memory. + GenerateSalt(salt_); + if (!CreateURLTable(table_size, true)) + return false; + +#ifndef NDEBUG + DebugValidate(); +#endif + + if (suppress_rebuild && persist_to_disk_) { + // When we disallow rebuilds (normally just unit tests), just use the + // current empty table. + WriteFullTable(); + return true; + } + + // This will build the table from history. On the first run, history will + // be empty, so this will be correct. This will also write the new table + // to disk. We don't want to save explicitly here, since the rebuild may + // not complete, leaving us with an empty but valid visited link database. + // In the future, we won't know we need to try rebuilding again. + return RebuildTableFromDelegate(); +} + +bool VisitedLinkMaster::ReadFileHeader(FILE* file, + int32* num_entries, + int32* used_count, + uint8 salt[LINK_SALT_LENGTH]) { + DCHECK(persist_to_disk_); + + // Get file size. + // Note that there is no need to seek back to the original location in the + // file since ReadFromFile() [which is the next call accessing the file] + // seeks before reading. + if (fseek(file, 0, SEEK_END) == -1) + return false; + size_t file_size = ftell(file); + + if (file_size <= kFileHeaderSize) + return false; + + uint8 header[kFileHeaderSize]; + if (!ReadFromFile(file, 0, &header, kFileHeaderSize)) + return false; + + // Verify the signature. + int32 signature; + memcpy(&signature, &header[kFileHeaderSignatureOffset], sizeof(signature)); + if (signature != kFileSignature) + return false; + + // Verify the version is up-to-date. As with other read errors, a version + // mistmatch will trigger a rebuild of the database from history, which will + // have the effect of migrating the database. + int32 version; + memcpy(&version, &header[kFileHeaderVersionOffset], sizeof(version)); + if (version != kFileCurrentVersion) + return false; // Bad version. + + // Read the table size and make sure it matches the file size. + memcpy(num_entries, &header[kFileHeaderLengthOffset], sizeof(*num_entries)); + if (*num_entries * sizeof(Fingerprint) + kFileHeaderSize != file_size) + return false; // Bad size. + + // Read the used item count. + memcpy(used_count, &header[kFileHeaderUsedOffset], sizeof(*used_count)); + if (*used_count > *num_entries) + return false; // Bad used item count; + + // Read the salt. + memcpy(salt, &header[kFileHeaderSaltOffset], LINK_SALT_LENGTH); + + // This file looks OK from the header's perspective. + return true; +} + +bool VisitedLinkMaster::GetDatabaseFileName(base::FilePath* filename) { + if (!database_name_override_.empty()) { + // use this filename, the directory must exist + *filename = database_name_override_; + return true; + } + + if (!browser_context_ || browser_context_->GetPath().empty()) + return false; + + base::FilePath profile_dir = browser_context_->GetPath(); + *filename = profile_dir.Append(FILE_PATH_LITERAL("Visited Links")); + return true; +} + +// Initializes the shared memory structure. The salt should already be filled +// in so that it can be written to the shared memory +bool VisitedLinkMaster::CreateURLTable(int32 num_entries, bool init_to_empty) { + // The table is the size of the table followed by the entries. + uint32 alloc_size = num_entries * sizeof(Fingerprint) + sizeof(SharedHeader); + + // Create the shared memory object. + shared_memory_ = new base::SharedMemory(); + if (!shared_memory_) + return false; + + if (!shared_memory_->CreateAndMapAnonymous(alloc_size)) { + delete shared_memory_; + shared_memory_ = NULL; + return false; + } + + if (init_to_empty) { + memset(shared_memory_->memory(), 0, alloc_size); + used_items_ = 0; + } + table_length_ = num_entries; + + // Save the header for other processes to read. + SharedHeader* header = static_cast<SharedHeader*>(shared_memory_->memory()); + header->length = table_length_; + memcpy(header->salt, salt_, LINK_SALT_LENGTH); + + // Our table pointer is just the data immediately following the size. + hash_table_ = reinterpret_cast<Fingerprint*>( + static_cast<char*>(shared_memory_->memory()) + sizeof(SharedHeader)); + + return true; +} + +bool VisitedLinkMaster::BeginReplaceURLTable(int32 num_entries) { + base::SharedMemory *old_shared_memory = shared_memory_; + Fingerprint* old_hash_table = hash_table_; + int32 old_table_length = table_length_; + if (!CreateURLTable(num_entries, true)) { + // Try to put back the old state. + shared_memory_ = old_shared_memory; + hash_table_ = old_hash_table; + table_length_ = old_table_length; + return false; + } + +#ifndef NDEBUG + DebugValidate(); +#endif + + return true; +} + +void VisitedLinkMaster::FreeURLTable() { + if (shared_memory_) { + delete shared_memory_; + shared_memory_ = NULL; + } + if (!persist_to_disk_ || !file_) + return; + PostIOTask(FROM_HERE, base::Bind(&AsyncClose, file_)); + // AsyncClose() will close the file and free the memory pointed by |file_|. + file_ = NULL; +} + +bool VisitedLinkMaster::ResizeTableIfNecessary() { + DCHECK(table_length_ > 0) << "Must have a table"; + + // Load limits for good performance/space. We are pretty conservative about + // keeping the table not very full. This is because we use linear probing + // which increases the likelihood of clumps of entries which will reduce + // performance. + const float max_table_load = 0.5f; // Grow when we're > this full. + const float min_table_load = 0.2f; // Shrink when we're < this full. + + float load = ComputeTableLoad(); + if (load < max_table_load && + (table_length_ <= static_cast<float>(kDefaultTableSize) || + load > min_table_load)) + return false; + + // Table needs to grow or shrink. + int new_size = NewTableSizeForCount(used_items_); + DCHECK(new_size > used_items_); + DCHECK(load <= min_table_load || new_size > table_length_); + ResizeTable(new_size); + return true; +} + +void VisitedLinkMaster::ResizeTable(int32 new_size) { + DCHECK(shared_memory_ && shared_memory_->memory() && hash_table_); + shared_memory_serial_++; + +#ifndef NDEBUG + DebugValidate(); +#endif + + base::SharedMemory* old_shared_memory = shared_memory_; + Fingerprint* old_hash_table = hash_table_; + int32 old_table_length = table_length_; + if (!BeginReplaceURLTable(new_size)) + return; + + // Now we have two tables, our local copy which is the old one, and the new + // one loaded into this object where we need to copy the data. + for (int32 i = 0; i < old_table_length; i++) { + Fingerprint cur = old_hash_table[i]; + if (cur) + AddFingerprint(cur, false); + } + + // On error unmapping, just forget about it since we can't do anything + // else to release it. + delete old_shared_memory; + + // Send an update notification to all child processes so they read the new + // table. + listener_->NewTable(shared_memory_); + +#ifndef NDEBUG + DebugValidate(); +#endif + + // The new table needs to be written to disk. + if (persist_to_disk_) + WriteFullTable(); +} + +uint32 VisitedLinkMaster::NewTableSizeForCount(int32 item_count) const { + // These table sizes are selected to be the maximum prime number less than + // a "convenient" multiple of 1K. + static const int table_sizes[] = { + 16381, // 16K = 16384 <- don't shrink below this table size + // (should be == default_table_size) + 32767, // 32K = 32768 + 65521, // 64K = 65536 + 130051, // 128K = 131072 + 262127, // 256K = 262144 + 524269, // 512K = 524288 + 1048549, // 1M = 1048576 + 2097143, // 2M = 2097152 + 4194301, // 4M = 4194304 + 8388571, // 8M = 8388608 + 16777199, // 16M = 16777216 + 33554347}; // 32M = 33554432 + + // Try to leave the table 33% full. + int desired = item_count * 3; + + // Find the closest prime. + for (size_t i = 0; i < arraysize(table_sizes); i ++) { + if (table_sizes[i] > desired) + return table_sizes[i]; + } + + // Growing very big, just approximate a "good" number, not growing as much + // as normal. + return item_count * 2 - 1; +} + +// See the TableBuilder definition in the header file for how this works. +bool VisitedLinkMaster::RebuildTableFromDelegate() { + DCHECK(!table_builder_.get()); + + // TODO(brettw) make sure we have reasonable salt! + table_builder_ = new TableBuilder(this, salt_); + delegate_->RebuildTable(table_builder_); + return true; +} + +// See the TableBuilder declaration above for how this works. +void VisitedLinkMaster::OnTableRebuildComplete( + bool success, + const std::vector<Fingerprint>& fingerprints) { + if (success) { + // Replace the old table with a new blank one. + shared_memory_serial_++; + + // We are responsible for freeing it AFTER it has been replaced if + // replacement succeeds. + base::SharedMemory* old_shared_memory = shared_memory_; + + int new_table_size = NewTableSizeForCount( + static_cast<int>(fingerprints.size() + added_since_rebuild_.size())); + if (BeginReplaceURLTable(new_table_size)) { + // Free the old table. + delete old_shared_memory; + + // Add the stored fingerprints to the hash table. + for (size_t i = 0; i < fingerprints.size(); i++) + AddFingerprint(fingerprints[i], false); + + // Also add anything that was added while we were asynchronously + // generating the new table. + for (std::set<Fingerprint>::iterator i = added_since_rebuild_.begin(); + i != added_since_rebuild_.end(); ++i) + AddFingerprint(*i, false); + added_since_rebuild_.clear(); + + // Now handle deletions. + DeleteFingerprintsFromCurrentTable(deleted_since_rebuild_); + deleted_since_rebuild_.clear(); + + // Send an update notification to all child processes. + listener_->NewTable(shared_memory_); + + if (persist_to_disk_) + WriteFullTable(); + } + } + table_builder_ = NULL; // Will release our reference to the builder. + + // Notify the unit test that the rebuild is complete (will be NULL in prod.) + if (!rebuild_complete_task_.is_null()) { + rebuild_complete_task_.Run(); + rebuild_complete_task_.Reset(); + } +} + +void VisitedLinkMaster::WriteToFile(FILE** file, + off_t offset, + void* data, + int32 data_size) { + DCHECK(persist_to_disk_); +#ifndef NDEBUG + posted_asynchronous_operation_ = true; +#endif + PostIOTask(FROM_HERE, + base::Bind(&AsyncWrite, file, offset, + std::string(static_cast<const char*>(data), data_size))); +} + +void VisitedLinkMaster::WriteUsedItemCountToFile() { + DCHECK(persist_to_disk_); + if (!file_) + return; // See comment on the file_ variable for why this might happen. + WriteToFile(file_, kFileHeaderUsedOffset, &used_items_, sizeof(used_items_)); +} + +void VisitedLinkMaster::WriteHashRangeToFile(Hash first_hash, Hash last_hash) { + DCHECK(persist_to_disk_); + + if (!file_) + return; // See comment on the file_ variable for why this might happen. + if (last_hash < first_hash) { + // Handle wraparound at 0. This first write is first_hash->EOF + WriteToFile(file_, first_hash * sizeof(Fingerprint) + kFileHeaderSize, + &hash_table_[first_hash], + (table_length_ - first_hash + 1) * sizeof(Fingerprint)); + + // Now do 0->last_lash. + WriteToFile(file_, kFileHeaderSize, hash_table_, + (last_hash + 1) * sizeof(Fingerprint)); + } else { + // Normal case, just write the range. + WriteToFile(file_, first_hash * sizeof(Fingerprint) + kFileHeaderSize, + &hash_table_[first_hash], + (last_hash - first_hash + 1) * sizeof(Fingerprint)); + } +} + +bool VisitedLinkMaster::ReadFromFile(FILE* file, + off_t offset, + void* data, + size_t data_size) { + DCHECK(persist_to_disk_); +#ifndef NDEBUG + // Since this function is synchronous, we require that no asynchronous + // operations could possibly be pending. + DCHECK(!posted_asynchronous_operation_); +#endif + + if (fseek(file, offset, SEEK_SET) != 0) + return false; + + size_t num_read = fread(data, 1, data_size, file); + return num_read == data_size; +} + +// VisitedLinkTableBuilder ---------------------------------------------------- + +VisitedLinkMaster::TableBuilder::TableBuilder( + VisitedLinkMaster* master, + const uint8 salt[LINK_SALT_LENGTH]) + : master_(master), + success_(true) { + fingerprints_.reserve(4096); + memcpy(salt_, salt, LINK_SALT_LENGTH * sizeof(uint8)); +} + +// TODO(brettw): Do we want to try to cancel the request if this happens? It +// could delay shutdown if there are a lot of URLs. +void VisitedLinkMaster::TableBuilder::DisownMaster() { + master_ = NULL; +} + +void VisitedLinkMaster::TableBuilder::OnURL(const GURL& url) { + if (!url.is_empty()) { + fingerprints_.push_back(VisitedLinkMaster::ComputeURLFingerprint( + url.spec().data(), url.spec().length(), salt_)); + } +} + +void VisitedLinkMaster::TableBuilder::OnComplete(bool success) { + success_ = success; + DLOG_IF(WARNING, !success) << "Unable to rebuild visited links"; + + // Marshal to the main thread to notify the VisitedLinkMaster that the + // rebuild is complete. + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind(&TableBuilder::OnCompleteMainThread, this)); +} + +void VisitedLinkMaster::TableBuilder::OnCompleteMainThread() { + if (master_) + master_->OnTableRebuildComplete(success_, fingerprints_); +} + +} // namespace visitedlink diff --git a/chromium/components/visitedlink/browser/visitedlink_master.h b/chromium/components/visitedlink/browser/visitedlink_master.h new file mode 100644 index 0000000000000000000000000000000000000000..aff4e498a7cc9d4b2380f7b5962e1def4e5a5791 --- /dev/null +++ b/chromium/components/visitedlink/browser/visitedlink_master.h @@ -0,0 +1,445 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_MASTER_H_ +#define COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_MASTER_H_ + +#if defined(OS_WIN) +#include <windows.h> +#endif +#include <set> +#include <vector> + +#include "base/callback.h" +#include "base/callback_forward.h" +#include "base/files/file_path.h" +#include "base/gtest_prod_util.h" +#include "base/memory/shared_memory.h" +#include "base/threading/sequenced_worker_pool.h" +#include "components/visitedlink/common/visitedlink_common.h" + +#if defined(UNIT_TEST) || defined(PERF_TEST) || !defined(NDEBUG) +#include "base/logging.h" +#endif + +class GURL; + +namespace content { +class BrowserContext; +} + +namespace visitedlink { + +class VisitedLinkDelegate; + +// Controls the link coloring database. The master controls all writing to the +// database as well as disk I/O. There should be only one master. +// +// This class will defer writing operations to the file thread. This means that +// class destruction, the file may still be open since operations are pending on +// another thread. +class VisitedLinkMaster : public VisitedLinkCommon { + public: + // Listens to the link coloring database events. The master is given this + // event as a constructor argument and dispatches events using it. + class Listener { + public: + virtual ~Listener() {} + + // Called when link coloring database has been created or replaced. The + // argument is the new table handle. + virtual void NewTable(base::SharedMemory*) = 0; + + // Called when new link has been added. The argument is the fingerprint + // (hash) of the link. + virtual void Add(Fingerprint fingerprint) = 0; + + // Called when link coloring state has been reset. This may occur when + // entire or parts of history were deleted. + virtual void Reset() = 0; + }; + + VisitedLinkMaster(content::BrowserContext* browser_context, + VisitedLinkDelegate* delegate, + bool persist_to_disk); + + // In unit test mode, we allow the caller to optionally specify the database + // filename so that it can be run from a unit test. The directory where this + // file resides must exist in this mode. You can also specify the default + // table size to test table resizing. If this parameter is 0, we will use the + // defaults. + // + // In the unit test mode, we also allow the caller to provide a history + // service pointer (the history service can't be fetched from the browser + // process when we're in unit test mode). This can be NULL to try to access + // the main version, which will probably fail (which can be good for testing + // this failure mode). + // + // When |suppress_rebuild| is set, we'll not attempt to load data from + // history if the file can't be loaded. This should generally be set for + // testing except when you want to test the rebuild process explicitly. + VisitedLinkMaster(Listener* listener, + VisitedLinkDelegate* delegate, + bool persist_to_disk, + bool suppress_rebuild, + const base::FilePath& filename, + int32 default_table_size); + virtual ~VisitedLinkMaster(); + + // Must be called immediately after object creation. Nothing else will work + // until this is called. Returns true on success, false means that this + // object won't work. + bool Init(); + + base::SharedMemory* shared_memory() { return shared_memory_; } + + // Adds a URL to the table. + void AddURL(const GURL& url); + + // Adds a set of URLs to the table. + void AddURLs(const std::vector<GURL>& url); + + // See DeleteURLs. + class URLIterator { + public: + // HasNextURL must return true when this is called. Returns the next URL + // then advances the iterator. Note that the returned reference is only + // valid until the next call of NextURL. + virtual const GURL& NextURL() = 0; + + // Returns true if still has URLs to be iterated. + virtual bool HasNextURL() const = 0; + + protected: + virtual ~URLIterator() {} + }; + + // Deletes the specified URLs from |rows| from the table. + void DeleteURLs(URLIterator* iterator); + + // Clears the visited links table by deleting the file from disk. Used as + // part of history clearing. + void DeleteAllURLs(); + + // Returns the Delegate of this Master. + VisitedLinkDelegate* GetDelegate(); + +#if defined(UNIT_TEST) || !defined(NDEBUG) || defined(PERF_TEST) + // This is a debugging function that can be called to double-check internal + // data structures. It will assert if the check fails. + void DebugValidate(); + + // Sets a task to execute when the next rebuild from history is complete. + // This is used by unit tests to wait for the rebuild to complete before + // they continue. The pointer will be owned by this object after the call. + void set_rebuild_complete_task(const base::Closure& task) { + DCHECK(rebuild_complete_task_.is_null()); + rebuild_complete_task_ = task; + } + + // returns the number of items in the table for testing verification + int32 GetUsedCount() const { + return used_items_; + } + + // Returns the listener. + VisitedLinkMaster::Listener* GetListener() const { + return listener_.get(); + } + + // Call to cause the entire database file to be re-written from scratch + // to disk. Used by the performance tester. + void RewriteFile() { + WriteFullTable(); + } +#endif + + private: + FRIEND_TEST_ALL_PREFIXES(VisitedLinkTest, Delete); + FRIEND_TEST_ALL_PREFIXES(VisitedLinkTest, BigDelete); + FRIEND_TEST_ALL_PREFIXES(VisitedLinkTest, BigImport); + + // Object to rebuild the table on the history thread (see the .cc file). + class TableBuilder; + + // Byte offsets of values in the header. + static const int32 kFileHeaderSignatureOffset; + static const int32 kFileHeaderVersionOffset; + static const int32 kFileHeaderLengthOffset; + static const int32 kFileHeaderUsedOffset; + static const int32 kFileHeaderSaltOffset; + + // The signature at the beginning of a file. + static const int32 kFileSignature; + + // version of the file format this module currently uses + static const int32 kFileCurrentVersion; + + // Bytes in the file header, including the salt. + static const size_t kFileHeaderSize; + + // When creating a fresh new table, we use this many entries. + static const unsigned kDefaultTableSize; + + // When the user is deleting a boatload of URLs, we don't really want to do + // individual writes for each of them. When the count exceeds this threshold, + // we will write the whole table to disk at once instead of individual items. + static const size_t kBigDeleteThreshold; + + // Backend for the constructors initializing the members. + void InitMembers(); + + // If a rebuild is in progress, we save the URL in the temporary list. + // Otherwise, we add this to the table. Returns the index of the + // inserted fingerprint or null_hash_ on failure. + Hash TryToAddURL(const GURL& url); + + // File I/O functions + // ------------------ + // These functions are only called if |persist_to_disk_| is true. + + // Posts the given task to the blocking worker pool with our options. + void PostIOTask(const tracked_objects::Location& from_here, + const base::Closure& task); + + // Writes the entire table to disk. It will leave the table file open and + // the handle to it will be stored in file_. + void WriteFullTable(); + + // Try to load the table from the database file. If the file doesn't exist or + // is corrupt, this will return failure. + bool InitFromFile(); + + // Reads the header of the link coloring database from disk. Assumes the + // file pointer is at the beginning of the file and that there are no pending + // asynchronous I/O operations. + // + // Returns true on success and places the size of the table in num_entries + // and the number of nonzero fingerprints in used_count. This will fail if + // the version of the file is not the current version of the database. + bool ReadFileHeader(FILE* hfile, int32* num_entries, int32* used_count, + uint8 salt[LINK_SALT_LENGTH]); + + // Fills *filename with the name of the link database filename + bool GetDatabaseFileName(base::FilePath* filename); + + // Wrapper around Window's WriteFile using asynchronous I/O. This will proxy + // the write to a background thread. + void WriteToFile(FILE** hfile, off_t offset, void* data, int32 data_size); + + // Helper function to schedule and asynchronous write of the used count to + // disk (this is a common operation). + void WriteUsedItemCountToFile(); + + // Helper function to schedule an asynchronous write of the given range of + // hash functions to disk. The range is inclusive on both ends. The range can + // wrap around at 0 and this function will handle it. + void WriteHashRangeToFile(Hash first_hash, Hash last_hash); + + // Synchronous read from the file. Assumes there are no pending asynchronous + // I/O functions. Returns true if the entire buffer was successfully filled. + bool ReadFromFile(FILE* hfile, off_t offset, void* data, size_t data_size); + + // General table handling + // ---------------------- + + // Called to add a fingerprint to the table. If |send_notifications| is true + // and the item is added successfully, Listener::Add will be invoked. + // Returns the index of the inserted fingerprint or null_hash_ if there was a + // duplicate and this item was skippped. + Hash AddFingerprint(Fingerprint fingerprint, bool send_notifications); + + // Deletes all fingerprints from the given vector from the current hash table + // and syncs it to disk if there are changes. This does not update the + // deleted_since_rebuild_ list, the caller must update this itself if there + // is an update pending. + void DeleteFingerprintsFromCurrentTable( + const std::set<Fingerprint>& fingerprints); + + // Removes the indicated fingerprint from the table. If the update_file flag + // is set, the changes will also be written to disk. Returns true if the + // fingerprint was deleted, false if it was not in the table to delete. + bool DeleteFingerprint(Fingerprint fingerprint, bool update_file); + + // Creates a new empty table, call if InitFromFile() fails. Normally, when + // |suppress_rebuild| is false, the table will be rebuilt from history, + // keeping us in sync. When |suppress_rebuild| is true, the new table will be + // empty and we will not consult history. This is used when clearing the + // database and for unit tests. + bool InitFromScratch(bool suppress_rebuild); + + // Allocates the Fingerprint structure and length. When init_to_empty is set, + // the table will be filled with 0s and used_items_ will be set to 0 as well. + // If the flag is not set, these things are untouched and it is the + // responsibility of the caller to fill them (like when we are reading from + // a file). + bool CreateURLTable(int32 num_entries, bool init_to_empty); + + // A wrapper for CreateURLTable, this will allocate a new table, initialized + // to empty. The caller is responsible for saving the shared memory pointer + // and handles before this call (they will be replaced with new ones) and + // releasing them later. This is designed for callers that make a new table + // and then copy values from the old table to the new one, then release the + // old table. + // + // Returns true on success. On failure, the old table will be restored. The + // caller should not attemp to release the pointer/handle in this case. + bool BeginReplaceURLTable(int32 num_entries); + + // unallocates the Fingerprint table + void FreeURLTable(); + + // For growing the table. ResizeTableIfNecessary will check to see if the + // table should be resized and calls ResizeTable if needed. Returns true if + // we decided to resize the table. + bool ResizeTableIfNecessary(); + + // Resizes the table (growing or shrinking) as necessary to accomodate the + // current count. + void ResizeTable(int32 new_size); + + // Returns the desired table size for |item_count| URLs. + uint32 NewTableSizeForCount(int32 item_count) const; + + // Computes the table load as fraction. For example, if 1/4 of the entries are + // full, this value will be 0.25 + float ComputeTableLoad() const { + return static_cast<float>(used_items_) / static_cast<float>(table_length_); + } + + // Initializes a rebuild of the visited link database based on the browser + // history. This will set table_builder_ while working, and there should not + // already be a rebuild in place when called. See the definition for more + // details on how this works. + // + // Returns true on success. Failure means we're not attempting to rebuild + // the database because something failed. + bool RebuildTableFromDelegate(); + + // Callback that the table rebuilder uses when the rebuild is complete. + // |success| is true if the fingerprint generation succeeded, in which case + // |fingerprints| will contain the computed fingerprints. On failure, there + // will be no fingerprints. + void OnTableRebuildComplete(bool success, + const std::vector<Fingerprint>& fingerprints); + + // Increases or decreases the given hash value by one, wrapping around as + // necessary. Used for probing. + inline Hash IncrementHash(Hash hash) { + if (hash >= table_length_ - 1) + return 0; // Wrap around. + return hash + 1; + } + inline Hash DecrementHash(Hash hash) { + if (hash <= 0) + return table_length_ - 1; // Wrap around. + return hash - 1; + } + +#ifndef NDEBUG + // Indicates whether any asynchronous operation has ever been completed. + // We do some synchronous reads that require that no asynchronous operations + // are pending, yet we don't track whether they have been completed. This + // flag is a sanity check that these reads only happen before any + // asynchronous writes have been fired. + bool posted_asynchronous_operation_; +#endif + + // Reference to the browser context that this object belongs to + // (it knows the path to where the data is stored) + content::BrowserContext* browser_context_; + + // Client owns the delegate and is responsible for it being valid through + // the life time this VisitedLinkMaster. + VisitedLinkDelegate* delegate_; + + // VisitedLinkEventListener to handle incoming events. + scoped_ptr<Listener> listener_; + + // Lazily initialized sequence token for posting file tasks. + base::SequencedWorkerPool::SequenceToken sequence_token_; + + // When non-NULL, indicates we are in database rebuild mode and points to + // the class collecting fingerprint information from the history system. + // The pointer is owned by this class, but it must remain valid while the + // history query is running. We must only delete it when the query is done. + scoped_refptr<TableBuilder> table_builder_; + + // Indicates URLs added and deleted since we started rebuilding the table. + std::set<Fingerprint> added_since_rebuild_; + std::set<Fingerprint> deleted_since_rebuild_; + + // TODO(brettw) Support deletion, we need to track whether anything was + // deleted during the rebuild here. Then we should delete any of these + // entries from the complete table later. + // std::vector<Fingerprint> removed_since_rebuild_; + + // The currently open file with the table in it. This may be NULL if we're + // rebuilding and haven't written a new version yet or if |persist_to_disk_| + // is false. Writing to the file may be safely ignored in this case. Also + // |file_| may be non-NULL but point to a NULL pointer. That would mean that + // opening of the file is already scheduled in a background thread and any + // writing to the file can also be scheduled to the background thread as it's + // guaranteed to be executed after the opening. + // The class owns both the |file_| pointer and the pointer pointed + // by |*file_|. + FILE** file_; + + // If true, will try to persist the hash table to disk. Will rebuild from + // VisitedLinkDelegate::RebuildTable if there are disk corruptions. + bool persist_to_disk_; + + // Shared memory consists of a SharedHeader followed by the table. + base::SharedMemory *shared_memory_; + + // When we generate new tables, we increment the serial number of the + // shared memory object. + int32 shared_memory_serial_; + + // Number of non-empty items in the table, used to compute fullness. + int32 used_items_; + + // Testing values ----------------------------------------------------------- + // + // The following fields exist for testing purposes. They are not used in + // release builds. It'd be nice to eliminate them in release builds, but we + // don't want to change the signature of the object between the unit test and + // regular builds. Instead, we just have "default" values that these take + // in release builds that give "regular" behavior. + + // Overridden database file name for testing + base::FilePath database_name_override_; + + // When nonzero, overrides the table size for new databases for testing + int32 table_size_override_; + + // When set, indicates the task that should be run after the next rebuild from + // history is complete. + base::Closure rebuild_complete_task_; + + // Set to prevent us from attempting to rebuild the database from global + // history if we have an error opening the file. This is used for testing, + // will be false in production. + bool suppress_rebuild_; + + DISALLOW_COPY_AND_ASSIGN(VisitedLinkMaster); +}; + +// NOTE: These methods are defined inline here, so we can share the compilation +// of visitedlink_master.cc between the browser and the unit/perf tests. + +#if defined(UNIT_TEST) || defined(PERF_TEST) || !defined(NDEBUG) +inline void VisitedLinkMaster::DebugValidate() { + int32 used_count = 0; + for (int32 i = 0; i < table_length_; i++) { + if (hash_table_[i]) + used_count++; + } + DCHECK_EQ(used_count, used_items_); +} +#endif + +} // namespace visitedlink + +#endif // COMPONENTS_VISITEDLINK_BROWSER_VISITEDLINK_MASTER_H_ diff --git a/chromium/components/visitedlink/common/BUILD.gn b/chromium/components/visitedlink/common/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..61d3ef221035b4ed57c14102f63ea5071996e094 --- /dev/null +++ b/chromium/components/visitedlink/common/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright 2014 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +static_library("common") { + output_name = "visitedlink_common" + sources = [ + "visitedlink_common.cc", + "visitedlink_common.h", + "visitedlink_message_generator.cc", + "visitedlink_message_generator.h", + "visitedlink_messages.h", + ] + + deps = [ + "//base", + "//content/public/common", + "//ipc", + "//url" + ] +} diff --git a/chromium/components/visitedlink/common/DEPS b/chromium/components/visitedlink/common/DEPS new file mode 100644 index 0000000000000000000000000000000000000000..d5923ee96cb072bf837a7a4e685bea65e8ea0ea0 --- /dev/null +++ b/chromium/components/visitedlink/common/DEPS @@ -0,0 +1,3 @@ +include_rules = [ + "+content/public/common", +] diff --git a/chromium/components/visitedlink/common/OWNERS b/chromium/components/visitedlink/common/OWNERS new file mode 100644 index 0000000000000000000000000000000000000000..63607cc97b63f90774d7eb9cfd7089a5868644b1 --- /dev/null +++ b/chromium/components/visitedlink/common/OWNERS @@ -0,0 +1,12 @@ +# Changes to IPC messages require a security review to avoid introducing +# new sandbox escapes. +per-file *_messages*.h=set noparent +per-file *_messages*.h=cevans@chromium.org +per-file *_messages*.h=dcheng@chromium.org +per-file *_messages*.h=inferno@chromium.org +per-file *_messages*.h=jln@chromium.org +per-file *_messages*.h=jschuh@chromium.org +per-file *_messages*.h=kenrb@chromium.org +per-file *_messages*.h=nasko@chromium.org +per-file *_messages*.h=palmer@chromium.org +per-file *_messages*.h=tsepez@chromium.org diff --git a/chromium/components/visitedlink/common/visitedlink_common.cc b/chromium/components/visitedlink/common/visitedlink_common.cc new file mode 100644 index 0000000000000000000000000000000000000000..7576231bc0556de3757d94cc7cf8bafc9e29f8a4 --- /dev/null +++ b/chromium/components/visitedlink/common/visitedlink_common.cc @@ -0,0 +1,102 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/visitedlink/common/visitedlink_common.h" + +#include <string.h> // for memset() + +#include "base/logging.h" +#include "base/md5.h" +#include "url/gurl.h" + +namespace visitedlink { + +const VisitedLinkCommon::Fingerprint VisitedLinkCommon::null_fingerprint_ = 0; +const VisitedLinkCommon::Hash VisitedLinkCommon::null_hash_ = -1; + +VisitedLinkCommon::VisitedLinkCommon() + : hash_table_(NULL), + table_length_(0) { + memset(salt_, 0, sizeof(salt_)); +} + +VisitedLinkCommon::~VisitedLinkCommon() { +} + +// FIXME: this uses linear probing, it should be replaced with quadratic +// probing or something better. See VisitedLinkMaster::AddFingerprint +bool VisitedLinkCommon::IsVisited(const char* canonical_url, + size_t url_len) const { + if (url_len == 0) + return false; + if (!hash_table_ || table_length_ == 0) + return false; + return IsVisited(ComputeURLFingerprint(canonical_url, url_len)); +} + +bool VisitedLinkCommon::IsVisited(const GURL& url) const { + return IsVisited(url.spec().data(), url.spec().size()); +} + +bool VisitedLinkCommon::IsVisited(Fingerprint fingerprint) const { + // Go through the table until we find the item or an empty spot (meaning it + // wasn't found). This loop will terminate as long as the table isn't full, + // which should be enforced by AddFingerprint. + Hash first_hash = HashFingerprint(fingerprint); + Hash cur_hash = first_hash; + while (true) { + Fingerprint cur_fingerprint = FingerprintAt(cur_hash); + if (cur_fingerprint == null_fingerprint_) + return false; // End of probe sequence found. + if (cur_fingerprint == fingerprint) + return true; // Found a match. + + // This spot was taken, but not by the item we're looking for, search in + // the next position. + cur_hash++; + if (cur_hash == table_length_) + cur_hash = 0; + if (cur_hash == first_hash) { + // Wrapped around and didn't find an empty space, this means we're in an + // infinite loop because AddFingerprint didn't do its job resizing. + NOTREACHED(); + return false; + } + } +} + +// Uses the top 64 bits of the MD5 sum of the canonical URL as the fingerprint, +// this is as random as any other subset of the MD5SUM. +// +// FIXME: this uses the MD5SUM of the 16-bit character version. For systems +// where wchar_t is not 16 bits (Linux uses 32 bits, I think), this will not be +// compatable. We should define explicitly what should happen here across +// platforms, and convert if necessary (probably to UTF-16). + +// static +VisitedLinkCommon::Fingerprint VisitedLinkCommon::ComputeURLFingerprint( + const char* canonical_url, + size_t url_len, + const uint8 salt[LINK_SALT_LENGTH]) { + DCHECK(url_len > 0) << "Canonical URLs should not be empty"; + + base::MD5Context ctx; + base::MD5Init(&ctx); + base::MD5Update(&ctx, base::StringPiece(reinterpret_cast<const char*>(salt), + LINK_SALT_LENGTH)); + base::MD5Update(&ctx, base::StringPiece(canonical_url, url_len)); + + base::MD5Digest digest; + base::MD5Final(&digest, &ctx); + + // This is the same as "return *(Fingerprint*)&digest.a;" but if we do that + // direct cast the alignment could be wrong, and we can't access a 64-bit int + // on arbitrary alignment on some processors. This reinterpret_casts it + // down to a char array of the same size as fingerprint, and then does the + // bit cast, which amounts to a memcpy. This does not handle endian issues. + return bit_cast<Fingerprint, uint8[8]>( + *reinterpret_cast<uint8(*)[8]>(&digest.a)); +} + +} // namespace visitedlink diff --git a/chromium/components/visitedlink/common/visitedlink_common.h b/chromium/components/visitedlink/common/visitedlink_common.h new file mode 100644 index 0000000000000000000000000000000000000000..37afe1d157581a010214801f361142ca12b652d7 --- /dev/null +++ b/chromium/components/visitedlink/common/visitedlink_common.h @@ -0,0 +1,138 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VISITEDLINK_COMMON_VISITEDLINK_COMMON_H_ +#define COMPONENTS_VISITEDLINK_COMMON_VISITEDLINK_COMMON_H_ + +#include <vector> + +#include "base/basictypes.h" + +class GURL; + +namespace visitedlink { + +// number of bytes in the salt +#define LINK_SALT_LENGTH 8 + +// A multiprocess-safe database of the visited links for the browser. There +// should be exactly one process that has write access (implemented by +// VisitedLinkMaster), while all other processes should be read-only +// (implemented by VisitedLinkSlave). These other processes add links by calling +// the writer process to add them for it. The writer may also notify the readers +// to replace their table when the table is resized. +// +// IPC is not implemented in these classes. This is done through callback +// functions supplied by the creator of these objects to allow more flexibility, +// especially for testing. +// +// This class defines the common base for these others. We implement accessors +// for looking things up in the hash table, and for computing hash values and +// fingerprints. Both the master and the slave inherit from this, and add their +// own code to set up and change these values as their design requires. The +// slave pretty much just sets up the shared memory and saves the pointer. The +// master does a lot of work to manage the table, reading and writing it to and +// from disk, and resizing it when it gets too full. +// +// To ask whether a page is in history, we compute a 64-bit fingerprint of the +// URL. This URL is hashed and we see if it is in the URL hashtable. If it is, +// we consider it visited. Otherwise, it is unvisited. Note that it is possible +// to get collisions, which is the penalty for not storing all URL strings in +// memory (which could get to be more than we want to have in memory). We use +// a salt value for the links on one computer so that an attacker can not +// manually create a link that causes a collision. +class VisitedLinkCommon { + public: + // A number that identifies the URL. + typedef uint64 Fingerprint; + typedef std::vector<Fingerprint> Fingerprints; + + // A hash value of a fingerprint + typedef int32 Hash; + + // A fingerprint or hash value that does not exist + static const Fingerprint null_fingerprint_; + static const Hash null_hash_; + + VisitedLinkCommon(); + virtual ~VisitedLinkCommon(); + + // Returns the fingerprint for the given URL. + Fingerprint ComputeURLFingerprint(const char* canonical_url, + size_t url_len) const { + return ComputeURLFingerprint(canonical_url, url_len, salt_); + } + + // Looks up the given key in the table. The fingerprint for the URL is + // computed if you call one with the string argument. Returns true if found. + // Does not modify the hastable. + bool IsVisited(const char* canonical_url, size_t url_len) const; + bool IsVisited(const GURL& url) const; + bool IsVisited(Fingerprint fingerprint) const; + +#ifdef UNIT_TEST + // Returns statistics about DB usage + void GetUsageStatistics(int32* table_size, + VisitedLinkCommon::Fingerprint** fingerprints) { + *table_size = table_length_; + *fingerprints = hash_table_; + } +#endif + + protected: + // This structure is at the beginning of the shared memory so that the slaves + // can get stats on the table + struct SharedHeader { + // see goes into table_length_ + uint32 length; + + // goes into salt_ + uint8 salt[LINK_SALT_LENGTH]; + }; + + // Returns the fingerprint at the given index into the URL table. This + // function should be called instead of accessing the table directly to + // contain endian issues. + Fingerprint FingerprintAt(int32 table_offset) const { + if (!hash_table_) + return null_fingerprint_; + return hash_table_[table_offset]; + } + + // Computes the fingerprint of the given canonical URL. It is static so the + // same algorithm can be re-used by the table rebuilder, so you will have to + // pass the salt as a parameter. See the non-static version above if you + // want to use the current class' salt. + static Fingerprint ComputeURLFingerprint(const char* canonical_url, + size_t url_len, + const uint8 salt[LINK_SALT_LENGTH]); + + // Computes the hash value of the given fingerprint, this is used as a lookup + // into the hashtable. + static Hash HashFingerprint(Fingerprint fingerprint, int32 table_length) { + if (table_length == 0) + return null_hash_; + return static_cast<Hash>(fingerprint % table_length); + } + // Uses the current hashtable. + Hash HashFingerprint(Fingerprint fingerprint) const { + return HashFingerprint(fingerprint, table_length_); + } + + // pointer to the first item + VisitedLinkCommon::Fingerprint* hash_table_; + + // the number of items in the hash table + int32 table_length_; + + // salt used for each URL when computing the fingerprint + uint8 salt_[LINK_SALT_LENGTH]; + + private: + DISALLOW_COPY_AND_ASSIGN(VisitedLinkCommon); +}; + +} // namespace visitedlink + +#endif // COMPONENTS_VISITEDLINK_COMMON_VISITEDLINK_COMMON_H_ diff --git a/chromium/components/visitedlink/common/visitedlink_message_generator.cc b/chromium/components/visitedlink/common/visitedlink_message_generator.cc new file mode 100644 index 0000000000000000000000000000000000000000..29d31916e7f30435ff4f48e63e417f2899de9420 --- /dev/null +++ b/chromium/components/visitedlink/common/visitedlink_message_generator.cc @@ -0,0 +1,34 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Get basic type definitions. +#define IPC_MESSAGE_IMPL +#include "components/visitedlink/common/visitedlink_message_generator.h" + +// Generate constructors. +#include "ipc/struct_constructor_macros.h" +#include "components/visitedlink/common/visitedlink_message_generator.h" + +// Generate destructors. +#include "ipc/struct_destructor_macros.h" +#include "components/visitedlink/common/visitedlink_message_generator.h" + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC { +#include "components/visitedlink/common/visitedlink_message_generator.h" +} // namespace IPC + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC { +#include "components/visitedlink/common/visitedlink_message_generator.h" +} // namespace IPC + +// Generate param traits log methods. +#include "ipc/param_traits_log_macros.h" +namespace IPC { +#include "components/visitedlink/common/visitedlink_message_generator.h" +} // namespace IPC + diff --git a/chromium/components/visitedlink/common/visitedlink_message_generator.h b/chromium/components/visitedlink/common/visitedlink_message_generator.h new file mode 100644 index 0000000000000000000000000000000000000000..e4a496bafb35d288bc26a64d91548826aaa3fe19 --- /dev/null +++ b/chromium/components/visitedlink/common/visitedlink_message_generator.h @@ -0,0 +1,7 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Multiply-included file, no traditional include guard. + +#include "components/visitedlink/common/visitedlink_messages.h" diff --git a/chromium/components/visitedlink/common/visitedlink_messages.h b/chromium/components/visitedlink/common/visitedlink_messages.h new file mode 100644 index 0000000000000000000000000000000000000000..c0877765f128ba03a73bd2a7bd65e6572dc53b82 --- /dev/null +++ b/chromium/components/visitedlink/common/visitedlink_messages.h @@ -0,0 +1,29 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Multiply-included file, no traditional include guard. +#include <vector> + +#include "base/basictypes.h" +#include "base/memory/shared_memory.h" +#include "content/public/common/common_param_traits_macros.h" +#include "ipc/ipc_message_macros.h" + +#define IPC_MESSAGE_START VisitedLinkMsgStart + +// History system notification that the visited link database has been +// replaced. It has one SharedMemoryHandle argument consisting of the table +// handle. This handle is valid in the context of the renderer +IPC_MESSAGE_CONTROL1(ChromeViewMsg_VisitedLink_NewTable, + base::SharedMemoryHandle) + +// History system notification that a link has been added and the link +// coloring state for the given hash must be re-calculated. +IPC_MESSAGE_CONTROL1(ChromeViewMsg_VisitedLink_Add, std::vector<uint64>) + +// History system notification that one or more history items have been +// deleted, which at this point means that all link coloring state must be +// re-calculated. +IPC_MESSAGE_CONTROL0(ChromeViewMsg_VisitedLink_Reset) + diff --git a/chromium/components/visitedlink/renderer/BUILD.gn b/chromium/components/visitedlink/renderer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..33618cccb69ac561d186c0fdf17b3eeadc75789f --- /dev/null +++ b/chromium/components/visitedlink/renderer/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright 2014 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +if (!is_ios) { + static_library("renderer") { + output_name = "visitedlink_renderer" + sources = [ + "visitedlink_slave.cc", + "visitedlink_slave.h", + ] + + deps = [ + "//base", + "//content/public/common", + "//content/public/renderer", + "//third_party/WebKit/public:blink", + ] + } +} diff --git a/chromium/components/visitedlink/renderer/DEPS b/chromium/components/visitedlink/renderer/DEPS new file mode 100644 index 0000000000000000000000000000000000000000..ad0391cf78ba88aa4ab900aaa652f217aa092a9f --- /dev/null +++ b/chromium/components/visitedlink/renderer/DEPS @@ -0,0 +1,5 @@ +include_rules = [ + "+content/public/renderer", + "+third_party/WebKit/public/platform", + "+third_party/WebKit/public/web", +] diff --git a/chromium/components/visitedlink/renderer/visitedlink_slave.cc b/chromium/components/visitedlink/renderer/visitedlink_slave.cc new file mode 100644 index 0000000000000000000000000000000000000000..b1e62fdb4806c7be93c07f665f1e4375406aeb14 --- /dev/null +++ b/chromium/components/visitedlink/renderer/visitedlink_slave.cc @@ -0,0 +1,92 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/visitedlink/renderer/visitedlink_slave.h" + +#include "base/logging.h" +#include "base/memory/shared_memory.h" +#include "components/visitedlink/common/visitedlink_messages.h" +#include "third_party/WebKit/public/web/WebView.h" + +using blink::WebView; + +namespace visitedlink { + +VisitedLinkSlave::VisitedLinkSlave() : shared_memory_(NULL) {} + +VisitedLinkSlave::~VisitedLinkSlave() { + FreeTable(); +} + +bool VisitedLinkSlave::OnControlMessageReceived(const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(VisitedLinkSlave, message) + IPC_MESSAGE_HANDLER(ChromeViewMsg_VisitedLink_NewTable, + OnUpdateVisitedLinks) + IPC_MESSAGE_HANDLER(ChromeViewMsg_VisitedLink_Add, OnAddVisitedLinks) + IPC_MESSAGE_HANDLER(ChromeViewMsg_VisitedLink_Reset, OnResetVisitedLinks) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +// This function's job is to initialize the table with the given +// shared memory handle. This memory is mapped into the process. +void VisitedLinkSlave::OnUpdateVisitedLinks(base::SharedMemoryHandle table) { + DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle"; + // since this function may be called again to change the table, we may need + // to free old objects + FreeTable(); + DCHECK(shared_memory_ == NULL && hash_table_ == NULL); + + // create the shared memory object + shared_memory_ = new base::SharedMemory(table, true); + if (!shared_memory_) + return; + + // map the header into our process so we can see how long the rest is, + // and set the salt + if (!shared_memory_->Map(sizeof(SharedHeader))) + return; + SharedHeader* header = + static_cast<SharedHeader*>(shared_memory_->memory()); + DCHECK(header); + int32 table_len = header->length; + memcpy(salt_, header->salt, sizeof(salt_)); + shared_memory_->Unmap(); + + // now do the whole table because we know the length + if (!shared_memory_->Map(sizeof(SharedHeader) + + table_len * sizeof(Fingerprint))) { + shared_memory_->Close(); + return; + } + + // commit the data + DCHECK(shared_memory_->memory()); + hash_table_ = reinterpret_cast<Fingerprint*>( + static_cast<char*>(shared_memory_->memory()) + sizeof(SharedHeader)); + table_length_ = table_len; +} + +void VisitedLinkSlave::OnAddVisitedLinks( + const VisitedLinkSlave::Fingerprints& fingerprints) { + for (size_t i = 0; i < fingerprints.size(); ++i) + WebView::updateVisitedLinkState(fingerprints[i]); +} + +void VisitedLinkSlave::OnResetVisitedLinks() { + WebView::resetVisitedLinkState(); +} + +void VisitedLinkSlave::FreeTable() { + if (shared_memory_) { + delete shared_memory_; + shared_memory_ = NULL; + } + hash_table_ = NULL; + table_length_ = 0; +} + +} // namespace visitedlink diff --git a/chromium/components/visitedlink/renderer/visitedlink_slave.h b/chromium/components/visitedlink/renderer/visitedlink_slave.h new file mode 100644 index 0000000000000000000000000000000000000000..425c03e1be7acfe58db3157574ac95d8a421a75a --- /dev/null +++ b/chromium/components/visitedlink/renderer/visitedlink_slave.h @@ -0,0 +1,42 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VISITEDLINK_RENDERER_VISITEDLINK_SLAVE_H_ +#define COMPONENTS_VISITEDLINK_RENDERER_VISITEDLINK_SLAVE_H_ + +#include "base/compiler_specific.h" +#include "base/memory/shared_memory.h" +#include "components/visitedlink/common/visitedlink_common.h" +#include "content/public/renderer/render_process_observer.h" + +namespace visitedlink { + +// Reads the link coloring database provided by the master. There can be any +// number of slaves reading the same database. +class VisitedLinkSlave : public VisitedLinkCommon, + public content::RenderProcessObserver { + public: + VisitedLinkSlave(); + virtual ~VisitedLinkSlave(); + + // RenderProcessObserver implementation. + virtual bool OnControlMessageReceived(const IPC::Message& message) OVERRIDE; + + // Message handlers. + void OnUpdateVisitedLinks(base::SharedMemoryHandle table); + void OnAddVisitedLinks(const VisitedLinkSlave::Fingerprints& fingerprints); + void OnResetVisitedLinks(); + + private: + void FreeTable(); + + // shared memory consists of a SharedHeader followed by the table + base::SharedMemory* shared_memory_; + + DISALLOW_COPY_AND_ASSIGN(VisitedLinkSlave); +}; + +} // namespace visitedlink + +#endif // COMPONENTS_VISITEDLINK_RENDERER_VISITEDLINK_SLAVE_H_ diff --git a/chromium/third_party/cacheinvalidation/OWNERS b/chromium/third_party/cacheinvalidation/OWNERS deleted file mode 100644 index de982c8b1e8595ad241f048b059f9d12c453eb13..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/OWNERS +++ /dev/null @@ -1,9 +0,0 @@ -# Owners of third_party/cacheinvalidation -# -# These are current and former members of the Sync team who have the most -# knowledge and experience with the cacheinvalidation library. - -dcheng@chromium.org -rlarocque@chromium.org -tim@chromium.org -zea@chromium.org diff --git a/chromium/third_party/cacheinvalidation/README.chromium b/chromium/third_party/cacheinvalidation/README.chromium deleted file mode 100644 index ce5bb62e9648cd4f78e39d220a1bee622b96891a..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/README.chromium +++ /dev/null @@ -1,24 +0,0 @@ -Name: Google Cache Invalidation API -Short Name: google-cache-invalidation-api -URL: http://code.google.com/p/google-cache-invalidation-api/ -Version: r330 -License: Apache 2.0 -License File: src/google/cacheinvalidation/COPYING -Security Critical: no - -Description: -This is the API to talk to the Google Cache Invalidation service. - -Local Modifications: -None. - -Note: If you are rolling forward the Cache Invalidation API version, and want to -check if any changes need to be made to cacheinvalidation.gyp, do the following: - - cd src/third_party/cacheinvalidation/src - git remote update - git diff --diff-filter=ACDR --name-only origin/master | grep -v ^java/ - -This should give you a list of relevant files that were added, copied, renamed -or deleted upstream. You will likely need to make appropriate changes to -cacheinvalidation.gyp to keep the build green. diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/callback.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/callback.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/compiler-specific.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/compiler-specific.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/callback.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/callback.h deleted file mode 100644 index da92dfbfabcae68f6015f7bc076ffa78baf02494..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/callback.h +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_CALLBACK_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_CALLBACK_H_ - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" - -#define INVALIDATION_CALLBACK1_TYPE(Arg1) ::base::Callback<void(Arg1)> - -// Below are a collection of types and functions that adapt base::Callback's -// pass-by-value semantics to the pointer-based callback system that -// cacheinvalidation needs. - -namespace invalidation { - -typedef ::base::Closure Closure; - -template <class T> -bool IsCallbackRepeatable(const T* callback) { - // The default cacheinvalidation Callbacks may be self-deleting. We don't - // support this behave, so we already return true to indicate that the - // cacheinvalidation implementation should delete our Callbacks. - return true; -} - -namespace internal { - -// Identity<T>::type is a typedef of T. Useful for preventing the -// compiler from inferring the type of an argument in templates. -template <typename T> -struct Identity { - typedef T type; -}; - -} // namespace internal - -// The cacheinvalidation callback system expects to take the callback by -// pointer and handle the ownership semantics itself. Adapting the -// Chromium Callback system requires returning a dynamically allocated -// copy of the result of Bind(). - -inline Closure* NewPermanentCallback(void (*fn)()) { - return new ::base::Closure(::base::Bind(fn)); -} - -template <class T1, class T2> -Closure* NewPermanentCallback( - T1* object, void (T2::*method)()) { - return new ::base::Closure(::base::Bind(method, base::Unretained(object))); -} - -template <class T1, class T2, typename Arg1> -::base::Callback<void(Arg1)>* NewPermanentCallback( - T1* object, void (T2::*method)(Arg1)) { - return new ::base::Callback<void(Arg1)>( - ::base::Bind(method, base::Unretained(object))); -} - -template <class T1, class T2, typename Arg1> -Closure* NewPermanentCallback( - T1* object, - void (T2::*method)(Arg1), - typename internal::Identity<Arg1>::type arg1) { - return new ::base::Closure(::base::Bind(method, base::Unretained(object), - arg1)); -} - -template <typename Arg1, typename Arg2> -Closure* NewPermanentCallback( - void (*fn)(Arg1, Arg2), - typename internal::Identity<Arg1>::type arg1, - typename internal::Identity<Arg2>::type arg2) { - return new ::base::Closure(::base::Bind(fn, arg1, arg2)); -} - -template <class T1, class T2, typename Arg1, typename Arg2> -Closure* NewPermanentCallback( - T1* object, - void (T2::*method)(Arg1, Arg2), - typename internal::Identity<Arg1>::type arg1, - typename internal::Identity<Arg2>::type arg2) { - return new ::base::Closure(::base::Bind(method, base::Unretained(object), - arg1, arg2)); -} - -template <class T1, class T2, typename Arg1, typename Arg2> -::base::Callback<void(Arg2)>* NewPermanentCallback( - T1* object, - void (T2::*method)(Arg1, Arg2), - typename internal::Identity<Arg1>::type arg1) { - return new ::base::Callback<void(Arg2)>( - ::base::Bind(method, base::Unretained(object), arg1)); -} - -template <class T1, class T2, typename Arg1, typename Arg2, typename Arg3> -Closure* NewPermanentCallback( - T1* object, - void (T2::*method)(Arg1, Arg2, Arg3), - typename internal::Identity<Arg1>::type arg1, - typename internal::Identity<Arg2>::type arg2, - typename internal::Identity<Arg3>::type arg3) { - return new ::base::Closure(::base::Bind(method, base::Unretained(object), - arg1, arg2, arg3)); -} - -template <class T1, class T2, typename Arg1, typename Arg2, typename Arg3, - typename Arg4> -Closure* NewPermanentCallback( - T1* object, - void (T2::*method)(Arg1, Arg2, Arg3, Arg4), - typename internal::Identity<Arg1>::type arg1, - typename internal::Identity<Arg2>::type arg2, - typename internal::Identity<Arg3>::type arg3, - typename internal::Identity<Arg4>::type arg4) { - return new ::base::Closure(::base::Bind(method, base::Unretained(object), - arg1, arg2, arg3, arg4)); -} - -// Creates a Closure that runs |callback| on |arg|. The returned Closure owns -// |callback|. -template <typename ArgType> -Closure* NewPermanentCallback( - INVALIDATION_CALLBACK1_TYPE(ArgType)* callback, - typename internal::Identity<ArgType>::type arg) { - return new ::base::Closure(::base::Bind( - &::base::Callback<void(ArgType)>::Run, base::Owned(callback), arg)); -} - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_CALLBACK_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/gmock.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/gmock.h deleted file mode 100644 index f85846f20b906ea69ca0fa7a5ef51833a914456b..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/gmock.h +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_GMOCK_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_GMOCK_H_ - -#include "testing/gmock/include/gmock/gmock.h" - -namespace testing { -namespace internal { - -// WhenDeserializedAs and EqualsProto are utilities that aren't part of gmock. - -// Implements WhenDeserializedAs<Proto>(proto_matcher). -template <class Proto> -class WhenDeserializedAsMatcher { - public: - typedef Matcher<const Proto&> InnerMatcher; - - explicit WhenDeserializedAsMatcher(const InnerMatcher& proto_matcher) - : proto_matcher_(proto_matcher) {} - - virtual ~WhenDeserializedAsMatcher() {} - - // Deserializes the string as a protobuf of the same type as the expected - // protobuf. - Proto* Deserialize(const string& str) const { - Proto* proto = new Proto; - if (proto->ParsePartialFromString(str)) { - return proto; - } else { - delete proto; - return NULL; - } - } - - void DescribeTo(::std::ostream* os) const { - *os << "can be deserialized as a protobuf that "; - proto_matcher_.DescribeTo(os); - } - - void DescribeNegationTo(::std::ostream* os) const { - *os << "cannot be deserialized as a protobuf that "; - proto_matcher_.DescribeTo(os); - } - - bool MatchAndExplain(const string& arg, MatchResultListener* listener) const { - // Deserializes the string arg as a protobuf of the same type as the - // expected protobuf. - scoped_ptr<const Proto> deserialized_arg(Deserialize(arg)); - // No need to explain the match result. - return (deserialized_arg.get() != NULL) && - proto_matcher_.Matches(*deserialized_arg); - } - - private: - const InnerMatcher proto_matcher_; -}; - -} // namespace internal - -namespace proto { - -// WhenDeserializedAs<Proto>(m) is a matcher that matches a string -// that can be deserialized as a protobuf of type Proto that matches -// m, which can be any valid protobuf matcher. -template <class Proto, class InnerMatcher> -inline PolymorphicMatcher<internal::WhenDeserializedAsMatcher<Proto> > -WhenDeserializedAs(const InnerMatcher& inner_matcher) { - return MakePolymorphicMatcher( - internal::WhenDeserializedAsMatcher<Proto>( - SafeMatcherCast<const Proto&>(inner_matcher))); -} - -} // namespace proto - -MATCHER_P(EqualsProto, message, "") { - // TOOD(ghc): This implementation assume protobuf serialization is - // deterministic, which is true in practice but technically not something that - // code is supposed to rely on. However, it vastly simplifies the - // implementation... - std::string expected_serialized, actual_serialized; - message.SerializeToString(&expected_serialized); - arg.SerializeToString(&actual_serialized); - return expected_serialized == actual_serialized; -} - -} // namespace testing - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_GMOCK_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/googletest.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/googletest.h deleted file mode 100644 index 8623e8cf48dff710ad7d3844503738db99176823..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/googletest.h +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_GOOGLETEST_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_GOOGLETEST_H_ - -#include "testing/gtest/include/gtest/gtest.h" - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_GOOGLETEST_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/logging.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/logging.h deleted file mode 100644 index 0c7c52f8c4c4ccde81729ab6aac5de811bbea81d..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/logging.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_LOGGING_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_LOGGING_H_ - -#include "base/logging.h" - -namespace invalidation { - -using logging::LogMessage; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_LOGGING_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/mutex.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/mutex.h deleted file mode 100644 index 1f0e23cdf95a2c629d0bc131be9edcb19a864950..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/mutex.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_MUTEX_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_MUTEX_H_ - -#include "base/logging.h" -#include "base/synchronization/lock.h" - -namespace invalidation { - -typedef base::Lock Mutex; - -class MutexLock { - public: - explicit MutexLock(Mutex* m) : auto_lock_(*m) {} - - private: - base::AutoLock auto_lock_; - DISALLOW_COPY_AND_ASSIGN(MutexLock); -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_MUTEX_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/random.cc b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/random.cc deleted file mode 100644 index 808baa65cc392f36ac9effed3c963b37ab0e7faf..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/random.cc +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "google/cacheinvalidation/deps/random.h" - -namespace invalidation { - -double Random::RandDouble() { - return base::RandDouble(); -} - -uint64 Random::RandUint64() { - return base::RandUint64(); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/random.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/random.h deleted file mode 100644 index 55b3abc9e7669b5c0909fa38409c9a4a53f7e75d..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/random.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_RANDOM_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_RANDOM_H_ - -#include "base/rand_util.h" - -namespace invalidation { - -class Random { - public: - // We don't actually use the seed. - explicit Random(int64 seed) {} - - virtual ~Random() {} - - // Returns a pseudorandom value between(inclusive) and(exclusive). - virtual double RandDouble(); - - virtual uint64 RandUint64(); -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_RANDOM_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/scoped_ptr.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/scoped_ptr.h deleted file mode 100644 index b849a40f6dc66874158b1824d1475788363fdd30..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/scoped_ptr.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_SCOPED_PTR_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_SCOPED_PTR_H_ - -#include "base/memory/scoped_ptr.h" - -namespace invalidation { - -using ::scoped_ptr; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_SCOPED_PTR_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/sha1-digest-function.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/sha1-digest-function.h deleted file mode 100644 index d12c971dfe9fd06df0037da52506bf920e587161..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/sha1-digest-function.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Interface to SHA1 digest computation. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_SHA1_DIGEST_FUNCTION_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_SHA1_DIGEST_FUNCTION_H_ - -#include <string> - -#include "base/sha1.h" -#include "google/cacheinvalidation/deps/digest-function.h" -#include "google/cacheinvalidation/deps/stl-namespace.h" - -namespace invalidation { - -using ::INVALIDATION_STL_NAMESPACE::string; - -class Sha1DigestFunction : public DigestFunction { - public: - Sha1DigestFunction() : reset_needed_(false) {} - - virtual void Reset() { - reset_needed_ = false; - buffer_.clear(); - } - - virtual void Update(const string& s) { - CHECK(!reset_needed_); - buffer_.append(s); - } - - virtual string GetDigest() { - CHECK(!reset_needed_); - reset_needed_ = true; - return base::SHA1HashString(buffer_); - } - - private: - string buffer_; - bool reset_needed_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_SHA1_DIGEST_FUNCTION_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/stl-namespace.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/stl-namespace.h deleted file mode 100644 index 352af0e3d3de18cc94dbb90a1814fe54e1e1733a..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/stl-namespace.h +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_STL_NAMESPACE_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_STL_NAMESPACE_H_ - -#define INVALIDATION_STL_NAMESPACE std - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_STL_NAMESPACE_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/string_util.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/string_util.h deleted file mode 100644 index c8f75a488fde54333c59c1defa1f1532e1ad075b..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/string_util.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_STRING_UTIL_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_STRING_UTIL_H_ - -#include "base/strings/string_number_conversions.h" -#include "base/strings/stringprintf.h" - -namespace invalidation { - -using base::StringAppendV; -using base::StringPrintf; - -inline std::string SimpleItoa(int v) { - return base::IntToString(v); -} - -inline std::string SimpleItoa(int64 v) { - return base::Int64ToString(v); -} - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_STRING_UTIL_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/time.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/time.h deleted file mode 100644 index 8ac2aa1343c1e9bc6ebd7282460ca88721308db8..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/deps/time.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_TIME_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_TIME_H_ - -#include "base/time/time.h" - -namespace invalidation { -typedef base::Time Time; -typedef base::TimeTicks TimeTicks; -typedef base::TimeDelta TimeDelta; -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_TIME_H_ diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/gmock.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/gmock.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/googletest.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/googletest.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/hash_map.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/hash_map.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/logging.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/logging.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/md5.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/md5.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/mutex.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/mutex.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/random.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/random.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/scoped_ptr.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/scoped_ptr.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/stl-namespace.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/stl-namespace.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/string_util.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/string_util.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/time.h b/chromium/third_party/cacheinvalidation/overrides/google/cacheinvalidation/time.h deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/AndroidManifest.xml b/chromium/third_party/cacheinvalidation/src/example-app-build/AndroidManifest.xml deleted file mode 100644 index c2673e9829f7ca5f76729febcf1965845792310e..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/example-app-build/AndroidManifest.xml +++ /dev/null @@ -1,92 +0,0 @@ -<?xml version="1.0" ?> -<!-- Copyright 2011 Google Inc. All Rights Reserved. --> -<!-- Manifest for AndroidListener sample application. Must be merged with - j/c/g/ipc/invalidation/external/client/contrib:android_listener_manifest. --> -<manifest android:versionCode="1" android:versionName="0.1" package="com.google.ipc.invalidation.examples.android2" xmlns:android="http://schemas.android.com/apk/res/android"> - <!-- *** WARNING *** DO NOT EDIT! THIS IS GENERATED MANIFEST BY MERGE_MANIFEST TOOL. - Merger manifest: - java/com/google/ipc/invalidation/examples/android2/AndroidManifest.xml - Mergee manifests: - blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml - --> - <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14"/> - <!-- Declare and use permission allowing this application to receive GCM - messages. --> - <permission android:name="com.google.ipc.invalidation.examples.android2.permission.C2D_MESSAGE" android:protectionLevel="signature"/> - <uses-permission android:name="com.google.ipc.invalidation.examples.android2.permission.C2D_MESSAGE"/> - <application> - <!-- Configure the listener class for the application --> - <meta-data android:name="ipc.invalidation.ticl.listener_service_class" android:value="com.google.ipc.invalidation.examples.android2.ExampleListener"/> - <!-- To enable background invalidations uncomment the following element: - --> - <!--<meta-data - android:name= - "ipc.invalidation.ticl.background_invalidation_listener_service_class" - android:value= - "com.google.ipc.invalidation.examples.android2.ExampleListener"/>--> - <!-- Example activity --> - <activity android:name="com.google.ipc.invalidation.examples.android2.MainActivity"> - <intent-filter> - <action android:name="android.intent.action.MAIN"/> - <category android:name="android.intent.category.LAUNCHER"/> - </intent-filter> - </activity> - <!-- Ticl listener. --> - <service android:exported="false" android:name="com.google.ipc.invalidation.examples.android2.ExampleListener"> - <intent-filter> - <action android:name="com.google.ipc.invalidation.AUTH_TOKEN_REQUEST"/> - </intent-filter> - </service> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- Receiver for scheduler alarms. --> - <receiver android:exported="false" android:name="com.google.ipc.invalidation.external.client.contrib.AndroidListener$AlarmReceiver"/> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- Receiver for scheduler alarms. --> - <receiver android:exported="false" android:name="com.google.ipc.invalidation.ticl.android2.AndroidInternalScheduler$AlarmReceiver"/> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- GCM Broadcast Receiver --> - <receiver android:exported="true" android:name="com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener$GCMReceiver" android:permission="com.google.android.c2dm.permission.SEND"> - <intent-filter> - <action android:name="com.google.android.c2dm.intent.RECEIVE"/> - <action android:name="com.google.android.c2dm.intent.REGISTRATION"/> - <category android:name="com.google.ipc.invalidation.ticl.android2"/> - </intent-filter> - </receiver> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- Merged from file: java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml --> - <receiver android:exported="false" android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageReceiverService$Receiver"> - <intent-filter> - <action android:name="com.google.ipc.invalidation.gcmmplex.EVENT"/> - </intent-filter> - </receiver> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- Ticl service. --> - <service android:exported="false" android:name="com.google.ipc.invalidation.ticl.android2.TiclService"/> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- Ticl sender. --> - <service android:exported="false" android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageSenderService"/> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- GCM multiplexer --> - <service android:exported="false" android:name="com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener"> - <meta-data android:name="sender_ids" android:value="ipc.invalidation@gmail.com"/> - </service> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- Invalidation service multiplexed GCM receiver --> - <service android:enabled="true" android:exported="false" android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageReceiverService"/> - </application> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- App receives GCM messages. --> - <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- GCM connects to Google Services. --> - <uses-permission android:name="android.permission.INTERNET"/> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- GCM requires a Google account. --> - <uses-permission android:name="android.permission.GET_ACCOUNTS"/> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- Merged from file: java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml --> - <uses-permission android:name="android.permission.USE_CREDENTIALS"/> - <!-- Merged from file: blaze-out/gcc-4.X.Y-crosstool-v17-hybrid-grtev3-k8-fastbuild/bin/java/com/google/ipc/invalidation/external/client/contrib/android_listener_manifest/AndroidManifest.xml --> - <!-- Keeps the processor from sleeping when a message is received. --> - <uses-permission android:name="android.permission.WAKE_LOCK"/> -</manifest> diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/README b/chromium/third_party/cacheinvalidation/src/example-app-build/README deleted file mode 100644 index 07cd60ec4343650f6643f7682c8a4ba65042b741..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/example-app-build/README +++ /dev/null @@ -1,8 +0,0 @@ -Copyright 2012 Google Inc. All Rights Reserved. - -This directory contains the files required to build the example application for -the Invalidation Client, the source code of which is located under -../src/java/com/google/ipc/invalidation/examples/android2. - -To build the example, first run ./generate_protos.sh. Then, run ant debug or -ant release to build the application. diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/ant.properties b/chromium/third_party/cacheinvalidation/src/example-app-build/ant.properties deleted file mode 100644 index a4e924b54f666bb6ba1e88b6fa57c03583f67d3f..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/example-app-build/ant.properties +++ /dev/null @@ -1 +0,0 @@ -source.dir = ../java:generated-protos diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/build.xml b/chromium/third_party/cacheinvalidation/src/example-app-build/build.xml deleted file mode 100644 index 4b8f3c009bf2c94a6a9e07209258273c6170670c..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/example-app-build/build.xml +++ /dev/null @@ -1,88 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project name="MainActivity" default="help"> - - <!-- The local.properties file is created and updated by the 'android' tool. - It contains the path to the SDK. It should *NOT* be checked into - Version Control Systems. --> - <property file="local.properties" /> - - <!-- The ant.properties file can be created by you. It is only edited by the - 'android' tool to add properties to it. - This is the place to change some Ant specific build properties. - Here are some properties you may want to change/update: - - source.dir - The name of the source directory. Default is 'src'. - out.dir - The name of the output directory. Default is 'bin'. - - For other overridable properties, look at the beginning of the rules - files in the SDK, at tools/ant/build.xml - - Properties related to the SDK location or the project target should - be updated using the 'android' tool with the 'update' action. - - This file is an integral part of the build system for your - application and should be checked into Version Control Systems. - - --> - <property file="ant.properties" /> - - <!-- The project.properties file is created and updated by the 'android' - tool, as well as ADT. - - This contains project specific properties such as project target, and library - dependencies. Lower level build properties are stored in ant.properties - (or in .classpath for Eclipse projects). - - This file is an integral part of the build system for your - application and should be checked into Version Control Systems. --> - <loadproperties srcFile="project.properties" /> - - <!-- quick check on sdk.dir --> - <fail - message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var" - unless="sdk.dir" - /> - - -<!-- extension targets. Uncomment the ones where you want to do custom work - in between standard targets --> -<!-- - <target name="-pre-build"> - </target> ---> -<!-- - <target name="-pre-build"> - <target name="-pre-compile"> - </target> - - /* This is typically used for code obfuscation. - Compiled code location: ${out.classes.absolute.dir} - If this is not done in place, override ${out.dex.input.absolute.dir} */ - <target name="-post-compile"> - </target> ---> - - <!-- Import the actual build file. - - To customize existing targets, there are two options: - - Customize only one target: - - copy/paste the target into this file, *before* the - <import> task. - - customize it to your needs. - - Customize the whole content of build.xml - - copy/paste the content of the rules files (minus the top node) - into this file, replacing the <import> task. - - customize to your needs. - - *********************** - ****** IMPORTANT ****** - *********************** - In all cases you must update the value of version-tag below to read 'custom' instead of an integer, - in order to avoid having your file be overridden by tools such as "android update project" - --> - <!-- version-tag: 1 --> - <import file="${sdk.dir}/tools/ant/build.xml" /> - -</project> diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/generate_protos.sh b/chromium/third_party/cacheinvalidation/src/example-app-build/generate_protos.sh deleted file mode 100755 index 71b5d8e783130a61da28cafc5e450e6633f90eda..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/example-app-build/generate_protos.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh -# Copyright 2012 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Tool to output Java classes for the protocol buffers used by the invalidation -# client into the generated-protos/ directory. -TOOL=${PROTOC- `which protoc`} -mkdir -p generated-protos/ -$TOOL --java_out=generated-protos/ ../proto/* --proto_path=../proto/ -EXAMPLE_PATH=../java/com/google/ipc/invalidation/examples/android2 -$TOOL --java_out=generated-protos/ $EXAMPLE_PATH/example_listener.proto --proto_path=$EXAMPLE_PATH \ No newline at end of file diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/libs/gcm.jar b/chromium/third_party/cacheinvalidation/src/example-app-build/libs/gcm.jar deleted file mode 100644 index ac109a830ebe95e89e1456e23328212ad70576dc..0000000000000000000000000000000000000000 Binary files a/chromium/third_party/cacheinvalidation/src/example-app-build/libs/gcm.jar and /dev/null differ diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/libs/guava-13.0.1.jar b/chromium/third_party/cacheinvalidation/src/example-app-build/libs/guava-13.0.1.jar deleted file mode 100644 index 09c5449115df66fdd2611e2c4f8c362fbb6aaff3..0000000000000000000000000000000000000000 Binary files a/chromium/third_party/cacheinvalidation/src/example-app-build/libs/guava-13.0.1.jar and /dev/null differ diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/libs/protobuf-java-2.4.1-lite.jar b/chromium/third_party/cacheinvalidation/src/example-app-build/libs/protobuf-java-2.4.1-lite.jar deleted file mode 100644 index 5ad584ff9cae2aa85eaf710e9132a3f2c1da0ad8..0000000000000000000000000000000000000000 Binary files a/chromium/third_party/cacheinvalidation/src/example-app-build/libs/protobuf-java-2.4.1-lite.jar and /dev/null differ diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/local.properties b/chromium/third_party/cacheinvalidation/src/example-app-build/local.properties deleted file mode 100644 index e521a1c732cab9a8662eb134e0f1daf112ad9102..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/example-app-build/local.properties +++ /dev/null @@ -1,10 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must *NOT* be checked in Version Control Systems, -# as it contains information specific to your local configuration. - -# location of the SDK. This is only used by Ant -# For customization when using a Version Control System, please read the -# header note. -sdk.dir=/home/dsmyers/bin/android-sdk-linux diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/proguard.cfg b/chromium/third_party/cacheinvalidation/src/example-app-build/proguard.cfg deleted file mode 100644 index 9533f0643713adf86b68c2b225c3371c545d8f3f..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/example-app-build/proguard.cfg +++ /dev/null @@ -1,76 +0,0 @@ -# -# This file was derived from the Android SDK default configuration in tools/lib/proguard.cfg, -# with changes/additions explicitly commented where made -# --optimizationpasses 5 --dontusemixedcaseclassnames --dontskipnonpubliclibraryclasses --dontpreverify -# Change: SDK defaults + code/allocation/variable required to disable proguard optimization bug --verbose --optimizations !code/simplification/arithmetic,!field/*,!class/merging/*,!code/allocation/variable - --keep public class * extends android.app.Activity --keep public class * extends android.app.Application --keep public class * extends android.app.Service --keep public class * extends android.content.BroadcastReceiver --keep public class * extends android.content.ContentProvider --keep public class * extends android.app.backup.BackupAgentHelper --keep public class * extends android.preference.Preference -# Change: not needed -#-keep public class com.android.vending.licensing.ILicensingService - --keepclasseswithmembernames class * { - native <methods>; -} - --keepclasseswithmembers class * { - public <init>(android.content.Context, android.util.AttributeSet); -} - --keepclasseswithmembers class * { - public <init>(android.content.Context, android.util.AttributeSet, int); -} - --keepclassmembers class * extends android.app.Activity { - public void *(android.view.View); -} - --keepclassmembers enum * { - public static **[] values(); - public static ** valueOf(java.lang.String); -} - --keep class * implements android.os.Parcelable { - public static final android.os.Parcelable$Creator *; -} - -# -# All changes below are additions to the Android SDK defaults, generally for the purposes of -# suppressing spurious or inconsequential warnings. -# - -# Suppress duplicate warning for system classes; Blaze is passing android.jar -# to proguard multiple times. --dontnote android.** --dontnote java.** --dontnote javax.** --dontnote junit.** --dontnote org.** --dontnote dalvik.** --dontnote com.android.internal.** - -# Stop warnings about missing unused classes --dontwarn com.google.common.annotations.** --dontwarn com.google.common.base.** --dontwarn com.google.common.collect.** --dontnote com.google.common.flags.** --dontwarn com.google.common.flags.** --dontwarn com.google.common.util.concurrent.** - -# Ignore missing JDK6 classes --dontwarn java.** - -# Inverting these produces significant size gains but loses significant debug info --dontobfuscate -#-flattenpackagehierarchy diff --git a/chromium/third_party/cacheinvalidation/src/example-app-build/project.properties b/chromium/third_party/cacheinvalidation/src/example-app-build/project.properties deleted file mode 100644 index 9aa0dfa878c4128dc3afc8f53971847400c1851c..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/example-app-build/project.properties +++ /dev/null @@ -1,11 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=Google Inc.:Google APIs:15 diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/COPYING b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/COPYING deleted file mode 100644 index d645695673349e3947e8e5ae42332d0ac3164cd7..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/COPYING +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/README b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/README deleted file mode 100644 index a9dd982e3bb3e2ee7408eef7e701a9330aa003a4..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/README +++ /dev/null @@ -1,16 +0,0 @@ -This directory contains the implementation of the client library for a cache -invalidation service. - -The public (stable) interfaces are those defined under include/: - invalidation-client.h - invalidation-client-factory.h - invalidation-listener.h - system-resources.h - types.h - -In order to compile this library, proper implementations of the interfaces -residing under deps/ must be provided. - -Interfaces and implementations defined under impl/ are subject to change, and -the test/ directory contains test helpers. Please do not depend directly -on anything in these directories. diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/android_channel.proto b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/android_channel.proto deleted file mode 100644 index 1e6a1fbd27a56736956b5490e5f6b7591632c4e7..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/android_channel.proto +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// The Android delivery service's network endpoint id descriptor. -// This proto is internal to the Android channel. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package ipc.invalidation; - -import "client_protocol.proto"; - -// Defines the valid major versions of the android channel protocol. The -// channel version controls the expected envelope syntax and semantics of -// http and c2dm messages sent between the client and server. -enum MajorVersion { - option allow_alias = true; - - // The initial version of the android channel protocol. Inbound and - // outbound channel packets contained a single binary protocol message only. - INITIAL = 0; - - // Adds batching (multiple protocol messages in a single channel message) - BATCH = 1; - - // The default channel version used by Android clients. Lower major numbers - // will represent earlier versions and higher numbers will represent - // experimental versions that are not yet released. - DEFAULT = 0; - - // The minimum and maximum supported channel major versions. Used to validate - // incoming requests, so update as new versions are added or old versions are - // no longer supported. - MIN_SUPPORTED = 0; - MAX_SUPPORTED = 1; -} - -// An id that specifies how to route a message to a Ticl on an Android device -// via C2DM. -message EndpointId { - // Field 1 was once the ProtocolVersion of this message. - - // The "registration_id" returned when the client registers with c2dm. This - // id is required by c2dm in order to send a message to the device. - optional string c2dm_registration_id = 2; - - // A key identifying a specific client on a device. - optional string client_key = 3; - - // The C2DM sender ID to use to deliver messages to the endpoint. - optional string sender_id = 4 [deprecated = true]; - - // Defines the expected channel version generated by the network endpoint or - // expected in messages sent from the server. - optional Version channel_version = 5; - - // The package name of the Android application that will receive the messages. - // Replaces sender_id. Must be set (unless sender_id is set; in which case it - // must not be set). - optional string package_name = 6; -} - -// A message addressed to a particular Ticl on an Android device. -message AddressedAndroidMessage { - // Client on the device to which the message is destined. - optional string client_key = 1; - - // Message contents (serialized ServerToClientMessage). - optional bytes message = 2; -} - -// A batch of messages addressed to potentially-different Ticls on the same -// Android device. -message AddressedAndroidMessageBatch { - repeated AddressedAndroidMessage addressed_message = 1; -} diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/channel_common.proto b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/channel_common.proto deleted file mode 100644 index 58e73be28e382110d55532674bbc82643497fdad..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/channel_common.proto +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Common utilities used by all channel related protos. -// This is also publicly visible to all channel implementors. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package ipc.invalidation; - -message ChannelMessageEncoding { - // What kind of encoding is used for network_message - enum MessageEncoding { - // Raw proto encoding - PROTOBUF_BINARY_FORMAT = 1; - - // JSPB-encoding: https://sites.google.com/a/google.com/jspblite/Home - PROTOBUF_JSON_FORMAT = 2; - } -} - -message NetworkEndpointId { - enum NetworkAddress { - TEST = 1; // A delivery service for testing - - // Low numbers reserved. - ANDROID = 113; // Android delivery service using c2dm / http. - } - optional NetworkAddress network_address = 1; - optional bytes client_address = 2; - - // Optional. When true, the client is considered offline but the - // client_address is maintained so that the client can potentially be reached. - // When false or undefined, the client is considered online. - optional bool is_offline = 3; -} diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client.proto b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client.proto deleted file mode 100644 index e79b32735088c295e386bc5a80bcf1a879e2d20a..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client.proto +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Specification of protocol buffers that are used only on the client side. -// -// Note: unless otherwise specified in a comment, all fields in all messages -// are required, even though they are listed as optional. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package ipc.invalidation; - -import "client_protocol.proto"; - -// An object that is serialized and given to clients for acknowledgement -// purposes. -message AckHandleP { - optional InvalidationP invalidation = 1; -} - -// The state persisted at a client so that it can be used after a reboot. -message PersistentTiclState { - // Last token received from the server (required). - optional bytes client_token = 1; - - // Last time a message was sent to the server (optional). Must be a value - // returned by the clock in the Ticl system resources. - optional int64 last_message_send_time_ms = 2 [default = 0]; -} - -// An envelope containing a Ticl's internal state, along with a digest of the -// serialized representation of this state, to ensure its integrity across -// reads and writes to persistent storage. -message PersistentStateBlob { - // The (important parts of the) Ticl's internal state. - optional PersistentTiclState ticl_state = 1; - - // Implementation-specific message authentication code for the Ticl state. - optional bytes authentication_code = 2; -} - -// State of a Ticl RunState. -message RunStateP { - enum State { - NOT_STARTED = 1; - STARTED = 2; - STOPPED = 3; - } - optional State state = 1; -} - diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_gateway.proto b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_gateway.proto deleted file mode 100644 index 5b12452f7be382d78b73af8ec45e38719064a32d..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_gateway.proto +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Specification of invalidation gateway internal forwarding messages and -// services. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package ipc.invalidation; - -// The message communicated between gateway and clients. -message ClientGatewayMessage { - // Whether it is client to server or server to client. - optional bool is_client_to_server = 1; - - // Serialized version of the ServiceContext. - optional bytes service_context = 2; - - // Rpc scheduling hash. - optional int64 rpc_scheduling_hash = 3; - - // Payload of the network message (ClientToServerMessage or - // ServerToClientMessage). - optional bytes network_message = 4; -} diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_protocol.proto b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_protocol.proto deleted file mode 100644 index 285457d61d600fd71bfb468401b770443fa9f631..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_protocol.proto +++ /dev/null @@ -1,595 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Specification of protocol buffers and the client-server protocol that are -// used by the clients of the system. -// -// Note: unless otherwise specified in a comment, all fields in all messages -// are required, even though they are listed as optional. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package ipc.invalidation; - -// Here is a high-level overview of the protocol. The protocol is designed in a -// "message-passing" style, i.e., the client (C) or the server (S) can send any -// message SPONTANEOUSLY at any time and both sides have to be prepared for any -// message from the other side. However, even with this style, there are some -// "flows" which are somewhat like requests and replies. - -// 1. Initialization: When a client starts up, it needs a token to alow it to -// perform any other operation with the server. -// C -> S: InitializeMessage -// S -> C: TokenControlMessage -// -// 2. Registration: When a client has to register or unregister for a set of -// objects, the following flow occurs: -// C -> S: RegistrationMessage -// S -> C: RegistrationStatusMessage -// -// 3. Invalidation: The server sends an invalidation and the client sends back -// an ack. -// S -> C InvalidationMessage -// C -> S InvalidationMessage -// -// 4. Registration sync: Once in a while the server may detect that the client -// and server's registration state is out of sync (the server can detect this -// since it gets the client's registration summary in the client's message -// header). In that case, it asks the client some registration information -// and the client sends it to the server. -// S -> C: RegistrationSyncRequestMessage -// C -> S: RegistrationSyncMessage -// -// 5. Information messages: The server can occasionally for client-side -// information such as statistics, etc. The client responds with the -// requested information -// S -> C: InfoRequestMessage -// C -> S: InfoMessage -// -// ------------------------------------------------------------------------ - -// A basic message type used for versioning public proto messages and/or -// types. The two fields are supposed to be used as follows: -// -// * The major version number is changed whenever an incompatible protocol -// change or type has been made. When a message/object with a particular -// major version is received, the receiver needs to either know how to handle -// this version or it needs to drop the message -// -// * The minor version can be changed (say) to document some internal change -// for debugging purposes. When a message is received by a receiver, it MUST -// ignore the minor version number for making any protocol/type -// decisions. I.e., the minor version number is for debugging purposes only. -// -// Versioning is used in various places - for entities that are part of a -// protocol (e.g., message requests), for various client implementations, and -// for other data types that change independently of the protocol (e.g., -// session tokens). For each versioned entity, we define a specific message -// type to encapsulate the version of that entity (e.g., ProtocolVersion, -// ClientVersion, etc.). -message Version { - optional int32 major_version = 1; - optional int32 minor_version = 2; -} - -// Message included in all client <-> server messages to indicate the version -// of the protocol in use by the sender. -message ProtocolVersion { - optional Version version = 1; -} - -// Defines a specific version of the client library (for information purposes -// only) May not be used to make decisions at the server (use ProtocolVersion -// instead). -message ClientVersion { - - // A client-specific version number. - optional Version version = 1; - - // All fields below are for informational/debugging/monitoring purposes only. - // No critical code decision is supposed to be made using them. - - // Information about the client operating system/platform, e.g., Windows, - // ChromeOS. - optional string platform = 2; - - // Language used for the library. - optional string language = 3; - - // Extra information about the client (e.g., application name). - optional string application_info = 4; -} - -// Message indicating the result of an operation. -message StatusP { - - // Whether operation is successful or not - enum Code { - SUCCESS = 1; - TRANSIENT_FAILURE = 2; - PERMANENT_FAILURE = 3; - } - - optional Code code = 1; - - // Textual description of the status or additional context about any - // error. (Optional - Can be set for success also.) - optional string description = 2; -} - -// Identifies an object that a client can register for. -message ObjectIdP { - - // The source of the data. - optional int32 source = 1; - - // The id of the object relative to the source. Must be <= 64 bytes. - optional bytes name = 2; -} - -// A message containing the part of the client's id that the application -// controls. This id is used for squelching invalidations on the server side. -// For example, if a client C1 modifies object x and informs the backend about -// C1's application client id as part of the invalidation. The backend can then -// avoid sending the invalidation unnecessarily to that client. -// -// If the application wishes to use this squelching feature, it must assign a -// globally unique client_name for a given client_type so that the particular -// instantation of the application can be identified. -message ApplicationClientIdP { - // The type of the client. - optional int32 client_type = 1; - - // A client name or unique id assigned by the application. Application should - // choose a unique name for different client instances if it wants to squelch - // invalidations by name (as discussed above). - optional bytes client_name = 2; -} - -// Invalidation for a given object/version. -message InvalidationP { - // The id of the object being invalidated. - optional ObjectIdP object_id = 1; - - // Whether the invalidation is for a known version of the object as assigned - // by an application backend (is_known_version == true) or an unknown system - // version synthesized by the invalidation service. (Note that if - // is_known_version is false then is_trickle_restart be true or missing - // because an unknown version implies that invalidation versions prior to the - // current backend version may have been dropped.) - optional bool is_known_version = 2; - - // Version being invalidated (see comment on is_known_version). If the - // is_known_version is false, the version corresponds to an internal "system - // version" for *that* object. An object's system version has no meaning to - // the application other than the fact that these system versions are also - // monotonically increasing and the client must ack such an invalidation with - // this system version (and an ack for a later system version acknowledges an - // invalidation for all earlier system version for *that* object. - optional int64 version = 3; - - // Whether the object's Trickle is restarting at this version. - // sets this value to true to inform Trickle API clients that it may - // have dropped invalidations prior to "version", or, if is_known_version is - // false, prior to the current backend version. - optional bool is_trickle_restart = 6 [default = false]; - - // Optional payload associated with this invalidation. - optional bytes payload = 4; - - // DEPRECATED: bridge arrival time is now maintained by - // InvalidationMetadataP in the SourcedInvalidation, InvalidationContents and - // ClientInvalidation containers. - optional int64 bridge_arrival_time_ms_deprecated = 5 [deprecated=true]; -} - -// Specifies the intention to change a registration on a specific object. To -// update registrations, a client sends a message containing repeated -// RegistrationP messages. -message RegistrationP { - enum OpType { - REGISTER = 1; - UNREGISTER = 2; - } - - // The object for which to (un)register. - optional ObjectIdP object_id = 1; - - // Whether to register or unregister. - optional OpType op_type = 2; -} - -// Summary of the registration state associated with a particular client, sent -// in the header of client<->server messages. This summary has two different -// (but related) meanings depending on where it is used: -// -// 1) In a client->server message, it describes the DESIRED client state. -// 2) In a server->client message, it describes the ACTUAL state at the server -// for that client. -message RegistrationSummary { - // Number of registrations desired (client) or held (server). - optional int32 num_registrations = 1; - - // Top-level digest over the registrations. - // - // The digest for an object id is computed as following (the digest chosen for - // this method is SHA-1): - // - // digest = new Digest(); - // digest.update(Little endian encoding of object source type) - // digest.update(object name) - // digest.getDigestSummary() - // - // For a set of objects, digest is computing by sorting lexicographically - // based on their digests and then performing the update process given above - // (i.e., calling digest.update on each object's digest and then calling - // getDigestSummary at the end). - optional bytes registration_digest = 2; -} - -// Header included on every client -> server message. -message ClientHeader { - - // Protocol version of this message. - optional ProtocolVersion protocol_version = 1; - - // Token identifying the client. Tokens are issued by the server in response - // to client requests (see InitializeMessage, below). In order to perform any - // operation other than initialization, the client must supply a token. When - // performing initialization, this field must be left unset. - optional bytes client_token = 2; - - // Optional summary of the client's desired registration state. The client is - // encouraged to provide this summary in every message once a "steady" state - // of registrations/unregistrations has been reached. For example, it may not - // want to send this summary during initialization (but after the initial set - // has been registered, it should try to send it). - optional RegistrationSummary registration_summary = 3; - - // Timestamp from the client's clock, expressed as ms since 00:00:00 UTC, 1 - // January 1970 (i.e., the UNIX epoch) - for debugging/monitoring purposes. - optional int64 client_time_ms = 4; - - // Highest server timestamp observed by the client (the server includes its - // time on every message to the client). Note: this time is NOT necessarily - // expressed as relative to the UNIX epoch - for debugging/monitoring - // purposes. - optional int64 max_known_server_time_ms = 5; - - // Message id to identify the message -for debugging/monitoring purposes. - optional string message_id = 6; - - // Client typecode (as in the InitializeMessage, below). This field may or - // may not be set. - optional int32 client_type = 7; -} - -// A message from the client to the server. -message ClientToServerMessage { - // Header. - optional ClientHeader header = 1; - - // Any or all of the follow messages may be present. - - // Optional initialization message, used to obtain a new token. Note that, if - // present, this message is always processed before the messages below, and - // those messages will be interpreted relative to the new token assigned here. - optional InitializeMessage initialize_message = 2; - - // Optional request to perform registrations. - optional RegistrationMessage registration_message = 3; - - // Optional data for registration sync. - optional RegistrationSyncMessage registration_sync_message = 4; - - // Optional invalidation acks. - optional InvalidationMessage invalidation_ack_message = 5; - - // Optional information about the client. - optional InfoMessage info_message = 6; -} - -// Used to obtain a new token when the client does not have one. -message InitializeMessage { - - // Defines how clients serialize object ids when computing digests for - // registrations. - enum DigestSerializationType { - - // The digest for an object id is computed by serializing the object id into - // bytes. - BYTE_BASED = 1; - - // The digest for an object id is computed by serializing the object id into - // an array of numbers. - NUMBER_BASED = 2; - } - - // Type of the client. This value is assigned by the backend notification - // system (out-of-band) and the client must use the correct value. - optional int32 client_type = 1; - - // Nonce. This value will be echoed as the existing token in the header of - // the server message that supplies the new token (the new token itself will - // be provided in a TokenControlMessage; see below). - optional bytes nonce = 2; - - // Id of the client as assigned by the application. - optional ApplicationClientIdP application_client_id = 3; - - // Type of registration digest used by this client. - optional DigestSerializationType digest_serialization_type = 4; -} - -// Registration operations to perform. -message RegistrationMessage { - repeated RegistrationP registration = 1; -} - -// Message from the client to the server. -message RegistrationSyncMessage { - - // Objects for which the client is registered. - repeated RegistrationSubtree subtree = 1; -} - -// Message sent from the client to the server about registered objects -// (typically) in response to a registration sync request. -// -// The name of the message implies a "tree" for future expansion where the -// intention is to not necessarily send the complete set of objects but to -// partition the object space into multiple ranges and then exchange Merkle-tree -// like data structures to determine which ranges are out-of-sync. -message RegistrationSubtree { - // Registered objects - repeated ObjectIdP registered_object = 1; -} - -// A message from the client to the server with info such as performance -// counters, client os info, etc. -message InfoMessage { - optional ClientVersion client_version = 1; - - // Config parameters used by the client. - // Deprecated and removed - the client_config parameter is what is used now. - repeated PropertyRecord config_parameter = 2; - - // Performance counters from the client. - repeated PropertyRecord performance_counter = 3; - - // If 'true', indicates that the client does not know the server's - // registration summary, so the server should respond with it even if the - // client's summary matches the server's. - optional bool server_registration_summary_requested = 4; - - // Configuration parameters for this client. - optional ClientConfigP client_config = 5; -} - -// Information about a single config/performance counter value in the -// InfoMessage. -message PropertyRecord { - - // Name of the performance counter/config parameter. - optional string name = 1; - - // Value of the performance counter/config parameter. - optional int32 value = 2; -} - -message ServerHeader { - // Protocol version of this message. - optional ProtocolVersion protocol_version = 1; - - // Current token that the server expects the client to have. Clients must - // ignore messages where this token field does not match their current token. - // During initialization, the client's "token" is the nonce that it generates - // and sends in the InitializeMessage. - optional bytes client_token = 2; - - // Summary of registration state held by the server for the client. - optional RegistrationSummary registration_summary = 3; - - // Timestamp from the server's clock. No guarantee on when this time is - // relative to. - optional int64 server_time_ms = 4; - - // Message id to identify the message (for debug purposes only). - optional string message_id = 5; -} - -message ServerToClientMessage { - optional ServerHeader header = 1; - - // Message to assign a new client token or invalidate an existing one. Note - // that, if present, this message is always processed before the messages - // below, and those messages will be interpreted relative to the new token - // assigned here. - optional TokenControlMessage token_control_message = 2; - - // Invalidations. - optional InvalidationMessage invalidation_message = 3; - - // Registration operation replies. - optional RegistrationStatusMessage registration_status_message = 4; - - // Request for client registration state. - optional RegistrationSyncRequestMessage registration_sync_request_message = 5; - - // Request to change config from the server. - optional ConfigChangeMessage config_change_message = 6; - - // Request for client information. - optional InfoRequestMessage info_request_message = 7; - - // Asynchronous error information that the server sends to the client. - optional ErrorMessage error_message = 8; -} - -// Message used to supply a new client token or invalidate an existing one. -message TokenControlMessage { - // If status is failure, new_token cannot be set. - optional bytes new_token = 1; // If missing, means destroy_token -} - -// Status of a particular registration (could be sent spontaneously by the -// server or in response to a registration request). -message RegistrationStatus { - optional RegistrationP registration = 1; - optional StatusP status = 2; -} - -// Registration status of several messages from the server to the client. -message RegistrationStatusMessage { - repeated RegistrationStatus registration_status = 1; -} - -// Request from the server to get the registration info from the client for -// sync purposes. -message RegistrationSyncRequestMessage { -} - -// A set of invalidations from the client to the server or vice-versa -message InvalidationMessage { - repeated InvalidationP invalidation = 1; -} - -// A request from the server to the client for information such as -// performance counters, client os, etc -message InfoRequestMessage { - enum InfoType { - GET_PERFORMANCE_COUNTERS = 1; - } - repeated InfoType info_type = 1; -} - -// A rate limit: a count of events and a window duration in which the events -// may occur. -message RateLimitP { - - // The size of the window over which the rate limit applies. - optional int32 window_ms = 1; - - // The number of events allowed within a given window. - optional int32 count = 2; -} - -// Configuration parameters for the protocol handler in the Ticl. -message ProtocolHandlerConfigP { - // Batching delay - certain messages (e.g., registrations, invalidation acks) - // are sent to the server after this delay. - optional int32 batching_delay_ms = 1 [default = 500]; - - // Rate limits for sending messages. Only two levels allowed currently. - repeated RateLimitP rate_limit = 2; -} - -// Configuration parameters for the Ticl. -message ClientConfigP { - - optional Version version = 1; - - // The delay after which a network message sent to the server is considered - // timed out. - optional int32 network_timeout_delay_ms = 2 [default = 60000]; - - // Retry delay for a persistent write if it fails - optional int32 write_retry_delay_ms = 3 [default = 10000]; - - // Delay for sending heartbeats to the server. - optional int32 heartbeat_interval_ms = 4 [default = 1200000]; - - // Delay after which performance counters are sent to the server. - optional int32 perf_counter_delay_ms = 5 [default = 21600000]; // 6 hours. - - // The maximum exponential backoff factor used for network and persistence - /// timeouts. - optional int32 max_exponential_backoff_factor = 6 [default = 500]; - - // Smearing percent for randomizing delays. - optional int32 smear_percent = 7 [default = 20]; - - // Whether the client is transient, that is, does not write its session - // token to durable storage. - // TODO(xiaolan): (BUG 5627144) need to expose to the clients. - // For android the default is false. But for mtrx the default is true. - optional bool is_transient = 8 [default = false]; - - // Initial delay for a heartbeat after restarting from persistent state. We - // use this so that the application has a chance to respond to the - // reissueRegistrations call. - optional int32 initial_persistent_heartbeat_delay_ms = 9 [default = 2000]; - - // Configuration for the protocol client to control batching etc. - optional ProtocolHandlerConfigP protocol_handler_config = 10; - - // Whether the channel supports delivery while the client is offline. If - // true, then the servers' use of the channel is such that the - // following holds: if any number of messages are sent to the client while - // the client is unreachable, then the channel will eventually deliver at - // least one message to the client such that, on receiving the message, the - // client will send a message to the server. E.g., the channel could deliver - // a single invalidation or a single registration sync request. C2DM is - // an example of a suitable channel. - // - // When this is true, the Ticl will record in persistent storage the last - // time it sent a message to the server. On persistent restart, it will not - // send a message to the server unless the last one was sent more than a - // heartbeat-interval ago. This is designed to support efficient Android - // clients, which will destroy and recreate the Ticl when transitioning - // between foreground and background states. - optional bool channel_supports_offline_delivery = 11 [default = false]; - - // If the client loses network connectivity, it will send a heartbeat after it - // comes online, unless it had already sent a message more recently than this - // threshold. - optional int32 offline_heartbeat_threshold_ms = 12 [default = 60000]; - - // Whether the client allows suppression. If true (the default), then - // both continuous and restarted invalidations result in an invalidate() - // upcall, which is appropriate for invalidation clients. If false, - // then restarted invalidations result in an invalidateUnknownVersion() - // upcall, which provides correct semantics for Trickles clients. - optional bool allow_suppression = 13 [default = true]; -} - -// A message asking the client to change its configuration parameters -message ConfigChangeMessage { - - // On receipt of this value, do not send any new message to the server - // for the specified delay (this message needs to be accepted without - // any token check). A zero value is ignored by the client. So the lowest - // value for this field is 1. This concept exists to allow the server - // to tell the clients that they should not come back to the server - // for some period of time. - optional int64 next_message_delay_ms = 1; -} - -// An error message that contains an enum for different types of failures with a -// textual description of the failure (as the need arises new error codes will -// be added to this message). -message ErrorMessage { - - enum Code { - AUTH_FAILURE = 1; // Authorization or authentication failure. - UNKNOWN_FAILURE = 10000; // Some failure which is not described above. - }; - - optional Code code = 1; - - // Textual description of the error - optional string description = 2; -} diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_test_internal.proto b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_test_internal.proto deleted file mode 100644 index 4f8bfa93ccfc8bead8bb9cd0214c1d5b6336750f..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/client_test_internal.proto +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Specification of protocol buffers that are used only on the client side for -// testing. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package ipc.invalidation; - -import "client_protocol.proto"; - -// Registration manager state -message RegistrationManagerStateP { - optional RegistrationSummary client_summary = 1; - optional RegistrationSummary server_summary = 2; - repeated ObjectIdP registered_objects = 3; -} diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/callback.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/callback.h deleted file mode 100644 index 80670d8f370c6f3863237cd60a594bc94efdb0d7..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/callback.h +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Defines callback types for the invalidation client library. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_CALLBACK_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_CALLBACK_H_ - -#include "base/callback.h" - -#define INVALIDATION_CALLBACK1_TYPE(Arg1) ::Callback1<Arg1> - -namespace invalidation { - -using ::Closure; -using ::DoNothing; -using ::NewPermanentCallback; - -template <class T> -bool IsCallbackRepeatable(const T* callback) { - return callback->IsRepeatable(); -} - -// Encapsulates a callback and its argument. Deletes the inner callback when it -// is itself deleted, regardless of whether it is ever run. -template<typename ArgumentType> -class CallbackWrapper : public Closure { - public: - // Constructs a new CallbackWrapper, which takes ownership of the inner - // callback. - CallbackWrapper( - INVALIDATION_CALLBACK1_TYPE(ArgumentType)* callback, ArgumentType arg) : - callback_(callback), arg_(arg) {} - - virtual ~CallbackWrapper() { - delete callback_; - } - - // Returns whether the inner callback is repeatable. - virtual bool IsRepeatable() const { - return callback_->IsRepeatable(); - } - - // Runs the inner callback on the argument. - virtual void Run() { - callback_->Run(arg_); - } - - private: - // The callback to run. - INVALIDATION_CALLBACK1_TYPE(ArgumentType)* callback_; - // The argument on which to run it. - ArgumentType arg_; -}; - -// An override of NewPermanentCallback that wraps a callback and its argument, -// transferring ownership of the inner callback to the new one. We define this -// here (in deps/callback.h), along with the class above, because the Google -// implementation of callbacks is much different from the one used in Chrome. A -// Chrome Closure's destructor and Run() method are not virtual, so we can't -// define custom implementations (as above in CallbackWrapper) to get the -// semantics and memory management behavior we want. -template <typename ArgType> -Closure* NewPermanentCallback( - INVALIDATION_CALLBACK1_TYPE(ArgType)* callback, ArgType arg) { - return new CallbackWrapper<ArgType>(callback, arg); -} - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_CALLBACK_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/digest-function.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/digest-function.h deleted file mode 100644 index 6e00f5ba5aa471b3ac627281a11de400f00e2311..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/digest-function.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Interface specifying a function to compute digests. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_DIGEST_FUNCTION_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_DIGEST_FUNCTION_H_ - -#include <string> - -#include "google/cacheinvalidation/deps/stl-namespace.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::string; - -class DigestFunction { - public: - virtual ~DigestFunction() {} - - /* Clears the digest state. */ - virtual void Reset() = 0; - - /* Adds data to the digest being computed. */ - virtual void Update(const string& data) = 0; - - /* Stores the digest of the data added by Update. After this call has been - * made, reset must be called before Update and GetDigest can be called. - */ - virtual string GetDigest() = 0; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_DIGEST_FUNCTION_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/gmock.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/gmock.h deleted file mode 100644 index 777bfec2d76d8b6e3169afee43ba06e04db3be53..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/gmock.h +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_GMOCK_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_GMOCK_H_ - -#error Replace with a header that imports the Google Mock library. - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_GMOCK_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/googletest.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/googletest.h deleted file mode 100644 index a0e649283610c161bb618ca7d6ac369dabbe2a41..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/googletest.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_GOOGLETEST_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_GOOGLETEST_H_ - -#error This file should be replaced with a stub pointing to the googletest \ - header. - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_GOOGLETEST_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/logging.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/logging.h deleted file mode 100644 index 5639774ac93ad569f16a00f4ac85529b9b7042fe..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/logging.h +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_LOGGING_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_LOGGING_H_ - -#error This file should be replaced with a stub pointing to the google-glog \ - header. Also there should be a LogMessage() function in the invalidation \ - namespace. - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_LOGGING_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/mutex.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/mutex.h deleted file mode 100644 index f78c759b7db447dfd91dbf5738913a4be933efa2..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/mutex.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_MUTEX_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_MUTEX_H_ - -#include "base/mutex.h" - -namespace invalidation { - -using ::Mutex; -using ::MutexLock; -} // invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_MUTEX_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/random.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/random.h deleted file mode 100644 index 3d3d67da53fbea9c9e278f9c4cdceb82ed5a9ddc..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/random.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_RANDOM_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_RANDOM_H_ - -#error This file should be replaced with an implementation of the following \ - interface. - -namespace invalidation { - -class Random { - public: - explicit Random(int64 seed); - - // Returns a pseudorandom value between 0 (inclusive) and 1 (exclusive). - virtual double RandDouble(); - - // Returns a pseudorandom unsigned 64-bit number. - virtual uint64 RandUint64(); -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_RANDOM_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/scoped_ptr.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/scoped_ptr.h deleted file mode 100644 index 91f415b6a99dcec7f8b7b8738f0ab94ddd556f99..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/scoped_ptr.h +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_SCOPED_PTR_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_SCOPED_PTR_H_ - -#error Override scoped_ptr.h to point to a scoped_ptr implementation. - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_SCOPED_PTR_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/sha1-digest-function.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/sha1-digest-function.h deleted file mode 100644 index ed4b7faad3560ad1280d26c8957e169e0ae08fea..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/sha1-digest-function.h +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Interface to SHA1 digest computation. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_SHA1_DIGEST_FUNCTION_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_SHA1_DIGEST_FUNCTION_H_ - -#error Replace this file with an implementation of DigestFunction based on SHA1. - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_SHA1_DIGEST_FUNCTION_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/stl-namespace.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/stl-namespace.h deleted file mode 100644 index e05bcb47f2ba338455bb1c2a0412086a389a74cf..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/stl-namespace.h +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_STL_NAMESPACE_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_STL_NAMESPACE_H_ - -// Google style is to use the global namespace for stl classes so we -// leave this blank. -#define INVALIDATION_STL_NAMESPACE - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_STL_NAMESPACE_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/string_util.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/string_util.h deleted file mode 100644 index 8f03ca3b135fbccdb53ef9e4a93361d9dd4bf864..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/string_util.h +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_STRING_UTIL_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_STRING_UTIL_H_ - -#error This file should be replaced with a stub pointing to a file \ - containing string utility functions in the invalidation namespace. \ - At least StringAppendV() StringPrintf(), and IntToString() are needed. - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_STRING_UTIL_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/time.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/time.h deleted file mode 100644 index 070b1fe5b1b0a61d1da3159828f48aa9de1a6b57..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/deps/time.h +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GOOGLE_CACHEINVALIDATION_DEPS_TIME_H_ -#define GOOGLE_CACHEINVALIDATION_DEPS_TIME_H_ - -#error This file should be replaced with a stub pointing to something \ - like base/time.h from the Chromium source tree, with definitions for types \ - Time, TimeDelta, etc. - -#endif // GOOGLE_CACHEINVALIDATION_DEPS_TIME_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/basic-system-resources.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/basic-system-resources.cc deleted file mode 100644 index 0b2c24f25596dc5d167c24fd598ffd7aa4349399..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/basic-system-resources.cc +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "google/cacheinvalidation/impl/basic-system-resources.h" - -namespace invalidation { - -BasicSystemResources::BasicSystemResources( - Logger* logger, Scheduler* internal_scheduler, - Scheduler* listener_scheduler, NetworkChannel* network, - Storage* storage, const string& platform) - : logger_(logger), - internal_scheduler_(internal_scheduler), - listener_scheduler_(listener_scheduler), - network_(network), - storage_(storage), - platform_(platform) { - logger_->SetSystemResources(this); - internal_scheduler_->SetSystemResources(this); - listener_scheduler_->SetSystemResources(this); - network_->SetSystemResources(this); - storage_->SetSystemResources(this); -} - -BasicSystemResources::~BasicSystemResources() { -} - -void BasicSystemResources::Start() { - CHECK(!run_state_.IsStarted()) << "resources already started"; - - // TODO(ghc): Investigate whether we should have Start() and Stop() methods - // on components like the scheduler. Otherwise, the resources can't start and - // stop them ... - run_state_.Start(); -} - -void BasicSystemResources::Stop() { - CHECK(run_state_.IsStarted()) << "cannot stop resources that aren't started"; - CHECK(!run_state_.IsStopped()) << "resources already stopped"; - run_state_.Stop(); -} - -bool BasicSystemResources::IsStarted() const { - return run_state_.IsStarted(); -} - -Logger* BasicSystemResources::logger() { - return logger_.get(); -} - -Scheduler* BasicSystemResources::internal_scheduler() { - return internal_scheduler_.get(); -} - -Scheduler* BasicSystemResources::listener_scheduler() { - return listener_scheduler_.get(); -} - -NetworkChannel* BasicSystemResources::network() { - return network_.get(); -} - -Storage* BasicSystemResources::storage() { - return storage_.get(); -} - -string BasicSystemResources::platform() const { - return platform_; -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/basic-system-resources.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/basic-system-resources.h deleted file mode 100644 index 8fc1a2958d8273033432ef869c6b547d3ac6b15f..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/basic-system-resources.h +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// A simple implementation of SystemResources that just takes the resource -// components and constructs a SystemResources object. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_BASIC_SYSTEM_RESOURCES_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_BASIC_SYSTEM_RESOURCES_H_ - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/deps/scoped_ptr.h" -#include "google/cacheinvalidation/impl/run-state.h" - -namespace invalidation { - -class BasicSystemResources : public SystemResources { - public: - // Constructs an instance from resource components. Ownership of all - // components is transferred to the BasicSystemResources object. - BasicSystemResources( - Logger* logger, Scheduler* internal_scheduler, - Scheduler* listener_scheduler, NetworkChannel* network, - Storage* storage, const string& platform); - - virtual ~BasicSystemResources(); - - // Overrides from SystemResources. - virtual void Start(); - virtual void Stop(); - virtual bool IsStarted() const; - - virtual Logger* logger(); - virtual Scheduler* internal_scheduler(); - virtual Scheduler* listener_scheduler(); - virtual NetworkChannel* network(); - virtual Storage* storage(); - virtual string platform() const; - - private: - // Components comprising the system resources. We delegate calls to these as - // appropriate. - scoped_ptr<Logger> logger_; - scoped_ptr<Scheduler> internal_scheduler_; - scoped_ptr<Scheduler> listener_scheduler_; - scoped_ptr<NetworkChannel> network_; - scoped_ptr<Storage> storage_; - - // The state of the resources. - RunState run_state_; - - // Information about the client operating system/platform. - string platform_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_BASIC_SYSTEM_RESOURCES_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/build_constants.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/build_constants.h deleted file mode 100644 index 156b4949916067422d1b38d833942bd2dd8648d0..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/build_constants.h +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2013 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Build constant definitions - -#ifndef INVALIDATION_BUILD_CONSTANTS_H_ -#define INVALIDATION_BUILD_CONSTANTS_H_ -namespace invalidation { -const int BUILD_DATESTAMP = 20140204; -} // namespace invalidation -#endif // INVALIDATION_BUILD_CONSTANTS_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/checking-invalidation-listener.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/checking-invalidation-listener.cc deleted file mode 100644 index af5a4e5ed5d944f31822d77d3bb1f841fcbc8459..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/checking-invalidation-listener.cc +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// InvalidationListener wrapper that ensures that a delegate listener is called -// on the proper thread and calls the listener method on the listener thread. - -#include "google/cacheinvalidation/impl/checking-invalidation-listener.h" -#include "google/cacheinvalidation/impl/log-macro.h" - -namespace invalidation { - -CheckingInvalidationListener::CheckingInvalidationListener( - InvalidationListener* delegate, Statistics* statistics, - Scheduler* internal_scheduler, Scheduler* listener_scheduler, - Logger* logger) - : delegate_(delegate), - statistics_(statistics), - internal_scheduler_(internal_scheduler), - listener_scheduler_(listener_scheduler), - logger_(logger) { - CHECK(delegate != NULL); - CHECK(statistics != NULL); - CHECK(internal_scheduler_ != NULL); - CHECK(listener_scheduler != NULL); - CHECK(logger != NULL); -} - -void CheckingInvalidationListener::Invalidate( - InvalidationClient* client, const Invalidation& invalidation, - const AckHandle& ack_handle) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - statistics_->RecordListenerEvent(Statistics::ListenerEventType_INVALIDATE); - listener_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - delegate_, &InvalidationListener::Invalidate, client, invalidation, - ack_handle)); -} - -void CheckingInvalidationListener::InvalidateUnknownVersion( - InvalidationClient* client, const ObjectId& object_id, - const AckHandle& ack_handle) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - statistics_->RecordListenerEvent( - Statistics::ListenerEventType_INVALIDATE_UNKNOWN); - listener_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - delegate_, &InvalidationListener::InvalidateUnknownVersion, client, - object_id, ack_handle)); -} - -void CheckingInvalidationListener::InvalidateAll( - InvalidationClient* client, const AckHandle& ack_handle) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - statistics_->RecordListenerEvent( - Statistics::ListenerEventType_INVALIDATE_ALL); - listener_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - delegate_, &InvalidationListener::InvalidateAll, client, - ack_handle)); -} - -void CheckingInvalidationListener::InformRegistrationFailure( - InvalidationClient* client, const ObjectId& object_id, - bool is_transient, const string& error_message) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - statistics_->RecordListenerEvent( - Statistics::ListenerEventType_INFORM_REGISTRATION_FAILURE); - listener_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - delegate_, &InvalidationListener::InformRegistrationFailure, client, - object_id, is_transient, error_message)); -} - -void CheckingInvalidationListener::InformRegistrationStatus( - InvalidationClient* client, const ObjectId& object_id, - RegistrationState reg_state) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - statistics_->RecordListenerEvent( - Statistics::ListenerEventType_INFORM_REGISTRATION_STATUS); - listener_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - delegate_, &InvalidationListener::InformRegistrationStatus, client, - object_id, reg_state)); -} - -void CheckingInvalidationListener::ReissueRegistrations( - InvalidationClient* client, const string& prefix, int prefix_len) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - statistics_->RecordListenerEvent( - Statistics::ListenerEventType_REISSUE_REGISTRATIONS); - listener_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - delegate_, &InvalidationListener::ReissueRegistrations, - client, prefix, prefix_len)); -} - -void CheckingInvalidationListener::InformError( - InvalidationClient* client, const ErrorInfo& error_info) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - statistics_->RecordListenerEvent( - Statistics::ListenerEventType_INFORM_ERROR); - listener_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - delegate_, &InvalidationListener::InformError, client, error_info)); -} - -void CheckingInvalidationListener::Ready(InvalidationClient* client) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - TLOG(logger_, INFO, "Informing app that ticl is ready"); - listener_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback(delegate_, &InvalidationListener::Ready, client)); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/checking-invalidation-listener.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/checking-invalidation-listener.h deleted file mode 100644 index 4c82e03115514993bd6ebe03581b7c10f1d02330..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/checking-invalidation-listener.h +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// InvalidationListener wrapper that ensures that a delegate listener is called -// on the proper thread and calls the listener method on the listener thread. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_CHECKING_INVALIDATION_LISTENER_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_CHECKING_INVALIDATION_LISTENER_H_ - -#include "google/cacheinvalidation/include/invalidation-client.h" -#include "google/cacheinvalidation/include/invalidation-listener.h" -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/include/types.h" -#include "google/cacheinvalidation/impl/statistics.h" - -namespace invalidation { - -class CheckingInvalidationListener : public InvalidationListener { - public: - CheckingInvalidationListener( - InvalidationListener* delegate, Statistics* statistics, - Scheduler* internal_scheduler, Scheduler* listener_scheduler, - Logger* logger); - - virtual ~CheckingInvalidationListener() {} - - virtual void Invalidate( - InvalidationClient* client, const Invalidation& invalidation, - const AckHandle& ack_handle); - - virtual void InvalidateUnknownVersion( - InvalidationClient* client, const ObjectId& object_id, - const AckHandle& ack_handle); - - virtual void InvalidateAll( - InvalidationClient* client, const AckHandle& ack_handle); - - virtual void InformRegistrationFailure( - InvalidationClient* client, const ObjectId& object_id, - bool is_transient, const string& error_message); - - virtual void InformRegistrationStatus( - InvalidationClient* client, const ObjectId& object_id, - RegistrationState reg_state); - - virtual void ReissueRegistrations( - InvalidationClient* client, const string& prefix, int prefix_len); - - virtual void InformError( - InvalidationClient* client, const ErrorInfo& error_info); - - /* Returns the delegate InvalidationListener. */ - InvalidationListener* delegate() { - return delegate_; - } - - virtual void Ready(InvalidationClient* client); - - private: - /* The actual listener to which this listener delegates. */ - InvalidationListener* delegate_; - - /* Statistics objects to track number of sent messages, etc. */ - Statistics* statistics_; - - /* The scheduler for scheduling internal events in the library. */ - Scheduler* internal_scheduler_; - - /* The scheduler for scheduling events for the delegate. */ - Scheduler* listener_scheduler_; - - Logger* logger_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_CHECKING_INVALIDATION_LISTENER_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/client-protocol-namespace-fix.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/client-protocol-namespace-fix.h deleted file mode 100644 index 9366a392313683489d9c1ee7af807d9e3ecd30d9..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/client-protocol-namespace-fix.h +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Brings invalidation client protocol buffers into invalidation namespace. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_CLIENT_PROTOCOL_NAMESPACE_FIX_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_CLIENT_PROTOCOL_NAMESPACE_FIX_H_ - -#include "google/cacheinvalidation/client.pb.h" -#include "google/cacheinvalidation/client_protocol.pb.h" -#include "google/cacheinvalidation/types.pb.h" -#include "google/cacheinvalidation/impl/repeated-field-namespace-fix.h" - -namespace invalidation { - -// Client -using ::ipc::invalidation::PersistentStateBlob; -using ::ipc::invalidation::PersistentTiclState; - -// ClientProtocol -using ::ipc::invalidation::AckHandleP; -using ::ipc::invalidation::ApplicationClientIdP; -using ::ipc::invalidation::ClientConfigP; -using ::ipc::invalidation::ClientHeader; -using ::ipc::invalidation::ClientVersion; -using ::ipc::invalidation::ClientToServerMessage; -using ::ipc::invalidation::ConfigChangeMessage; -using ::ipc::invalidation::ErrorMessage; -using ::ipc::invalidation::ErrorMessage_Code_AUTH_FAILURE; -using ::ipc::invalidation::ErrorMessage_Code_UNKNOWN_FAILURE; -using ::ipc::invalidation::InfoMessage; -using ::ipc::invalidation::InfoRequestMessage; -using ::ipc::invalidation::InfoRequestMessage_InfoType; -using ::ipc::invalidation::InfoRequestMessage_InfoType_GET_PERFORMANCE_COUNTERS; -using ::ipc::invalidation::InitializeMessage; -using ::ipc::invalidation::InitializeMessage_DigestSerializationType_BYTE_BASED; -using ::ipc::invalidation::InitializeMessage_DigestSerializationType_NUMBER_BASED; -using ::ipc::invalidation::InvalidationMessage; -using ::ipc::invalidation::InvalidationP; -using ::ipc::invalidation::ObjectIdP; -using ::ipc::invalidation::PropertyRecord; -using ::ipc::invalidation::ProtocolHandlerConfigP; -using ::ipc::invalidation::ProtocolVersion; -using ::ipc::invalidation::RateLimitP; -using ::ipc::invalidation::RegistrationMessage; -using ::ipc::invalidation::RegistrationP; -using ::ipc::invalidation::RegistrationP_OpType_REGISTER; -using ::ipc::invalidation::RegistrationP_OpType_UNREGISTER; -using ::ipc::invalidation::RegistrationMessage; -using ::ipc::invalidation::RegistrationStatus; -using ::ipc::invalidation::RegistrationStatusMessage; -using ::ipc::invalidation::RegistrationSubtree; -using ::ipc::invalidation::RegistrationSummary; -using ::ipc::invalidation::RegistrationSyncMessage; -using ::ipc::invalidation::RegistrationSyncRequestMessage; -using ::ipc::invalidation::ServerHeader; -using ::ipc::invalidation::ServerToClientMessage; -using ::ipc::invalidation::StatusP; -using ::ipc::invalidation::StatusP_Code_SUCCESS; -using ::ipc::invalidation::StatusP_Code_PERMANENT_FAILURE; -using ::ipc::invalidation::StatusP_Code_TRANSIENT_FAILURE; -using ::ipc::invalidation::TokenControlMessage; -using ::ipc::invalidation::Version; - -// Types -using ::ipc::invalidation::ObjectSource_Type_INTERNAL; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_CLIENT_PROTOCOL_NAMESPACE_FIX_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/constants.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/constants.cc deleted file mode 100644 index e090648d3e0481e38ba953e5a78bfef08d11cc25..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/constants.cc +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Various constants common to clients and servers used in version 2 of the -// Ticl. - -#include "google/cacheinvalidation/impl/build_constants.h" -#include "google/cacheinvalidation/impl/constants.h" - -namespace invalidation { - -const int Constants::kClientMajorVersion = 3; -const int Constants::kClientMinorVersion = BUILD_DATESTAMP; -const int Constants::kProtocolMajorVersion = 3; -const int Constants::kProtocolMinorVersion = 2; -const int Constants::kConfigMajorVersion = 3; -const int Constants::kConfigMinorVersion = 2; -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/constants.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/constants.h deleted file mode 100644 index bb604d7617bad646be401998ffa5804707a672a5..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/constants.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Various constants common to clients and servers used in version 2 of the -// Ticl. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_CONSTANTS_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_CONSTANTS_H_ - -namespace invalidation { - -class Constants { - public: - /* Major version of the client library. */ - static const int kClientMajorVersion; - - /* Minor version of the client library, defined to be equal to the datestamp - * of the build (e.g. 20130401). - */ - static const int kClientMinorVersion; - - /* Major version of the protocol between the client and the server. */ - static const int kProtocolMajorVersion; - - /* Minor version of the protocol between the client and the server. */ - static const int kProtocolMinorVersion; - - /* Major version of the client config. */ - static const int kConfigMajorVersion; - - /* Minor version of the client config. */ - static const int kConfigMinorVersion; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_CONSTANTS_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/digest-store.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/digest-store.h deleted file mode 100644 index b81701efb726bbde56e19e1721d55af37b399d2f..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/digest-store.h +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Interface for a store that allows objects to be added/removed along with the -// ability to get the digest for the whole or partial set of those objects. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_DIGEST_STORE_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_DIGEST_STORE_H_ - -#include <vector> - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::vector; - -template<typename ElementType> -class DigestStore { - public: - virtual ~DigestStore() {} - - /* Returns the number of elements. */ - virtual int size() = 0; - - /* Returns whether element is in the store. */ - virtual bool Contains(const ElementType& element) = 0; - - /* Returns a digest of the desired objects in 'digest'. - * - * NOTE: the digest computations MUST NOT depend on the order in which the - * elements were added. - */ - virtual string GetDigest() = 0; - - /* Stores iterators bounding the elements whose digest prefixes begin with the - * bit prefix digest_prefix. prefix_len is the length of digest_prefix in - * bits, which may be less than digest_prefix.length (and may be 0). The - * implementing class can return *more* objects than what has been specified - * by digest_prefix, e.g., it could return all the objects in the store. - */ - virtual void GetElements(const string& digest_prefix, int prefix_len, - vector<ObjectIdP>* result) = 0; - - /* Adds element to the store. No-op if element is already present. - * Returns whether the element was added. - */ - virtual bool Add(const ElementType& element) = 0; - - /* Adds elements to the store. If any element in elements is already present, - * the addition is a no-op for that element. When the function returns, - * added_elements will have been modified to contain all the elements - * of elements that were not previously present. - */ - virtual void Add(const vector<ElementType>& elements, - vector<ElementType>* added_elements) = 0; - - /* Removes element from the store. No-op if element is not present. - * Returns whether the element was removed. - */ - virtual bool Remove(const ElementType& element) = 0; - - /* Remove elements from the store. If any element in element is not present, - * the removal is a no-op for that element. - * When the function returns, removed_elements will have been modified to - * contain all the elements of elements that were previously present - */ - virtual void Remove(const vector<ElementType>& elements, - vector<ElementType>* removed_elements) = 0; - - /* Removes all elements in this and stores them in elements. */ - virtual void RemoveAll(vector<ElementType>* elements) = 0; - - /* Returns a string representation of this digest store. */ - virtual string ToString() = 0; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_DIGEST_STORE_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/exponential-backoff-delay-generator.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/exponential-backoff-delay-generator.cc deleted file mode 100644 index eac021854985ed93aeeaf616395effa1df2e9596..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/exponential-backoff-delay-generator.cc +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "google/cacheinvalidation/impl/exponential-backoff-delay-generator.h" - -namespace invalidation { - -TimeDelta ExponentialBackoffDelayGenerator::GetNextDelay() { - TimeDelta delay = Scheduler::NoDelay(); // After a reset, delay is zero. - if (in_retry_mode) { - // We used to multiply the current_max_delay_ by the double, but this - // implicitly truncated the double to an integer, which would always be 0. - // By converting to and from milliseconds, we avoid this problem. - delay = TimeDelta::FromMilliseconds( - random_->RandDouble() * current_max_delay_.InMilliseconds()); - - // Adjust the max for the next run. - TimeDelta max_delay = initial_max_delay_ * max_exponential_factor_; - if (current_max_delay_ <= max_delay) { // Guard against overflow. - current_max_delay_ *= 2; - if (current_max_delay_ > max_delay) { - current_max_delay_ = max_delay; - } - } - } - in_retry_mode = true; - return delay; -} -} diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/exponential-backoff-delay-generator.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/exponential-backoff-delay-generator.h deleted file mode 100644 index cf36a66b14f45437d0d43469cfb3f7bba6b81a9d..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/exponential-backoff-delay-generator.h +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Class that generates successive intervals for random exponential backoff. -// Class tracks a "high water mark" which is doubled each time getNextDelay is -// called; each call to getNextDelay returns a value uniformly randomly -// distributed between 0 (inclusive) and the high water mark (exclusive). Note -// that this class does not dictate the time units for which the delay is -// computed. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_EXPONENTIAL_BACKOFF_DELAY_GENERATOR_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_EXPONENTIAL_BACKOFF_DELAY_GENERATOR_H_ - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/deps/scoped_ptr.h" -#include "google/cacheinvalidation/deps/logging.h" -#include "google/cacheinvalidation/deps/time.h" -#include "google/cacheinvalidation/deps/random.h" -#include "google/cacheinvalidation/impl/constants.h" - -namespace invalidation { - -class ExponentialBackoffDelayGenerator { - public: - /* Creates a generator with the given maximum and initial delays. - * Caller continues to own space for random. - */ - ExponentialBackoffDelayGenerator(Random* random, TimeDelta initial_max_delay, - int max_exponential_factor) : - initial_max_delay_(initial_max_delay), - max_exponential_factor_(max_exponential_factor), random_(random) { - CHECK_GT(max_exponential_factor_, 0) << "max factor must be positive"; - CHECK(random_ != NULL); - CHECK(initial_max_delay > Scheduler::NoDelay()) << - "Initial delay must be positive"; - Reset(); - } - - /* Resets the exponential backoff generator to start delays at the initial - * delay. - */ - void Reset() { - current_max_delay_ = initial_max_delay_; - in_retry_mode = false; - } - - /* Gets the next delay interval to use. */ - TimeDelta GetNextDelay(); - - private: - /* Initial delay time to use. */ - TimeDelta initial_max_delay_; - - /* Maximum allowed delay time. */ - int max_exponential_factor_; - - /* Next delay time to use. */ - TimeDelta current_max_delay_; - - /* If the first call to getNextDelay has been made after reset. */ - bool in_retry_mode; - - Random* random_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_EXPONENTIAL_BACKOFF_DELAY_GENERATOR_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-core.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-core.cc deleted file mode 100644 index f8e637dd16d1e9a6cc39da891d19272b2c4bdb91..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-core.cc +++ /dev/null @@ -1,1009 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Implementation of the Invalidation Client Library (Ticl). - -#include "google/cacheinvalidation/impl/invalidation-client-core.h" - -#include <sstream> - -#include "google/cacheinvalidation/client_test_internal.pb.h" -#include "google/cacheinvalidation/deps/callback.h" -#include "google/cacheinvalidation/deps/random.h" -#include "google/cacheinvalidation/deps/sha1-digest-function.h" -#include "google/cacheinvalidation/deps/string_util.h" -#include "google/cacheinvalidation/impl/exponential-backoff-delay-generator.h" -#include "google/cacheinvalidation/impl/invalidation-client-util.h" -#include "google/cacheinvalidation/impl/log-macro.h" -#include "google/cacheinvalidation/impl/persistence-utils.h" -#include "google/cacheinvalidation/impl/proto-converter.h" -#include "google/cacheinvalidation/impl/proto-helpers.h" -#include "google/cacheinvalidation/impl/recurring-task.h" -#include "google/cacheinvalidation/impl/smearer.h" - -namespace invalidation { - -using ::ipc::invalidation::RegistrationManagerStateP; - -const char* InvalidationClientCore::kClientTokenKey = "ClientToken"; - -// AcquireTokenTask - -AcquireTokenTask::AcquireTokenTask(InvalidationClientCore* client) - : RecurringTask( - "AcquireToken", - client->internal_scheduler_, - client->logger_, - &client->smearer_, - client->CreateExpBackOffGenerator(TimeDelta::FromMilliseconds( - client->config_.network_timeout_delay_ms())), - Scheduler::NoDelay(), - TimeDelta::FromMilliseconds( - client->config_.network_timeout_delay_ms())), - client_(client) { - } - -bool AcquireTokenTask::RunTask() { - // If token is still not assigned (as expected), sends a request. - // Otherwise, ignore. - if (client_->client_token_.empty()) { - // Allocate a nonce and send a message requesting a new token. - client_->set_nonce( - InvalidationClientCore::GenerateNonce(client_->random_.get())); - - client_->protocol_handler_.SendInitializeMessage( - client_->application_client_id_, client_->nonce_, - client_->batching_task_.get(), - "AcquireToken"); - // Reschedule to check state, retry if necessary after timeout. - return true; - } else { - return false; // Don't reschedule. - } -} - -// RegSyncHeartbeatTask - -RegSyncHeartbeatTask::RegSyncHeartbeatTask(InvalidationClientCore* client) - : RecurringTask( - "RegSyncHeartbeat", - client->internal_scheduler_, - client->logger_, - &client->smearer_, - client->CreateExpBackOffGenerator(TimeDelta::FromMilliseconds( - client->config_.network_timeout_delay_ms())), - TimeDelta::FromMilliseconds( - client->config_.network_timeout_delay_ms()), - TimeDelta::FromMilliseconds( - client->config_.network_timeout_delay_ms())), - client_(client) { -} - -bool RegSyncHeartbeatTask::RunTask() { - if (!client_->registration_manager_.IsStateInSyncWithServer()) { - // Simply send an info message to ensure syncing happens. - TLOG(client_->logger_, INFO, "Registration state not in sync with " - "server: %s", client_->registration_manager_.ToString().c_str()); - client_->SendInfoMessageToServer(false, true /* request server summary */); - return true; - } else { - TLOG(client_->logger_, INFO, "Not sending message since state is in sync"); - return false; - } -} - -// PersistentWriteTask - -PersistentWriteTask::PersistentWriteTask(InvalidationClientCore* client) - : RecurringTask( - "PersistentWrite", - client->internal_scheduler_, - client->logger_, - &client->smearer_, - client->CreateExpBackOffGenerator(TimeDelta::FromMilliseconds( - client->config_.write_retry_delay_ms())), - Scheduler::NoDelay(), - TimeDelta::FromMilliseconds( - client->config_.write_retry_delay_ms())), - client_(client) { -} - -bool PersistentWriteTask::RunTask() { - if (client_->client_token_.empty() || - (client_->client_token_ == last_written_token_)) { - // No work to be done - return false; // Do not reschedule - } - - // Persistent write needs to happen. - PersistentTiclState state; - state.set_client_token(client_->client_token_); - string serialized_state; - PersistenceUtils::SerializeState(state, client_->digest_fn_.get(), - &serialized_state); - client_->storage_->WriteKey(InvalidationClientCore::kClientTokenKey, - serialized_state, - NewPermanentCallback(this, &PersistentWriteTask::WriteCallback, - client_->client_token_)); - return true; // Reschedule after timeout to make sure that write does happen. -} - -void PersistentWriteTask::WriteCallback(const string& token, Status status) { - TLOG(client_->logger_, INFO, "Write state completed: %d, %s", - status.IsSuccess(), status.message().c_str()); - if (status.IsSuccess()) { - // Set lastWrittenToken to be the token that was written (NOT client_token_: - // which could have changed while the write was happening). - last_written_token_ = token; - } else { - client_->statistics_->RecordError( - Statistics::ClientErrorType_PERSISTENT_WRITE_FAILURE); - } -} - -// HeartbeatTask - -HeartbeatTask::HeartbeatTask(InvalidationClientCore* client) - : RecurringTask( - "Heartbeat", - client->internal_scheduler_, - client->logger_, - &client->smearer_, - NULL, - TimeDelta::FromMilliseconds( - client->config_.heartbeat_interval_ms()), - Scheduler::NoDelay()), - client_(client) { - next_performance_send_time_ = client_->internal_scheduler_->GetCurrentTime() + - smearer()->GetSmearedDelay(TimeDelta::FromMilliseconds( - client_->config_.perf_counter_delay_ms())); -} - -bool HeartbeatTask::RunTask() { - // Send info message. If needed, send performance counters and reset the next - // performance counter send time. - TLOG(client_->logger_, INFO, "Sending heartbeat to server: %s", - client_->ToString().c_str()); - Scheduler *scheduler = client_->internal_scheduler_; - bool must_send_perf_counters = - next_performance_send_time_ > scheduler->GetCurrentTime(); - if (must_send_perf_counters) { - next_performance_send_time_ = scheduler->GetCurrentTime() + - client_->smearer_.GetSmearedDelay(TimeDelta::FromMilliseconds( - client_->config_.perf_counter_delay_ms())); - } - - TLOG(client_->logger_, INFO, "Sending heartbeat to server: %s", - client_->ToString().c_str()); - client_->SendInfoMessageToServer(must_send_perf_counters, - !client_->registration_manager_.IsStateInSyncWithServer()); - return true; // Reschedule. -} - -BatchingTask::BatchingTask( - ProtocolHandler *handler, Smearer* smearer, TimeDelta batching_delay) - : RecurringTask( - "Batching", handler->internal_scheduler_, handler->logger_, smearer, - NULL, batching_delay, Scheduler::NoDelay()), - protocol_handler_(handler) { -} - -bool BatchingTask::RunTask() { - // Send message to server - the batching information is picked up in - // SendMessageToServer. - protocol_handler_->SendMessageToServer(); - return false; // Don't reschedule. -} - -InvalidationClientCore::InvalidationClientCore( - SystemResources* resources, Random* random, int client_type, - const string& client_name, const ClientConfigP& config, - const string& application_name) - : resources_(resources), - internal_scheduler_(resources->internal_scheduler()), - logger_(resources->logger()), - storage_(new SafeStorage(resources->storage())), - statistics_(new Statistics()), - config_(config), - digest_fn_(new Sha1DigestFunction()), - registration_manager_(logger_, statistics_.get(), digest_fn_.get()), - msg_validator_(new TiclMessageValidator(logger_)), - smearer_(random, config.smear_percent()), - protocol_handler_(config.protocol_handler_config(), resources, &smearer_, - statistics_.get(), client_type, application_name, this, - msg_validator_.get()), - is_online_(true), - random_(random) { - storage_.get()->SetSystemResources(resources_); - application_client_id_.set_client_name(client_name); - application_client_id_.set_client_type(client_type); - CreateSchedulingTasks(); - RegisterWithNetwork(resources); - TLOG(logger_, INFO, "Created client: %s", ToString().c_str()); -} - -void InvalidationClientCore::RegisterWithNetwork(SystemResources* resources) { - // Install ourselves as a receiver for server messages. - resources->network()->SetMessageReceiver( - NewPermanentCallback(this, &InvalidationClientCore::MessageReceiver)); - - resources->network()->AddNetworkStatusReceiver( - NewPermanentCallback(this, - &InvalidationClientCore::NetworkStatusReceiver)); -} - -void InvalidationClientCore::CreateSchedulingTasks() { - acquire_token_task_.reset(new AcquireTokenTask(this)); - reg_sync_heartbeat_task_.reset(new RegSyncHeartbeatTask(this)); - persistent_write_task_.reset(new PersistentWriteTask(this)); - heartbeat_task_.reset(new HeartbeatTask(this)); - batching_task_.reset(new BatchingTask(&protocol_handler_, - &smearer_, - TimeDelta::FromMilliseconds( - config_.protocol_handler_config().batching_delay_ms()))); -} - -void InvalidationClientCore::InitConfig(ClientConfigP* config) { - ProtoHelpers::InitConfigVersion(config->mutable_version()); - ProtocolHandler::InitConfig(config->mutable_protocol_handler_config()); -} - -void InvalidationClientCore::InitConfigForTest(ClientConfigP* config) { - ProtoHelpers::InitConfigVersion(config->mutable_version()); - config->set_network_timeout_delay_ms(2000); - config->set_heartbeat_interval_ms(5000); - config->set_write_retry_delay_ms(500); - ProtocolHandler::InitConfigForTest(config->mutable_protocol_handler_config()); -} - -void InvalidationClientCore::Start() { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - if (ticl_state_.IsStarted()) { - TLOG(logger_, SEVERE, - "Ignoring start call since already started: client = %s", - this->ToString().c_str()); - return; - } - - // Initialize the nonce so that we can maintain the invariant that exactly - // one of "nonce_" and "client_token_" is non-empty. - set_nonce(InvalidationClientCore::GenerateNonce(random_.get())); - - TLOG(logger_, INFO, "Starting with C++ config: %s", - ProtoHelpers::ToString(config_).c_str()); - - // Read the state blob and then schedule startInternal once the value is - // there. - ScheduleStartAfterReadingStateBlob(); -} - -void InvalidationClientCore::StartInternal(const string& serialized_state) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - CHECK(resources_->IsStarted()) << "Resources must be started before starting " - "the Ticl"; - - // Initialize the session manager using the persisted client token. - PersistentTiclState persistent_state; - bool deserialized = false; - if (!serialized_state.empty()) { - deserialized = PersistenceUtils::DeserializeState( - logger_, serialized_state, digest_fn_.get(), &persistent_state); - } - - if (!serialized_state.empty() && !deserialized) { - // In this case, we'll proceed as if we had no persistent state -- i.e., - // obtain a new client id from the server. - statistics_->RecordError( - Statistics::ClientErrorType_PERSISTENT_DESERIALIZATION_FAILURE); - TLOG(logger_, SEVERE, "Failed deserializing persistent state: %s", - ProtoHelpers::ToString(serialized_state).c_str()); - } - if (deserialized) { - // If we have persistent state, use the previously-stored token and send a - // heartbeat to let the server know that we've restarted, since we may have - // been marked offline. - // - // In the common case, the server will already have all of our - // registrations, but we won't know for sure until we've gotten its summary. - // We'll ask the application for all of its registrations, but to avoid - // making the registrar redo the work of performing registrations that - // probably already exist, we'll suppress sending them to the registrar. - TLOG(logger_, INFO, "Restarting from persistent state: %s", - ProtoHelpers::ToString( - persistent_state.client_token()).c_str()); - set_nonce(""); - set_client_token(persistent_state.client_token()); - should_send_registrations_ = false; - - // Schedule an info message for the near future. We delay a little bit to - // allow the application to reissue its registrations locally and avoid - // triggering registration sync with the data center due to a hash mismatch. - internal_scheduler_->Schedule(TimeDelta::FromMilliseconds( - config_.initial_persistent_heartbeat_delay_ms()), - NewPermanentCallback(this, - &InvalidationClientCore::SendInfoMessageToServer, false, true)); - - // We need to ensure that heartbeats are sent, regardless of whether we - // start fresh or from persistent state. The line below ensures that they - // are scheduled in the persistent startup case. For the other case, the - // task is scheduled when we acquire a token. - heartbeat_task_.get()->EnsureScheduled("Startup-after-persistence"); - } else { - // If we had no persistent state or couldn't deserialize the state that we - // had, start fresh. Request a new client identifier. - // - // The server can't possibly have our registrations, so whatever we get - // from the application we should send to the registrar. - TLOG(logger_, INFO, "Starting with no previous state"); - should_send_registrations_ = true; - ScheduleAcquireToken("Startup"); - } - // InvalidationListener.Ready() is called when the ticl has acquired a - // new token. -} - -void InvalidationClientCore::Stop() { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - TLOG(logger_, WARNING, "Ticl being stopped: %s", ToString().c_str()); - if (ticl_state_.IsStarted()) { - ticl_state_.Stop(); - } -} - -void InvalidationClientCore::Register(const ObjectId& object_id) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - vector<ObjectId> object_ids; - object_ids.push_back(object_id); - PerformRegisterOperations(object_ids, RegistrationP_OpType_REGISTER); -} - -void InvalidationClientCore::Unregister(const ObjectId& object_id) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - vector<ObjectId> object_ids; - object_ids.push_back(object_id); - PerformRegisterOperations(object_ids, RegistrationP_OpType_UNREGISTER); -} - -void InvalidationClientCore::PerformRegisterOperations( - const vector<ObjectId>& object_ids, RegistrationP::OpType reg_op_type) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - CHECK(!object_ids.empty()) << "Must specify some object id"; - - if (ticl_state_.IsStopped()) { - // The Ticl has been stopped. This might be some old registration op - // coming in. Just ignore instead of crashing. - TLOG(logger_, SEVERE, "Ticl stopped: register (%d) of %d objects ignored.", - reg_op_type, object_ids.size()); - return; - } - if (!ticl_state_.IsStarted()) { - // We must be in the NOT_STARTED state, since we can't be in STOPPED or - // STARTED (since the previous if-check didn't succeeded, and isStarted uses - // a != STARTED test). - TLOG(logger_, SEVERE, - "Ticl is not yet started; failing registration call; client = %s, " - "num-objects = %d, op = %d", - this->ToString().c_str(), object_ids.size(), reg_op_type); - for (size_t i = 0; i < object_ids.size(); ++i) { - const ObjectId& object_id = object_ids[i]; - GetListener()->InformRegistrationFailure(this, object_id, true, - "Client not yet ready"); - } - return; - } - - vector<ObjectIdP> object_id_protos; - for (size_t i = 0; i < object_ids.size(); ++i) { - const ObjectId& object_id = object_ids[i]; - ObjectIdP object_id_proto; - ProtoConverter::ConvertToObjectIdProto(object_id, &object_id_proto); - Statistics::IncomingOperationType op_type = - (reg_op_type == RegistrationP_OpType_REGISTER) ? - Statistics::IncomingOperationType_REGISTRATION : - Statistics::IncomingOperationType_UNREGISTRATION; - statistics_->RecordIncomingOperation(op_type); - TLOG(logger_, INFO, "Register %s, %d", - ProtoHelpers::ToString(object_id_proto).c_str(), reg_op_type); - object_id_protos.push_back(object_id_proto); - } - - - // Update the registration manager state, then have the protocol client send a - // message. - vector<ObjectIdP> object_id_protos_to_send; - registration_manager_.PerformOperations(object_id_protos, reg_op_type, - &object_id_protos_to_send); - - // Check whether we should suppress sending registrations because we don't - // yet know the server's summary. - if (should_send_registrations_ && (!object_id_protos_to_send.empty())) { - protocol_handler_.SendRegistrations( - object_id_protos_to_send, reg_op_type, batching_task_.get()); - } - reg_sync_heartbeat_task_.get()->EnsureScheduled("PerformRegister"); -} - -void InvalidationClientCore::Acknowledge(const AckHandle& acknowledge_handle) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - if (acknowledge_handle.IsNoOp()) { - // Nothing to do. We do not increment statistics here since this is a no op - // handle and statistics can only be acccessed on the scheduler thread. - return; - } - // Validate the ack handle. - - // 1. Parse the ack handle first. - AckHandleP ack_handle; - ack_handle.ParseFromString(acknowledge_handle.handle_data()); - if (!ack_handle.IsInitialized()) { - TLOG(logger_, WARNING, "Bad ack handle : %s", - ProtoHelpers::ToString(acknowledge_handle.handle_data()).c_str()); - statistics_->RecordError( - Statistics::ClientErrorType_ACKNOWLEDGE_HANDLE_FAILURE); - return; - } - - // 2. Validate ack handle - it should have a valid invalidation. - if (!ack_handle.has_invalidation() - || !msg_validator_->IsValid(ack_handle.invalidation())) { - TLOG(logger_, WARNING, "Incorrect ack handle: %s", - ProtoHelpers::ToString(ack_handle).c_str()); - statistics_->RecordError( - Statistics::ClientErrorType_ACKNOWLEDGE_HANDLE_FAILURE); - return; - } - - // Currently, only invalidations have non-trivial ack handle. - InvalidationP* invalidation = ack_handle.mutable_invalidation(); - invalidation->clear_payload(); // Don't send the payload back. - statistics_->RecordIncomingOperation( - Statistics::IncomingOperationType_ACKNOWLEDGE); - protocol_handler_.SendInvalidationAck(*invalidation, batching_task_.get()); -} - -string InvalidationClientCore::ToString() { - return StringPrintf("Client: %s, %s, %s", - ProtoHelpers::ToString(application_client_id_).c_str(), - ProtoHelpers::ToString(client_token_).c_str(), - this->ticl_state_.ToString().c_str()); -} - -string InvalidationClientCore::GetClientToken() { - CHECK(client_token_.empty() || nonce_.empty()); - TLOG(logger_, FINE, "Return client token = %s", - ProtoHelpers::ToString(client_token_).c_str()); - return client_token_; -} - -void InvalidationClientCore::HandleIncomingMessage(const string& message) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - statistics_->RecordReceivedMessage( - Statistics::ReceivedMessageType_TOTAL); - ParsedMessage parsed_message; - if (!protocol_handler_.HandleIncomingMessage(message, &parsed_message)) { - // Invalid message. - return; - } - - // Ensure we have either a matching token or a matching nonce. - if (!ValidateToken(parsed_message.header.token())) { - return; - } - - // Handle a token control message, if present. - if (parsed_message.token_control_message != NULL) { - statistics_->RecordReceivedMessage( - Statistics::ReceivedMessageType_TOKEN_CONTROL); - HandleTokenChanged(parsed_message.header.token(), - parsed_message.token_control_message->new_token()); - } - - // We might have lost our token or failed to acquire one. Ensure that we do - // not proceed in either case. - // Note that checking for the presence of a TokenControlMessage is *not* - // sufficient: it might be a token-assign with the wrong nonce or a - // token-destroy message, for example. - if (client_token_.empty()) { - return; - } - - // Handle the messages received from the server by calling the appropriate - // listener method. - - // In the beginning inform the listener about the header (the caller is - // already prepared to handle the fact that the same header is given to - // it multiple times). - HandleIncomingHeader(parsed_message.header); - - if (parsed_message.invalidation_message != NULL) { - statistics_->RecordReceivedMessage( - Statistics::ReceivedMessageType_INVALIDATION); - HandleInvalidations(parsed_message.invalidation_message->invalidation()); - } - if (parsed_message.registration_status_message != NULL) { - statistics_->RecordReceivedMessage( - Statistics::ReceivedMessageType_REGISTRATION_STATUS); - HandleRegistrationStatus( - parsed_message.registration_status_message->registration_status()); - } - if (parsed_message.registration_sync_request_message != NULL) { - statistics_->RecordReceivedMessage( - Statistics::ReceivedMessageType_REGISTRATION_SYNC_REQUEST); - HandleRegistrationSyncRequest(); - } - if (parsed_message.info_request_message != NULL) { - statistics_->RecordReceivedMessage( - Statistics::ReceivedMessageType_INFO_REQUEST); - HandleInfoMessage( - // Shouldn't have to do this, but the proto compiler generates bad code - // for repeated enum fields. - *reinterpret_cast<const RepeatedField<InfoRequestMessage_InfoType>* >( - &parsed_message.info_request_message->info_type())); - } - if (parsed_message.error_message != NULL) { - statistics_->RecordReceivedMessage( - Statistics::ReceivedMessageType_ERROR); - HandleErrorMessage( - parsed_message.error_message->code(), - parsed_message.error_message->description()); - } -} - -void InvalidationClientCore::HandleTokenChanged( - const string& header_token, const string& new_token) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - // The server is either supplying a new token in response to an - // InitializeMessage, spontaneously destroying a token we hold, or - // spontaneously upgrading a token we hold. - - if (!new_token.empty()) { - // Note: header_token cannot be empty, so an empty nonce or client_token will - // always be non-equal. - bool header_token_matches_nonce = header_token == nonce_; - bool header_token_matches_existing_token = header_token == client_token_; - bool should_accept_token = - header_token_matches_nonce || header_token_matches_existing_token; - if (!should_accept_token) { - TLOG(logger_, INFO, "Ignoring new token; %s does not match nonce = %s " - "or existing token = %s", - ProtoHelpers::ToString(new_token).c_str(), - ProtoHelpers::ToString(nonce_).c_str(), - ProtoHelpers::ToString(client_token_).c_str()); - return; - } - TLOG(logger_, INFO, "New token being assigned at client: %s, Old = %s", - ProtoHelpers::ToString(new_token).c_str(), - ProtoHelpers::ToString(client_token_).c_str()); - heartbeat_task_.get()->EnsureScheduled("Heartbeat-after-new-token"); - set_nonce(""); - set_client_token(new_token); - persistent_write_task_.get()->EnsureScheduled("Write-after-new-token"); - } else { - // Destroy the existing token. - TLOG(logger_, INFO, "Destroying existing token: %s", - ProtoHelpers::ToString(client_token_).c_str()); - ScheduleAcquireToken("Destroy"); - } -} - -void InvalidationClientCore::ScheduleAcquireToken(const string& debug_string) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - set_client_token(""); - acquire_token_task_.get()->EnsureScheduled(debug_string); -} - -void InvalidationClientCore::HandleInvalidations( - const RepeatedPtrField<InvalidationP>& invalidations) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - for (int i = 0; i < invalidations.size(); ++i) { - const InvalidationP& invalidation = invalidations.Get(i); - AckHandleP ack_handle_proto; - ack_handle_proto.mutable_invalidation()->CopyFrom(invalidation); - string serialized; - ack_handle_proto.SerializeToString(&serialized); - AckHandle ack_handle(serialized); - if (ProtoConverter::IsAllObjectIdP(invalidation.object_id())) { - TLOG(logger_, INFO, "Issuing invalidate all"); - GetListener()->InvalidateAll(this, ack_handle); - } else { - // Regular object. Could be unknown version or not. - Invalidation inv; - ProtoConverter::ConvertFromInvalidationProto(invalidation, &inv); - bool isSuppressed = invalidation.is_trickle_restart(); - TLOG(logger_, INFO, "Issuing invalidate: %s", - ProtoHelpers::ToString(invalidation).c_str()); - - // Issue invalidate if the invalidation had a known version AND either - // no suppression has occurred or the client allows suppression. - if (invalidation.is_known_version() && - (!isSuppressed || config_.allow_suppression())) { - GetListener()->Invalidate(this, inv, ack_handle); - } else { - // Unknown version - GetListener()->InvalidateUnknownVersion(this, - inv.object_id(), ack_handle); - } - } - } -} - -void InvalidationClientCore::HandleRegistrationStatus( - const RepeatedPtrField<RegistrationStatus>& reg_status_list) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - vector<bool> local_processing_statuses; - registration_manager_.HandleRegistrationStatus( - reg_status_list, &local_processing_statuses); - CHECK(local_processing_statuses.size() == - static_cast<size_t>(reg_status_list.size())) << - "Not all registration statuses were processed"; - - // Inform app about the success or failure of each registration based - // on what the registration manager has indicated. - for (int i = 0; i < reg_status_list.size(); ++i) { - const RegistrationStatus& reg_status = reg_status_list.Get(i); - bool was_success = local_processing_statuses[i]; - TLOG(logger_, FINE, "Process reg status: %s", - ProtoHelpers::ToString(reg_status).c_str()); - - ObjectId object_id; - ProtoConverter::ConvertFromObjectIdProto( - reg_status.registration().object_id(), &object_id); - if (was_success) { - // Server operation was both successful and agreed with what the client - // wanted. - RegistrationP::OpType reg_op_type = reg_status.registration().op_type(); - InvalidationListener::RegistrationState reg_state = - ConvertOpTypeToRegState(reg_op_type); - GetListener()->InformRegistrationStatus(this, object_id, reg_state); - } else { - // Server operation either failed or disagreed with client's intent (e.g., - // successful unregister, but the client wanted a registration). - string description = - (reg_status.status().code() == StatusP_Code_SUCCESS) ? - "Registration discrepancy detected" : - reg_status.status().description(); - bool is_permanent = - (reg_status.status().code() == StatusP_Code_PERMANENT_FAILURE); - GetListener()->InformRegistrationFailure( - this, object_id, !is_permanent, description); - } - } -} - -void InvalidationClientCore::HandleRegistrationSyncRequest() { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - // Send all the registrations in the reg sync message. - // Generate a single subtree for all the registrations. - RegistrationSubtree subtree; - registration_manager_.GetRegistrations("", 0, &subtree); - protocol_handler_.SendRegistrationSyncSubtree(subtree, batching_task_.get()); -} - -void InvalidationClientCore::HandleInfoMessage( - const RepeatedField<InfoRequestMessage_InfoType>& info_types) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - bool must_send_performance_counters = false; - for (int i = 0; i < info_types.size(); ++i) { - must_send_performance_counters = - (info_types.Get(i) == - InfoRequestMessage_InfoType_GET_PERFORMANCE_COUNTERS); - if (must_send_performance_counters) { - break; - } - } - SendInfoMessageToServer(must_send_performance_counters, - !registration_manager_.IsStateInSyncWithServer()); -} - -void InvalidationClientCore::HandleErrorMessage( - ErrorMessage::Code code, - const string& description) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - // If it is an auth failure, we shut down the ticl. - TLOG(logger_, SEVERE, "Received error message: %s, %s", - ProtoHelpers::ToString(code).c_str(), - description.c_str()); - - // Translate the code to error reason. - int reason; - switch (code) { - case ErrorMessage_Code_AUTH_FAILURE: - reason = ErrorReason::AUTH_FAILURE; - break; - case ErrorMessage_Code_UNKNOWN_FAILURE: - reason = ErrorReason::UNKNOWN_FAILURE; - break; - default: - reason = ErrorReason::UNKNOWN_FAILURE; - break; - } - // Issue an informError to the application. - ErrorInfo error_info(reason, false, description, ErrorContext()); - GetListener()->InformError(this, error_info); - - // If this is an auth failure, remove registrations and stop the Ticl. - // Otherwise do nothing. - if (code != ErrorMessage_Code_AUTH_FAILURE) { - return; - } - - // If there are any registrations, remove them and issue registration - // failure. - vector<ObjectIdP> desired_registrations; - registration_manager_.RemoveRegisteredObjects(&desired_registrations); - TLOG(logger_, WARNING, "Issuing failure for %d objects", - desired_registrations.size()); - for (size_t i = 0; i < desired_registrations.size(); ++i) { - ObjectId object_id; - ProtoConverter::ConvertFromObjectIdProto( - desired_registrations[i], &object_id); - GetListener()->InformRegistrationFailure( - this, object_id, false, "Auth error"); - } -} - -void InvalidationClientCore::HandleMessageSent() { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - last_message_send_time_ = internal_scheduler_->GetCurrentTime(); -} - -void InvalidationClientCore::HandleNetworkStatusChange(bool is_online) { - // If we're back online and haven't sent a message to the server in a while, - // send a heartbeat to make sure the server knows we're online. - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - bool was_online = is_online_; - is_online_ = is_online; - if (is_online && !was_online && - (internal_scheduler_->GetCurrentTime() > - last_message_send_time_ + TimeDelta::FromMilliseconds( - config_.offline_heartbeat_threshold_ms()))) { - TLOG(logger_, INFO, - "Sending heartbeat after reconnection; previous send was %s ms ago", - SimpleItoa( - (internal_scheduler_->GetCurrentTime() - last_message_send_time_) - .InMilliseconds()).c_str()); - SendInfoMessageToServer( - false, !registration_manager_.IsStateInSyncWithServer()); - } -} - -void InvalidationClientCore::GetRegistrationManagerStateAsSerializedProto( - string* result) { - RegistrationManagerStateP reg_state; - registration_manager_.GetClientSummary(reg_state.mutable_client_summary()); - registration_manager_.GetServerSummary(reg_state.mutable_server_summary()); - vector<ObjectIdP> registered_objects; - registration_manager_.GetRegisteredObjectsForTest(®istered_objects); - for (size_t i = 0; i < registered_objects.size(); ++i) { - reg_state.add_registered_objects()->CopyFrom(registered_objects[i]); - } - reg_state.SerializeToString(result); -} - -void InvalidationClientCore::GetStatisticsAsSerializedProto( - string* result) { - vector<pair<string, int> > properties; - statistics_->GetNonZeroStatistics(&properties); - InfoMessage info_message; - for (size_t i = 0; i < properties.size(); ++i) { - PropertyRecord* record = info_message.add_performance_counter(); - record->set_name(properties[i].first); - record->set_value(properties[i].second); - } - info_message.SerializeToString(result); -} - -void InvalidationClientCore::HandleIncomingHeader( - const ServerMessageHeader& header) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - CHECK(nonce_.empty()) << - "Cannot process server header " << header.ToString() << - " with non-empty nonce " << nonce_; - - if (header.registration_summary() != NULL) { - // We've received a summary from the server, so if we were suppressing - // registrations, we should now allow them to go to the registrar. - should_send_registrations_ = true; - - - // Pass the registration summary to the registration manager. If we are now - // in agreement with the server and we had any pending operations, we can - // tell the listener that those operations have succeeded. - vector<RegistrationP> upcalls; - registration_manager_.InformServerRegistrationSummary( - *header.registration_summary(), &upcalls); - TLOG(logger_, FINE, - "Receivced new server registration summary (%s); will make %d upcalls", - ProtoHelpers::ToString(*header.registration_summary()).c_str(), - upcalls.size()); - vector<RegistrationP>::iterator iter; - for (iter = upcalls.begin(); iter != upcalls.end(); iter++) { - const RegistrationP& registration = *iter; - ObjectId object_id; - ProtoConverter::ConvertFromObjectIdProto(registration.object_id(), - &object_id); - InvalidationListener::RegistrationState reg_state = - ConvertOpTypeToRegState(registration.op_type()); - GetListener()->InformRegistrationStatus(this, object_id, reg_state); - } - } -} - -bool InvalidationClientCore::ValidateToken(const string& server_token) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - if (!client_token_.empty()) { - // Client token case. - if (client_token_ != server_token) { - TLOG(logger_, INFO, "Incoming message has bad token: %s, %s", - ProtoHelpers::ToString(client_token_).c_str(), - ProtoHelpers::ToString(server_token).c_str()); - statistics_->RecordError(Statistics::ClientErrorType_TOKEN_MISMATCH); - return false; - } - return true; - } else if (!nonce_.empty()) { - // Nonce case. - CHECK(!nonce_.empty()) << "Client token and nonce are both empty: " - << client_token_ << ", " << nonce_; - if (nonce_ != server_token) { - statistics_->RecordError(Statistics::ClientErrorType_NONCE_MISMATCH); - TLOG(logger_, INFO, - "Rejecting server message with mismatched nonce: Client = %s, " - "Server = %s", ProtoHelpers::ToString(nonce_).c_str(), - ProtoHelpers::ToString(server_token).c_str()); - return false; - } else { - TLOG(logger_, INFO, - "Accepting server message with matching nonce: %s", - ProtoHelpers::ToString(nonce_).c_str()); - return true; - } - } - // Neither token nor nonce; ignore message. - return false; -} - -void InvalidationClientCore::SendInfoMessageToServer( - bool must_send_performance_counters, bool request_server_summary) { - TLOG(logger_, INFO, - "Sending info message to server; request server summary = %s", - request_server_summary ? "true" : "false"); - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - // Make sure that you have the latest registration summary. - vector<pair<string, int> > performance_counters; - ClientConfigP* config_to_send = NULL; - if (must_send_performance_counters) { - statistics_->GetNonZeroStatistics(&performance_counters); - config_to_send = &config_; - } - protocol_handler_.SendInfoMessage(performance_counters, config_to_send, - request_server_summary, batching_task_.get()); -} - -string InvalidationClientCore::GenerateNonce(Random* random) { - // Return a nonce computed by converting a random 64-bit number to a string. - return SimpleItoa(static_cast<int64>(random->RandUint64())); -} - -void InvalidationClientCore::set_nonce(const string& new_nonce) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - CHECK(new_nonce.empty() || client_token_.empty()) << - "Tried to set nonce with existing token " << client_token_; - nonce_ = new_nonce; -} - -void InvalidationClientCore::set_client_token(const string& new_client_token) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - CHECK(new_client_token.empty() || nonce_.empty()) << - "Tried to set token with existing nonce " << nonce_; - - // If the ticl has not been started and we are getting a new token (either - // from persistence or from the server, start the ticl and inform the - // application. - bool finish_starting_ticl = !ticl_state_.IsStarted() && - client_token_.empty() && !new_client_token.empty(); - client_token_ = new_client_token; - - if (finish_starting_ticl) { - FinishStartingTiclAndInformListener(); - } -} - -void InvalidationClientCore::FinishStartingTiclAndInformListener() { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - CHECK(!ticl_state_.IsStarted()); - - ticl_state_.Start(); - GetListener()->Ready(this); - - // We are not currently persisting our registration digest, so regardless of - // whether or not we are restarting from persistent state, we need to query - // the application for all of its registrations. - GetListener()->ReissueRegistrations(this, - RegistrationManager::kEmptyPrefix, 0); - TLOG(logger_, INFO, "Ticl started: %s", ToString().c_str()); -} - -void InvalidationClientCore::ScheduleStartAfterReadingStateBlob() { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - storage_->ReadKey(kClientTokenKey, - NewPermanentCallback(this, &InvalidationClientCore::ReadCallback)); -} - -void InvalidationClientCore::ReadCallback( - pair<Status, string> read_result) { - string serialized_state; - if (read_result.first.IsSuccess()) { - serialized_state = read_result.second; - } else { - statistics_->RecordError( - Statistics::ClientErrorType_PERSISTENT_READ_FAILURE); - TLOG(logger_, WARNING, "Could not read state blob: %s", - read_result.first.message().c_str()); - } - // Call start now. - internal_scheduler_->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - this, &InvalidationClientCore::StartInternal, serialized_state)); -} - -ExponentialBackoffDelayGenerator* -InvalidationClientCore::CreateExpBackOffGenerator( - const TimeDelta& initial_delay) { - return new ExponentialBackoffDelayGenerator(random_.get(), initial_delay, - config_.max_exponential_backoff_factor()); -} - -InvalidationListener::RegistrationState -InvalidationClientCore::ConvertOpTypeToRegState(RegistrationP::OpType - reg_op_type) { - InvalidationListener::RegistrationState reg_state = - reg_op_type == RegistrationP_OpType_REGISTER ? - InvalidationListener::REGISTERED : - InvalidationListener::UNREGISTERED; - return reg_state; -} - -void InvalidationClientCore::MessageReceiver(string message) { - internal_scheduler_->Schedule(Scheduler::NoDelay(), NewPermanentCallback( - this, - &InvalidationClientCore::HandleIncomingMessage, message)); -} - -void InvalidationClientCore::NetworkStatusReceiver(bool status) { - internal_scheduler_->Schedule(Scheduler::NoDelay(), NewPermanentCallback( - this, &InvalidationClientCore::HandleNetworkStatusChange, status)); -} - - -void InvalidationClientCore::ChangeNetworkTimeoutDelayForTest( - const TimeDelta& delay) { - config_.set_network_timeout_delay_ms(delay.InMilliseconds()); - CreateSchedulingTasks(); -} - -void InvalidationClientCore::ChangeHeartbeatDelayForTest( - const TimeDelta& delay) { - config_.set_heartbeat_interval_ms(delay.InMilliseconds()); - CreateSchedulingTasks(); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-core.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-core.h deleted file mode 100644 index d6f66d7caba85431bb767bbffa468a648de29587..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-core.h +++ /dev/null @@ -1,490 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Implementation of the Invalidation Client Library (Ticl). - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_CORE_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_CORE_H_ - -#include <string> -#include <utility> - -#include "google/cacheinvalidation/include/invalidation-client.h" -#include "google/cacheinvalidation/include/invalidation-listener.h" -#include "google/cacheinvalidation/deps/digest-function.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" -#include "google/cacheinvalidation/impl/digest-store.h" -#include "google/cacheinvalidation/impl/exponential-backoff-delay-generator.h" -#include "google/cacheinvalidation/impl/protocol-handler.h" -#include "google/cacheinvalidation/impl/registration-manager.h" -#include "google/cacheinvalidation/impl/run-state.h" -#include "google/cacheinvalidation/impl/safe-storage.h" -#include "google/cacheinvalidation/impl/smearer.h" - -namespace invalidation { - -class InvalidationClientCore; - -/* A task for acquiring tokens from the server. */ -class AcquireTokenTask : public RecurringTask { - public: - explicit AcquireTokenTask(InvalidationClientCore* client); - virtual ~AcquireTokenTask() {} - - // The actual implementation as required by the RecurringTask. - virtual bool RunTask(); - - private: - /* The client that owns this task. */ - InvalidationClientCore* client_; -}; - -/* A task that schedules heartbeats when the registration summary at the client - * is not in sync with the registration summary from the server. - */ -class RegSyncHeartbeatTask : public RecurringTask { - public: - explicit RegSyncHeartbeatTask(InvalidationClientCore* client); - virtual ~RegSyncHeartbeatTask() {} - - // The actual implementation as required by the RecurringTask. - virtual bool RunTask(); - - private: - /* The client that owns this task. */ - InvalidationClientCore* client_; -}; - -/* A task that writes the token to persistent storage. */ -class PersistentWriteTask : public RecurringTask { - public: - explicit PersistentWriteTask(InvalidationClientCore* client); - virtual ~PersistentWriteTask() {} - - // The actual implementation as required by the RecurringTask. - virtual bool RunTask(); - - private: - /* Handles the result of a request to write to persistent storage. - * |state| is the serialized state that was written. - */ - void WriteCallback(const string& state, Status status); - - InvalidationClientCore* client_; - - /* The last client token that was written to to persistent state - * successfully. - */ - string last_written_token_; -}; - -/* A task for sending heartbeats to the server. */ -class HeartbeatTask : public RecurringTask { - public: - explicit HeartbeatTask(InvalidationClientCore* client); - virtual ~HeartbeatTask() {} - - // The actual implementation as required by the RecurringTask. - virtual bool RunTask(); - private: - /* The client that owns this task. */ - InvalidationClientCore* client_; - - /* Next time that the performance counters are sent to the server. */ - Time next_performance_send_time_; -}; - -/* The task that is scheduled to send batched messages to the server (when - * needed). - */ -class BatchingTask : public RecurringTask { - public: - BatchingTask(ProtocolHandler *handler, Smearer* smearer, - TimeDelta batching_delay); - - virtual ~BatchingTask() {} - - // The actual implementation as required by the RecurringTask. - virtual bool RunTask(); - - private: - ProtocolHandler* protocol_handler_; -}; - -class InvalidationClientCore : public InvalidationClient, - public ProtocolListener { - public: - /* Modifies |config| to contain default parameters. */ - static void InitConfig(ClientConfigP *config); - - /* Modifies |config| to contain parameters set for unit tests. */ - static void InitConfigForTest(ClientConfigP *config); - - /* Creates the tasks used by the Ticl for token acquisition, heartbeats, - * persistent writes and registration sync. - */ - void CreateSchedulingTasks(); - - /* Stores the client id that is used for squelching invalidations on the - * server side. - */ - void GetApplicationClientIdForTest(string* result) { - application_client_id_.SerializeToString(result); - } - - void GetClientTokenForTest(string* result) { - *result = client_token_; - } - - // Getters for testing. No transfer of ownership occurs in any of these - // methods. - - /* Returns the system resources. */ - SystemResources* GetResourcesForTest() { - return resources_; - } - - /* Returns the performance counters/statistics. */ - Statistics* GetStatisticsForTest() { - return statistics_.get(); - } - - /* Returns the digest function used for computing digests for object - * registrations. - */ - DigestFunction* GetDigestFunctionForTest() { - return digest_fn_.get(); - } - - /* Changes the existing delay for the network timeout delay in the operation - * scheduler to be delay_ms. - */ - void ChangeNetworkTimeoutDelayForTest(const TimeDelta& delay); - - /* Changes the existing delay for the heartbeat delay in the operation - * scheduler to be delay_ms. - */ - void ChangeHeartbeatDelayForTest(const TimeDelta& delay); - - /* Returns the next time a message is allowed to be sent to the server (could - * be in the past). - */ - int64 GetNextMessageSendTimeMsForTest() { - return protocol_handler_.GetNextMessageSendTimeMsForTest(); - } - - /* Returns true iff the client is currently started. */ - bool IsStartedForTest() { - return ticl_state_.IsStarted(); - } - - /* Sets the digest store to be digest_store for testing purposes. - * - * REQUIRES: This method is called before the Ticl has been started. - */ - void SetDigestStoreForTest(DigestStore<ObjectIdP>* digest_store) { - CHECK(!resources_->IsStarted()); - registration_manager_.SetDigestStoreForTest(digest_store); - } - - virtual void Start(); - - virtual void Stop(); - - virtual void Register(const ObjectId& object_id); - - virtual void Unregister(const ObjectId& object_id); - - virtual void Register(const vector<ObjectId>& object_ids) { - PerformRegisterOperations(object_ids, RegistrationP_OpType_REGISTER); - } - - virtual void Unregister(const vector<ObjectId>& object_ids) { - PerformRegisterOperations(object_ids, RegistrationP_OpType_UNREGISTER); - } - - /* Implementation of (un)registration. - * - * Arguments: - * object_ids - object ids on which to operate - * reg_op_type - whether to register or unregister - */ - virtual void PerformRegisterOperations( - const vector<ObjectId>& object_ids, RegistrationP::OpType reg_op_type); - - void PerformRegisterOperationsInternal( - const vector<ObjectId>& object_ids, RegistrationP::OpType reg_op_type); - - virtual void Acknowledge(const AckHandle& acknowledge_handle); - - string ToString(); - - /* Returns a randomly generated nonce. */ - static string GenerateNonce(Random* random); - - // - // Protocol listener methods - // - - /* Returns the current client token. */ - virtual string GetClientToken(); - - virtual void GetRegistrationSummary(RegistrationSummary* summary) { - registration_manager_.GetClientSummary(summary); - } - - virtual void HandleMessageSent(); - - /* Gets registration manager state as a serialized RegistrationManagerState. - */ - void GetRegistrationManagerStateAsSerializedProto(string* result); - - /* Gets statistics as a serialized InfoMessage. */ - void GetStatisticsAsSerializedProto(string* result); - - /* The single key used to write all the Ticl state. */ - static const char* kClientTokenKey; - protected: - /* Constructs a client. - * - * Arguments: - * resources - resources to use during execution - * random - a random number generator (owned by this after the call) - * client_type - client type code - * client_name - application identifier for the client - * config - configuration for the client - */ - InvalidationClientCore( - SystemResources* resources, Random* random, int client_type, - const string& client_name, const ClientConfigP &config, - const string& application_name); - - /* Returns the internal scheduler. */ - Scheduler* GetInternalScheduler() { - return internal_scheduler_; - } - - /* Returns the statistics. */ - Statistics* GetStatistics() { - return statistics_.get(); - } - - /* Returns the listener. */ - virtual InvalidationListener* GetListener() = 0; - private: - // Friend classes so that they can access the scheduler, logger, smearer, etc. - friend class AcquireTokenTask; - friend class HeartbeatTask; - friend class InvalidationClientFactoryTest; - friend class PersistentWriteTask; - friend class RegSyncHeartbeatTask; - - // - // Private methods. - // - - virtual void HandleNetworkStatusChange(bool is_online); - - /* Implementation of start on the internal thread with the persistent - * serialized_state if any. Starts the TICL protocol and makes the TICL ready - * to received registration, invalidations, etc - */ - void StartInternal(const string& serialized_state); - - void AcknowledgeInternal(const AckHandle& acknowledge_handle); - - /* Set client_token to NULL and schedule acquisition of the token. */ - void ScheduleAcquireToken(const string& debug_string); - - /* Sends an info message to the server. If mustSendPerformanceCounters is - * true, the performance counters are sent regardless of when they were sent - * earlier. - */ - void SendInfoMessageToServer( - bool mustSendPerformanceCounters, bool request_server_summary); - - /* Sets the nonce to new_nonce. - * - * REQUIRES: new_nonce be empty or client_token_ be empty. The goal is to - * ensure that a nonce is never set unless there is no client token, unless - * the nonce is being cleared. - */ - void set_nonce(const string& new_nonce); - - /* Sets the client_token_ to new_client_token. - * - * REQUIRES: new_client_token be empty or nonce_ be empty. The goal is to - * ensure that a token is never set unless there is no nonce, unless the token - * is being cleared. - */ - void set_client_token(const string& new_client_token); - - /* Reads the Ticl state from persistent storage (if any) and calls - * startInternal. - */ - void ScheduleStartAfterReadingStateBlob(); - - /* Handles the result of a request to read from persistent storage. */ - void ReadCallback(pair<Status, string> read_result); - - /* Finish starting the ticl and inform the listener that it is ready. */ - void FinishStartingTiclAndInformListener(); - - /* Returns an exponential backoff generator with a max exponential factor - * given by |config_.max_exponential_backoff_factor| and initial delay - * |initial_delay|. - * Space for the returned object is owned by the caller. - */ - ExponentialBackoffDelayGenerator* CreateExpBackOffGenerator( - const TimeDelta& initial_delay); - - /* Registers a message receiver and status change listener on |resources|. */ - void RegisterWithNetwork(SystemResources* resources); - - /* Handles inbound messages from the network. */ - void MessageReceiver(string message); - - /* Responds to changes in network connectivity. */ - void NetworkStatusReceiver(bool status); - - /* Handles a |message| from the server. */ - void HandleIncomingMessage(const string& message); - - /* - * Handles a changed token. |header_token| is the token in the server message - * header. |new_token| is a new token from the server; if empty, it indicates - * a destroy-token message. - */ - void HandleTokenChanged(const string& header_token, const string& new_token); - - /* Processes a server message |header|. */ - void HandleIncomingHeader(const ServerMessageHeader& header); - - /* Handles |invalidations| from the server. */ - void HandleInvalidations( - const RepeatedPtrField<InvalidationP>& invalidations); - - /* Handles registration statusES from the server. */ - void HandleRegistrationStatus( - const RepeatedPtrField<RegistrationStatus>& reg_status_list); - - /* Handles A registration sync request from the server. */ - void HandleRegistrationSyncRequest(); - - /* Handles an info message request from the server. */ - void HandleInfoMessage( - const RepeatedField<InfoRequestMessage_InfoType>& info_types); - - /* Handles an error message with |code| and |description| from the server. */ - void HandleErrorMessage(ErrorMessage::Code code, const string& description); - - /* Returns whether |server_token| matches the client token or nonce. */ - bool ValidateToken(const string& server_token); - - /* Converts an operation type reg_status to a - * InvalidationListener::RegistrationState. - */ - static InvalidationListener::RegistrationState ConvertOpTypeToRegState( - RegistrationP::OpType reg_op_type); - - /* Resources for the Ticl. */ - SystemResources* resources_; // Owned by application. - - /* Reference into the resources object for cleaner code. All Ticl code must be - * scheduled on this scheduler. - */ - Scheduler* internal_scheduler_; - - /* Logger reference into the resources object for cleaner code. */ - Logger* logger_; - - /* A storage layer which schedules the callbacks on the internal scheduler - * thread. - */ - scoped_ptr<SafeStorage> storage_; - - /* Statistics objects to track number of sent messages, etc. */ - scoped_ptr<Statistics> statistics_; - - /* Configuration for this instance. */ - ClientConfigP config_; - - /* Application identifier for this client. */ - ApplicationClientIdP application_client_id_; - - /* The function for computing the registration and persistence state digests. - */ - scoped_ptr<DigestFunction> digest_fn_; - - /* Object maintaining the registration state for this client. */ - RegistrationManager registration_manager_; - - /* Used to validate messages */ - scoped_ptr<TiclMessageValidator> msg_validator_; - - /* A smearer to make sure that delays are randomized a little bit. */ - Smearer smearer_; - - /* Object handling low-level wire format interactions. */ - ProtocolHandler protocol_handler_; - - /* The state of the Ticl whether it has started or not. */ - RunState ticl_state_; - - /* Current client token known from the server. */ - string client_token_; - - // After the client starts, exactly one of nonce and clientToken is non-null. - - /* If not empty, nonce for pending identifier request. */ - string nonce_; - - /* Whether we should send registrations to the server or not. */ - // TODO(ghc): [cleanup] Make the server summary in the registration manager - // nullable and replace this variable with a test for whether it's null or - // not. - bool should_send_registrations_; - - /* Whether the network is online. Assume so when we start. */ - bool is_online_; - - /* Last time a message was sent to the server. */ - Time last_message_send_time_; - - /* A task for acquiring the token (if the client has no token). */ - scoped_ptr<AcquireTokenTask> acquire_token_task_; - - /* Task for checking if reg summary is out of sync and then sending a - * heartbeat to the server. - */ - scoped_ptr<RegSyncHeartbeatTask> reg_sync_heartbeat_task_; - - /* Task for writing the state blob to persistent storage. */ - scoped_ptr<PersistentWriteTask> persistent_write_task_; - - /* A task for periodic heartbeats. */ - scoped_ptr<HeartbeatTask> heartbeat_task_; - - /* Task to send all batched messages to the server. */ - scoped_ptr<BatchingTask> batching_task_; - - /* Random number generator for smearing, exp backoff, etc. */ - scoped_ptr<Random> random_; - - DISALLOW_COPY_AND_ASSIGN(InvalidationClientCore); -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_CORE_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-factory.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-factory.cc deleted file mode 100644 index 996a459d9047ba17cfbc4d442579bbd6525126b2..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-factory.cc +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "google/cacheinvalidation/include/invalidation-client-factory.h" - -#include "google/cacheinvalidation/impl/invalidation-client-impl.h" - -namespace invalidation { - -InvalidationClient* ClientFactory::Create( - SystemResources* resources, - const InvalidationClientConfig& config, - InvalidationListener* listener) { - ClientConfigP client_config; - InvalidationClientCore::InitConfig(&client_config); - client_config.set_allow_suppression(config.allow_suppression()); - Random* random = new Random(InvalidationClientUtil::GetCurrentTimeMs( - resources->internal_scheduler())); - return new InvalidationClientImpl( - resources, random, config.client_type(), config.client_name(), - client_config, config.application_name(), listener); -} - -// Deprecated, please the factory function that takes an -// InvalidationClientConfig instead. -InvalidationClient* CreateInvalidationClient( - SystemResources* resources, - int32 client_type, - const string& client_name, - const string& application_name, - InvalidationListener* listener) { - InvalidationClientConfig config( - client_type, client_name, application_name, true /* allowSuppression*/); - return ClientFactory::Create(resources, config, listener); -} - -InvalidationClient* ClientFactory::CreateForTest( - SystemResources* resources, - const InvalidationClientConfig& config, - InvalidationListener* listener) { - // Make a config with test params and construct an instance to return. - ClientConfigP client_config; - InvalidationClientCore::InitConfigForTest(&client_config); - client_config.set_allow_suppression(config.allow_suppression()); - Random* random = new Random(InvalidationClientUtil::GetCurrentTimeMs( - resources->internal_scheduler())); - return new InvalidationClientImpl( - resources, random, config.client_type(), config.client_name(), - client_config, config.application_name(), listener); -} - -InvalidationClient* CreateInvalidationClientForTest( - SystemResources* resources, - int32 client_type, - const string& client_name, - const string& application_name, - InvalidationListener* listener) { - return ClientFactory::CreateForTest( - resources, - InvalidationClientConfig(client_type, client_name, application_name, - true /* allowSuppression */), - listener); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-factory_test.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-factory_test.cc deleted file mode 100644 index ea5166492addb647a56ed685a488642eb59c79a8..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-factory_test.cc +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2013 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Unit tests for the InvalidationClientFactory class. - -#include "google/cacheinvalidation/include/invalidation-client-factory.h" -#include "google/cacheinvalidation/include/invalidation-listener.h" -#include "google/cacheinvalidation/include/types.h" -#include "google/cacheinvalidation/types.pb.h" -#include "google/cacheinvalidation/deps/googletest.h" -#include "google/cacheinvalidation/impl/basic-system-resources.h" -#include "google/cacheinvalidation/impl/constants.h" -#include "google/cacheinvalidation/impl/invalidation-client-impl.h" - -#include "google/cacheinvalidation/test/test-utils.h" - -namespace invalidation { - -using ::ipc::invalidation::ClientType_Type_TEST; -using ::ipc::invalidation::ObjectSource_Type_TEST; -using ::testing::StrictMock; - -// Test constants -static const char CLIENT_NAME[] = "demo-client-01"; -static const char APPLICATION_NAME[] = "demo-app"; - -// Tests the basic functionality of the invalidation client factory. -class InvalidationClientFactoryTest : public UnitTestBase { - public: - virtual ~InvalidationClientFactoryTest() {} - - // Performs setup for client factory unit tests, e.g. creating resource - // components and setting up common expectations for certain mock objects. - virtual void SetUp() { - UnitTestBase::SetUp(); - InitCommonExpectations(); // Set up expectations for common mock operations - - // Set up the listener scheduler to run any runnable that it receives. - EXPECT_CALL(*listener_scheduler, Schedule(_, _)) - .WillRepeatedly(InvokeAndDeleteClosure<1>()); - } - - // Creates a client with the given value for allowSuppression. - // The caller owns the storage. - InvalidationClientImpl* CreateClient(bool allowSuppression) { - InvalidationClientConfig config(ClientType_Type_TEST, - CLIENT_NAME, APPLICATION_NAME, allowSuppression); - return static_cast<InvalidationClientImpl*>( - ClientFactory::Create(resources.get(), config, &listener)); - } - - // Verifies that a client has expected values for allowing suppression - // and application client id. - void CheckClientValid(const InvalidationClientImpl* client, - bool allowSuppression) { - // Check that the the allow suppression flag was correctly set to - // the expected value. - ClientConfigP config = client->config_; - ASSERT_EQ(allowSuppression, config.allow_suppression()); - - // Check that the client type and client name were properly populated. - ASSERT_EQ(ClientType_Type_TEST, - client->application_client_id_.client_type()); - - ASSERT_EQ(CLIENT_NAME, - client->application_client_id_.client_name()); - } - - // The client being tested. Created fresh for each test function. - scoped_ptr<InvalidationClientImpl> client; - - // A mock invalidation listener. - StrictMock<MockInvalidationListener> listener; -}; - -// Tests that the deprecated CreateInvalidationClient overload -// correctly initializes the client to allow suppression. -TEST_F(InvalidationClientFactoryTest, TestCreateClient) { - client.reset(static_cast<InvalidationClientImpl*>( - CreateInvalidationClient( - resources.get(), - ClientType_Type_TEST, - CLIENT_NAME, - APPLICATION_NAME, - &listener))); - CheckClientValid(client.get(), true /* allowSuppression */); -} - -// Tests CreateClient with allowSuppression = false. -TEST_F(InvalidationClientFactoryTest, TestCreateClientForTrickles) { - bool allowSuppression = false; - client.reset(CreateClient(allowSuppression)); - CheckClientValid(client.get(), allowSuppression); -} - -// Tests CreateClient with allowSuppression = true. -TEST_F(InvalidationClientFactoryTest, testCreateClientForInvalidation) { - bool allowSuppression = true; - client.reset(CreateClient(allowSuppression)); - CheckClientValid(client.get(), allowSuppression); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl.cc deleted file mode 100644 index 947ffe4d57ddd236fcc29174f17b3cba91efafdf..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl.cc +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Implementation of the Invalidation Client Library (Ticl). - -#include "google/cacheinvalidation/impl/invalidation-client-impl.h" - -namespace invalidation { - -InvalidationClientImpl::InvalidationClientImpl( - SystemResources* resources, Random* random, int client_type, - const string& client_name, const ClientConfigP& config, - const string& application_name, InvalidationListener* listener) - : InvalidationClientCore(resources, random, client_type, client_name, - config, application_name), - listener_(new CheckingInvalidationListener( - listener, GetStatistics(), resources->internal_scheduler(), - resources->listener_scheduler(), resources->logger())) { -} - -void InvalidationClientImpl::Start() { - GetInternalScheduler()->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback(this, &InvalidationClientImpl::DoStart)); -} - -void InvalidationClientImpl::Stop() { - GetInternalScheduler()->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback(this, &InvalidationClientImpl::DoStop)); -} - -void InvalidationClientImpl::Register(const ObjectId& object_id) { - GetInternalScheduler()->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback(this, &InvalidationClientImpl::DoRegister, - object_id)); -} - -void InvalidationClientImpl::Register(const vector<ObjectId>& object_ids) { - GetInternalScheduler()->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback(this, &InvalidationClientImpl::DoBulkRegister, - object_ids)); -} - -void InvalidationClientImpl::Unregister(const ObjectId& object_id) { - GetInternalScheduler()->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback(this, &InvalidationClientImpl::DoUnregister, - object_id)); -} - -void InvalidationClientImpl::Unregister(const vector<ObjectId>& object_ids) { - GetInternalScheduler()->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback(this, &InvalidationClientImpl::DoBulkUnregister, - object_ids)); -} - -void InvalidationClientImpl::Acknowledge(const AckHandle& acknowledge_handle) { - GetInternalScheduler()->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback(this, &InvalidationClientImpl::DoAcknowledge, - acknowledge_handle)); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl.h deleted file mode 100644 index 2321dccc46c0a3a44690e1a21c834b34e64c5c21..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl.h +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Implementation of the Invalidation Client Library (Ticl). - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_IMPL_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_IMPL_H_ - -#include <string> -#include <utility> - -#include "google/cacheinvalidation/include/invalidation-client.h" -#include "google/cacheinvalidation/include/invalidation-listener.h" -#include "google/cacheinvalidation/impl/checking-invalidation-listener.h" -#include "google/cacheinvalidation/impl/invalidation-client-core.h" -#include "google/cacheinvalidation/impl/protocol-handler.h" - -namespace invalidation { - -class InvalidationClientImpl : public InvalidationClientCore { - public: - /* Constructs a client. - * - * Arguments: - * resources - resources to use during execution - * random - a random number generator (owned by this after the call) - * client_type - client type code - * client_name - application identifier for the client - * config - configuration for the client - * listener - application callback - */ - InvalidationClientImpl( - SystemResources* resources, Random* random, int client_type, - const string& client_name, const ClientConfigP &config, - const string& application_name, InvalidationListener* listener); - - // These methods override those in InvalidationClientCore. Their - // implementations all enqueue an event onto the work queue and - // then delegate to the InvalidationClientCore method through one - // of the private DoYYY functions (below). - - virtual void Start(); - - virtual void Stop(); - - virtual void Register(const ObjectId& object_id); - - virtual void Unregister(const ObjectId& object_id); - - virtual void Register(const vector<ObjectId>& object_ids); - - virtual void Unregister(const vector<ObjectId>& object_ids); - - virtual void Acknowledge(const AckHandle& acknowledge_handle); - - /* Returns the listener that was registered by the caller. */ - InvalidationListener* GetInvalidationListenerForTest() { - return listener_.get()->delegate(); - } - - protected: - virtual InvalidationListener* GetListener() { - return listener_.get(); - } - - private: - /* - * All of these methods simply delegate to the superclass implementation. They - * exist so that NewPermanentCallback objects created in - * invalidation-client-impl.cc can call superclass methods. - */ - void DoStart() { - this->InvalidationClientCore::Start(); - } - - void DoStop() { - this->InvalidationClientCore::Stop(); - } - - void DoRegister(const ObjectId& object_id) { - this->InvalidationClientCore::Register(object_id); - } - - void DoUnregister(const ObjectId& object_id) { - this->InvalidationClientCore::Unregister(object_id); - } - - void DoBulkRegister(const vector<ObjectId>& object_ids) { - this->InvalidationClientCore::Register(object_ids); - } - - void DoBulkUnregister(const vector<ObjectId>& object_ids) { - this->InvalidationClientCore::Unregister(object_ids); - } - - void DoAcknowledge(const AckHandle& acknowledge_handle) { - this->InvalidationClientCore::Acknowledge(acknowledge_handle); - } - - /* - * The listener registered by the application, wrapped in a - * CheckingInvalidationListener. - */ - scoped_ptr<CheckingInvalidationListener> listener_; - - DISALLOW_COPY_AND_ASSIGN(InvalidationClientImpl); -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_IMPL_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl_test.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl_test.cc deleted file mode 100644 index ab72ef2b0a13dd81a7c20a345d14440f34ddfb81..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-impl_test.cc +++ /dev/null @@ -1,504 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Unit tests for the InvalidationClientImpl class. - -#include <vector> - -#include "google/cacheinvalidation/client_test_internal.pb.h" -#include "google/cacheinvalidation/types.pb.h" -#include "google/cacheinvalidation/include/invalidation-listener.h" -#include "google/cacheinvalidation/include/types.h" -#include "google/cacheinvalidation/deps/gmock.h" -#include "google/cacheinvalidation/deps/googletest.h" -#include "google/cacheinvalidation/deps/random.h" -#include "google/cacheinvalidation/deps/string_util.h" -#include "google/cacheinvalidation/impl/basic-system-resources.h" -#include "google/cacheinvalidation/impl/constants.h" -#include "google/cacheinvalidation/impl/invalidation-client-impl.h" -#include "google/cacheinvalidation/impl/statistics.h" -#include "google/cacheinvalidation/impl/throttle.h" -#include "google/cacheinvalidation/impl/ticl-message-validator.h" -#include "google/cacheinvalidation/test/deterministic-scheduler.h" -#include "google/cacheinvalidation/test/test-logger.h" -#include "google/cacheinvalidation/test/test-utils.h" - -namespace invalidation { - -using ::ipc::invalidation::ClientType_Type_TEST; -using ::ipc::invalidation::RegistrationManagerStateP; -using ::ipc::invalidation::ObjectSource_Type_TEST; -using ::ipc::invalidation::StatusP_Code_PERMANENT_FAILURE; -using ::testing::_; -using ::testing::AllOf; -using ::testing::DeleteArg; -using ::testing::DoAll; -using ::testing::ElementsAre; -using ::testing::EqualsProto; -using ::testing::Eq; -using ::testing::Invoke; -using ::testing::InvokeArgument; -using ::testing::Matcher; -using ::testing::Property; -using ::testing::Return; -using ::testing::ReturnPointee; -using ::testing::SaveArg; -using ::testing::SetArgPointee; -using ::testing::StrictMock; -using ::testing::proto::WhenDeserializedAs; - -// Creates an action SaveArgToVector<k>(vector*) that saves the kth argument in -// |vec|. -ACTION_TEMPLATE( - SaveArgToVector, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(vec)) { - vec->push_back(std::tr1::get<k>(args)); -} - -// Given the ReadCallback of Storage::ReadKey as argument 1, invokes it with a -// permanent failure status code. -ACTION(InvokeReadCallbackFailure) { - arg1->Run(pair<Status, string>(Status(Status::PERMANENT_FAILURE, ""), "")); - delete arg1; -} - -// Given the WriteCallback of Storage::WriteKey as argument 2, invokes it with -// a success status code. -ACTION(InvokeWriteCallbackSuccess) { - arg2->Run(Status(Status::SUCCESS, "")); - delete arg2; -} - -// Tests the basic functionality of the invalidation client. -class InvalidationClientImplTest : public UnitTestBase { - public: - virtual ~InvalidationClientImplTest() {} - - // Performs setup for protocol handler unit tests, e.g. creating resource - // components and setting up common expectations for certain mock objects. - virtual void SetUp() { - UnitTestBase::SetUp(); - InitCommonExpectations(); // Set up expectations for common mock operations - - - // Clear throttle limits so that it does not interfere with any test. - InvalidationClientImpl::InitConfig(&config); - config.set_smear_percent(kDefaultSmearPercent); - config.mutable_protocol_handler_config()->clear_rate_limit(); - - // Set up the listener scheduler to run any runnable that it receives. - EXPECT_CALL(*listener_scheduler, Schedule(_, _)) - .WillRepeatedly(InvokeAndDeleteClosure<1>()); - - // Create the actual client. - Random* random = new Random(InvalidationClientUtil::GetCurrentTimeMs( - resources->internal_scheduler())); - client.reset(new InvalidationClientImpl( - resources.get(), random, ClientType_Type_TEST, "clientName", config, - "InvClientTest", &listener)); - } - - // Starts the Ticl and ensures that the initialize message is sent. In - // response, gives a tokencontrol message to the protocol handler and makes - // sure that ready is called. client_messages is the list of messages expected - // from the client. The 0th message corresponds to the initialization message - // sent out by the client. - void StartClient() { - // Start the client. - client.get()->Start(); - - // Let the message be sent out. - internal_scheduler->PassTime( - GetMaxBatchingDelay(config.protocol_handler_config())); - - // Check that the message contains an initializeMessage. - ClientToServerMessage client_message; - client_message.ParseFromString(outgoing_messages[0]); - ASSERT_TRUE(client_message.has_initialize_message()); - string nonce = client_message.initialize_message().nonce(); - - // Create the token control message and hand it to the protocol handler. - ServerToClientMessage sc_message; - InitServerHeader(nonce, sc_message.mutable_header()); - string new_token = "new token"; - sc_message.mutable_token_control_message()->set_new_token(new_token); - ProcessIncomingMessage(sc_message, MessageHandlingDelay()); - } - - // Sets the expectations so that the Ticl is ready to be started such that - // |num_outgoing_messages| are expected to be sent by the ticl. These messages - // will be saved in |outgoing_messages|. - void SetExpectationsForTiclStart(int num_outgoing_msgs) { - // Set up expectations for number of messages expected on the network. - EXPECT_CALL(*network, SendMessage(_)) - .Times(num_outgoing_msgs) - .WillRepeatedly(SaveArgToVector<0>(&outgoing_messages)); - - // Expect the storage to perform a read key that we will fail. - EXPECT_CALL(*storage, ReadKey(_, _)) - .WillOnce(InvokeReadCallbackFailure()); - - // Expect the listener to indicate that it is ready and let it reissue - // registrations. - EXPECT_CALL(listener, Ready(Eq(client.get()))); - EXPECT_CALL(listener, ReissueRegistrations(Eq(client.get()), _, _)); - - // Expect the storage layer to receive the write of the session token. - EXPECT_CALL(*storage, WriteKey(_, _, _)) - .WillOnce(InvokeWriteCallbackSuccess()); - } - - // - // Test state maintained for every test. - // - - // Messages sent by the Ticl. - vector<string> outgoing_messages; - - // Configuration for the protocol handler (uses defaults). - ClientConfigP config; - - // The client being tested. Created fresh for each test function. - scoped_ptr<InvalidationClientImpl> client; - - // A mock invalidation listener. - StrictMock<MockInvalidationListener> listener; -}; - -// Starts the ticl and checks that appropriate calls are made on the listener -// and that a proper message is sent on the network. -TEST_F(InvalidationClientImplTest, Start) { - SetExpectationsForTiclStart(1); - StartClient(); -} - -// Tests that GenerateNonce generates a unique nonce on every call. -TEST_F(InvalidationClientImplTest, GenerateNonce) { - // Create a random number generated seeded with the current time. - scoped_ptr<Random> random; - random.reset(new Random(InvalidationClientUtil::GetCurrentTimeMs( - resources->internal_scheduler()))); - - // Generate two nonces and make sure they are distinct. (The chances - // of a collision should be vanishingly small since our correctness - // relies upon no collisions.) - string nonce1 = InvalidationClientCore::GenerateNonce(random.get()); - string nonce2 = InvalidationClientCore::GenerateNonce(random.get()); - ASSERT_NE(nonce1, nonce2); -} - -// Starts the Ticl, registers for a few objects, gets success and ensures that -// the right listener methods are invoked. -TEST_F(InvalidationClientImplTest, Register) { - SetExpectationsForTiclStart(2); - - // Set some expectations for registration status messages. - vector<ObjectId> saved_oids; - EXPECT_CALL(listener, - InformRegistrationStatus(Eq(client.get()), _, - InvalidationListener::REGISTERED)) - .Times(3) - .WillRepeatedly(SaveArgToVector<1>(&saved_oids)); - - // Start the Ticl. - StartClient(); - - // Synthesize a few test object ids. - int num_objects = 3; - vector<ObjectIdP> oid_protos; - vector<ObjectId> oids; - InitTestObjectIds(num_objects, &oid_protos); - ConvertFromObjectIdProtos(oid_protos, &oids); - - // Register - client.get()->Register(oids); - - // Let the message be sent out. - internal_scheduler->PassTime( - GetMaxBatchingDelay(config.protocol_handler_config())); - - // Give a registration status message to the protocol handler and wait for - // the listener calls. - ServerToClientMessage message; - InitServerHeader(client.get()->GetClientToken(), message.mutable_header()); - vector<RegistrationStatus> registration_statuses; - MakeRegistrationStatusesFromObjectIds(oid_protos, true, true, - ®istration_statuses); - for (int i = 0; i < num_objects; ++i) { - message.mutable_registration_status_message() - ->add_registration_status()->CopyFrom(registration_statuses[i]); - } - - // Give this message to the protocol handler. - ProcessIncomingMessage(message, EndOfTestWaitTime()); - - // Check the object ids. - ASSERT_TRUE(CompareVectorsAsSets(saved_oids, oids)); - - // Check the registration message. - ClientToServerMessage client_msg; - client_msg.ParseFromString(outgoing_messages[1]); - ASSERT_TRUE(client_msg.has_registration_message()); - ASSERT_FALSE(client_msg.has_info_message()); - ASSERT_FALSE(client_msg.has_registration_sync_message()); - - RegistrationMessage expected_msg; - InitRegistrationMessage(oid_protos, true, &expected_msg); - const RegistrationMessage& actual_msg = client_msg.registration_message(); - ASSERT_TRUE(CompareMessages(expected_msg, actual_msg)); -} - -// Tests that given invalidations from the server, the right listener methods -// are invoked. Ack the invalidations and make sure that the ack message is sent -// out. Include a payload in one invalidation and make sure the client does not -// include it in the ack. -TEST_F(InvalidationClientImplTest, Invalidations) { - // Set some expectations for starting the client. - SetExpectationsForTiclStart(2); - - // Synthesize a few test object ids. - int num_objects = 3; - vector<ObjectIdP> oid_protos; - vector<ObjectId> oids; - InitTestObjectIds(num_objects, &oid_protos); - ConvertFromObjectIdProtos(oid_protos, &oids); - - // Set up listener invalidation calls. - vector<InvalidationP> invalidations; - vector<Invalidation> expected_invs; - MakeInvalidationsFromObjectIds(oid_protos, &invalidations); - // Put a payload in one of the invalidations. - invalidations[0].set_payload("this is a payload"); - ConvertFromInvalidationProtos(invalidations, &expected_invs); - - // Set up expectations for the acks. - vector<Invalidation> saved_invs; - vector<AckHandle> ack_handles; - - EXPECT_CALL(listener, Invalidate(Eq(client.get()), _, _)) - .Times(3) - .WillRepeatedly(DoAll(SaveArgToVector<1>(&saved_invs), - SaveArgToVector<2>(&ack_handles))); - - // Start the Ticl. - StartClient(); - - // Give this message to the protocol handler. - ServerToClientMessage message; - InitServerHeader(client.get()->GetClientToken(), message.mutable_header()); - InitInvalidationMessage(invalidations, - message.mutable_invalidation_message()); - - // Process the incoming invalidation message. - ProcessIncomingMessage(message, MessageHandlingDelay()); - - // Check the invalidations. - ASSERT_TRUE(CompareVectorsAsSets(expected_invs, saved_invs)); - - // Ack the invalidations now and wait for them to be sent out. - for (int i = 0; i < num_objects; i++) { - client.get()->Acknowledge(ack_handles[i]); - } - internal_scheduler->PassTime( - GetMaxBatchingDelay(config.protocol_handler_config())); - - // Check that the ack message is as expected. - ClientToServerMessage client_msg; - client_msg.ParseFromString(outgoing_messages[1]); - ASSERT_TRUE(client_msg.has_invalidation_ack_message()); - - InvalidationMessage expected_msg; - // The client should strip the payload from the invalidation. - invalidations[0].clear_payload(); - InitInvalidationMessage(invalidations, &expected_msg); - const InvalidationMessage& actual_msg = - client_msg.invalidation_ack_message(); - ASSERT_TRUE(CompareMessages(expected_msg, actual_msg)); -} - -// Give a registration sync request message and an info request message to the -// client and wait for the sync message and the info message to go out. -TEST_F(InvalidationClientImplTest, ServerRequests) { - // Set some expectations for starting the client. - SetExpectationsForTiclStart(2); - - // Start the ticl. - StartClient(); - - // Make the server to client message. - ServerToClientMessage message; - InitServerHeader(client.get()->GetClientToken(), message.mutable_header()); - - // Add a registration sync request message. - message.mutable_registration_sync_request_message(); - - // Add an info request message. - message.mutable_info_request_message()->add_info_type( - InfoRequestMessage_InfoType_GET_PERFORMANCE_COUNTERS); - - // Give it to the prototol handler. - ProcessIncomingMessage(message, EndOfTestWaitTime()); - - // Make sure that the message is as expected. - ClientToServerMessage client_msg; - client_msg.ParseFromString(outgoing_messages[1]); - ASSERT_TRUE(client_msg.has_info_message()); - ASSERT_TRUE(client_msg.has_registration_sync_message()); -} - -// Tests that an incoming unknown failure message results in the app being -// informed about it. -TEST_F(InvalidationClientImplTest, IncomingErrorMessage) { - SetExpectationsForTiclStart(1); - - // Set up listener expectation for error. - EXPECT_CALL(listener, InformError(Eq(client.get()), _)); - - // Start the ticl. - StartClient(); - - // Give the error message to the protocol handler. - ServerToClientMessage message; - InitServerHeader(client.get()->GetClientToken(), message.mutable_header()); - InitErrorMessage(ErrorMessage_Code_UNKNOWN_FAILURE, "Some error message", - message.mutable_error_message()); - ProcessIncomingMessage(message, EndOfTestWaitTime()); -} - -// Tests that an incoming auth failure message results in the app being informed -// about it and the registrations being removed. -TEST_F(InvalidationClientImplTest, IncomingAuthErrorMessage) { - SetExpectationsForTiclStart(2); - - // One object to register for. - int num_objects = 1; - vector<ObjectIdP> oid_protos; - vector<ObjectId> oids; - InitTestObjectIds(num_objects, &oid_protos); - ConvertFromObjectIdProtos(oid_protos, &oids); - - // Expect error and registration failure from the ticl. - EXPECT_CALL(listener, InformError(Eq(client.get()), _)); - EXPECT_CALL(listener, InformRegistrationFailure(Eq(client.get()), Eq(oids[0]), - Eq(false), _)); - - // Start the client. - StartClient(); - - // Register and let the message be sent out. - client.get()->Register(oids[0]); - internal_scheduler->PassTime( - GetMaxBatchingDelay(config.protocol_handler_config())); - - // Give this message to the protocol handler. - ServerToClientMessage message; - InitServerHeader(client.get()->GetClientToken(), message.mutable_header()); - InitErrorMessage(ErrorMessage_Code_AUTH_FAILURE, "Auth error message", - message.mutable_error_message()); - ProcessIncomingMessage(message, EndOfTestWaitTime()); -} - -// Tests that a registration that times out results in a reg sync message being -// sent out. -TEST_F(InvalidationClientImplTest, NetworkTimeouts) { - // Set some expectations for starting the client. - SetExpectationsForTiclStart(3); - - // One object to register for. - int num_objects = 1; - vector<ObjectIdP> oid_protos; - vector<ObjectId> oids; - InitTestObjectIds(num_objects, &oid_protos); - ConvertFromObjectIdProtos(oid_protos, &oids); - - // Start the client. - StartClient(); - - // Register for an object. - client.get()->Register(oids[0]); - - // Let the registration message be sent out. - internal_scheduler->PassTime( - GetMaxBatchingDelay(config.protocol_handler_config())); - - // Now let the network timeout occur and an info message be sent. - TimeDelta timeout_delay = GetMaxDelay(config.network_timeout_delay_ms()); - internal_scheduler->PassTime(timeout_delay); - - // Check that the message sent out is an info message asking for the server's - // summary. - ClientToServerMessage client_msg2; - client_msg2.ParseFromString(outgoing_messages[2]); - ASSERT_TRUE(client_msg2.has_info_message()); - ASSERT_TRUE( - client_msg2.info_message().server_registration_summary_requested()); - internal_scheduler->PassTime(EndOfTestWaitTime()); -} - -// Tests that an incoming message without registration summary does not -// cause the registration summary in the client to be changed. -TEST_F(InvalidationClientImplTest, NoRegistrationSummary) { - // Test plan: Initialze the ticl, let it get a token with a ServerToClient - // message that has no registration summary. - - // Set some expectations for starting the client and start the client. - // Give it a summary with 1 reg. - reg_summary.get()->set_num_registrations(1); - SetExpectationsForTiclStart(1); - StartClient(); - - // Now give it an message with no summary. It should not reset to a summary - // with zero registrations. - reg_summary.reset(NULL); - ServerToClientMessage message; - InitServerHeader(client.get()->GetClientToken(), message.mutable_header()); - ProcessIncomingMessage(message, EndOfTestWaitTime()); - - // Check that the registration manager state did not change. - string manager_serial_state; - client->GetRegistrationManagerStateAsSerializedProto(&manager_serial_state); - RegistrationManagerStateP reg_manager_state; - reg_manager_state.ParseFromString(manager_serial_state); - - // Check that the registration manager state's number of registrations is 1. - TLOG(logger, INFO, "Reg manager state: %s", - ProtoHelpers::ToString(reg_manager_state).c_str()); - ASSERT_EQ(1, reg_manager_state.server_summary().num_registrations()); -} - -// Tests that heartbeats are sent out as time advances. -TEST_F(InvalidationClientImplTest, Heartbeats) { - // Set some expectations for starting the client. - SetExpectationsForTiclStart(2); - - // Start the client. - StartClient(); - - // Now let the heartbeat occur and an info message be sent. - TimeDelta heartbeat_delay = GetMaxDelay(config.heartbeat_interval_ms() + - config.protocol_handler_config().batching_delay_ms()); - internal_scheduler->PassTime(heartbeat_delay); - - // Check that the heartbeat is sent and it does not ask for the server's - // summary. - ClientToServerMessage client_msg1; - client_msg1.ParseFromString(outgoing_messages[1]); - ASSERT_TRUE(client_msg1.has_info_message()); - ASSERT_FALSE( - client_msg1.info_message().server_registration_summary_requested()); - internal_scheduler->PassTime(EndOfTestWaitTime()); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-util.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-util.h deleted file mode 100644 index d5a2cc190d5210cfc490c919646f4ae000bfb2db..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/invalidation-client-util.h +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Useful utility functions for the TICL - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_UTIL_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_UTIL_H_ - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/deps/time.h" - -namespace invalidation { - -class InvalidationClientUtil { - public: - /* Returns the time in milliseconds. */ - static int64 GetTimeInMillis(const Time& time) { - return time.ToInternalValue() / Time::kMicrosecondsPerMillisecond; - } - - /* Returns the current time in the scheduler's epoch in milliseconds. */ - static int64 GetCurrentTimeMs(Scheduler* scheduler) { - return GetTimeInMillis(scheduler->GetCurrentTime()); - } -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_INVALIDATION_CLIENT_UTIL_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/log-macro.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/log-macro.h deleted file mode 100644 index 1ac374a1bc7793c25bedefa09a92fb5d8dbb9658..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/log-macro.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// A simple logging macro specifically for the invalidation client library. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_LOG_MACRO_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_LOG_MACRO_H_ - -#define TLOG(logger, level, str, ...) \ - logger->Log(Logger::level ## _LEVEL, __FILE__, __LINE__, str, ##__VA_ARGS__); - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_LOG_MACRO_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/object-id-digest-utils.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/object-id-digest-utils.cc deleted file mode 100644 index 182e9cad3e8adb5c6d7f2e82973c718c938f4d5a..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/object-id-digest-utils.cc +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Digest-related utilities for object ids. - -#include "google/cacheinvalidation/impl/object-id-digest-utils.h" - -namespace invalidation { - -string ObjectIdDigestUtils::GetDigest( - const ObjectIdP& object_id, DigestFunction* digest_fn) { - digest_fn->Reset(); - int source = object_id.source(); - string buffer(4, 0); - - // Little endian number for type followed by bytes. - buffer[0] = source & 0xff; - buffer[1] = (source >> 8) & 0xff; - buffer[2] = (source >> 16) & 0xff; - buffer[3] = (source >> 24) & 0xff; - - digest_fn->Update(buffer); - digest_fn->Update(object_id.name()); - return digest_fn->GetDigest(); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/object-id-digest-utils.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/object-id-digest-utils.h deleted file mode 100644 index 8adb3167a9b8c41dce38eb260fcf1e23f957d21b..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/object-id-digest-utils.h +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Digest-related utilities for object ids. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_OBJECT_ID_DIGEST_UTILS_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_OBJECT_ID_DIGEST_UTILS_H_ - -#include <map> - -#include "google/cacheinvalidation/deps/digest-function.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::map; - -class ObjectIdDigestUtils { - public: - /* Returns the digest of the set of keys in the given map. */ - template<typename T> - static string GetDigest( - map<string, T> registrations, DigestFunction* digest_fn) { - digest_fn->Reset(); - for (map<string, ObjectIdP>::iterator iter = registrations.begin(); - iter != registrations.end(); ++iter) { - digest_fn->Update(iter->first); - } - return digest_fn->GetDigest(); - } - - /* Returns the digest of object_id using digest_fn. */ - static string GetDigest( - const ObjectIdP& object_id, DigestFunction* digest_fn); -}; -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_OBJECT_ID_DIGEST_UTILS_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/persistence-utils.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/persistence-utils.cc deleted file mode 100644 index e9c1b3d962fb544758515a3800003d45f52682b7..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/persistence-utils.cc +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Utility methods for handling the Ticl persistent state. - -#include "google/cacheinvalidation/impl/persistence-utils.h" - -namespace invalidation { - -void PersistenceUtils::SerializeState( - PersistentTiclState state, DigestFunction* digest_fn, string* result) { - string mac = GenerateMac(state, digest_fn); - PersistentStateBlob blob; - blob.mutable_ticl_state()->CopyFrom(state); - blob.set_authentication_code(mac); - blob.SerializeToString(result); -} - -bool PersistenceUtils::DeserializeState( - Logger* logger, const string& state_blob_bytes, DigestFunction* digest_fn, - PersistentTiclState* ticl_state) { - PersistentStateBlob state_blob; - state_blob.ParseFromString(state_blob_bytes); - if (!state_blob.IsInitialized()) { - TLOG(logger, WARNING, "could not parse state blob from %s", - state_blob_bytes.c_str()); - return false; - } - - // Check the mac in the envelope against the recomputed mac from the state. - ticl_state->CopyFrom(state_blob.ticl_state()); - const string& mac = GenerateMac(*ticl_state, digest_fn); - if (mac != state_blob.authentication_code()) { - TLOG(logger, WARNING, "Ticl state failed MAC check: computed %s vs %s", - mac.c_str(), state_blob.authentication_code().c_str()); - return false; - } - return true; -} - -string PersistenceUtils::GenerateMac( - const PersistentTiclState& state, DigestFunction* digest_fn) { - string serialized; - state.SerializeToString(&serialized); - digest_fn->Reset(); - digest_fn->Update(serialized); - return digest_fn->GetDigest(); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/persistence-utils.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/persistence-utils.h deleted file mode 100644 index e9dc96ee268c8d6531908ef107a2680c38532e0a..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/persistence-utils.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Utility methods for handling the Ticl persistent state. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_PERSISTENCE_UTILS_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_PERSISTENCE_UTILS_H_ - -#include <string> - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/deps/digest-function.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" -#include "google/cacheinvalidation/impl/log-macro.h" - -namespace invalidation { - -class PersistenceUtils { - public: - /* Serializes a Ticl state blob. */ - static void SerializeState( - PersistentTiclState state, DigestFunction* digest_fn, string* result); - - /* Deserializes a Ticl state blob. Returns whether the parsed state could be - * parsed. - */ - static bool DeserializeState( - Logger* logger, const string& state_blob_bytes, DigestFunction* digest_fn, - PersistentTiclState* ticl_state); - - /* Returns a message authentication code over state. */ - static string GenerateMac( - const PersistentTiclState& state, DigestFunction* digest_fn); - - private: - PersistenceUtils() { - // Prevent instantiation. - } -}; // class PersistenceUtils - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_PERSISTENCE_UTILS_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-converter.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-converter.cc deleted file mode 100644 index e6d54b61f46dee3d89458e6666cb69bc5155c137..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-converter.cc +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Utilities to convert between protobufs and externally-exposed types in the -// Ticl. - -#include "google/cacheinvalidation/impl/proto-converter.h" - -#include "google/cacheinvalidation/deps/logging.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" - -namespace invalidation { - -void ProtoConverter::ConvertFromObjectIdProto( - const ObjectIdP& object_id_proto, ObjectId* object_id) { - object_id->Init(object_id_proto.source(), object_id_proto.name()); -} - -void ProtoConverter::ConvertToObjectIdProto( - const ObjectId& object_id, ObjectIdP* object_id_proto) { - object_id_proto->set_source(object_id.source()); - object_id_proto->set_name(object_id.name()); -} - -void ProtoConverter::ConvertFromInvalidationProto( - const InvalidationP& invalidation_proto, Invalidation* invalidation) { - ObjectId object_id; - ConvertFromObjectIdProto(invalidation_proto.object_id(), &object_id); - bool is_trickle_restart = invalidation_proto.is_trickle_restart(); - if (invalidation_proto.has_payload()) { - invalidation->Init(object_id, invalidation_proto.version(), - invalidation_proto.payload(), is_trickle_restart); - } else { - invalidation->Init(object_id, invalidation_proto.version(), - is_trickle_restart); - } -} - -void ProtoConverter::ConvertToInvalidationProto( - const Invalidation& invalidation, InvalidationP* invalidation_proto) { - ConvertToObjectIdProto( - invalidation.object_id(), invalidation_proto->mutable_object_id()); - invalidation_proto->set_version(invalidation.version()); - if (invalidation.has_payload()) { - invalidation_proto->set_payload(invalidation.payload()); - } - bool is_trickle_restart = invalidation.is_trickle_restart_for_internal_use(); - invalidation_proto->set_is_trickle_restart(is_trickle_restart); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-converter.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-converter.h deleted file mode 100644 index 7c7c43205c7fc895a561891a6d7efbe3d08e633b..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-converter.h +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Utilities to convert between protobufs and externally-exposed types in the -// Ticl. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_PROTO_CONVERTER_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_PROTO_CONVERTER_H_ - -#include "google/cacheinvalidation/include/types.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" - -namespace invalidation { - -class ProtoConverter { - public: - /* Converts an object id protocol buffer 'object_id_proto' to the - * corresponding external type 'object_id'. - */ - static void ConvertFromObjectIdProto( - const ObjectIdP& object_id_proto, ObjectId* object_id); - - /* Converts an object id 'object_id' to the corresponding protocol buffer - * 'object_id_proto'. - */ - static void ConvertToObjectIdProto( - const ObjectId& object_id, ObjectIdP* object_id_proto); - - /* Converts an invalidation protocol buffer 'invalidation_proto' to the - * corresponding external object 'invalidation'. - */ - static void ConvertFromInvalidationProto( - const InvalidationP& invalidation_proto, Invalidation* invalidation); - - /* Converts an invalidation to the corresponding protocol - * buffer and returns it. - */ - static void ConvertToInvalidationProto( - const Invalidation& invalidation, InvalidationP* invalidation_proto); - - static bool IsAllObjectIdP(const ObjectIdP& object_id_proto) { - return (object_id_proto.source() == ObjectSource_Type_INTERNAL) && - (object_id_proto.name() == ""); - } - - private: - ProtoConverter() { - // To prevent instantiation. - } -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_PROTO_CONVERTER_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-helpers.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-helpers.cc deleted file mode 100644 index 68cfe02a98402855c1fa02cdd80622a893f480f5..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-helpers.cc +++ /dev/null @@ -1,473 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Useful utility functions for the TICL - -#include "google/cacheinvalidation/impl/proto-helpers.h" - -#include <sstream> - -#include "google/cacheinvalidation/client_test_internal.pb.h" -#include "google/cacheinvalidation/deps/string_util.h" - -namespace invalidation { - -using ::ipc::invalidation::RegistrationManagerStateP; - -// Defines a ToString template method specialization for the given type. -#define DEFINE_TO_STRING(type) \ - template<> \ - string ProtoHelpers::ToString(const type& message) - -// Creates a stringstream |stream| and emits a leading "{ " to it. -#define BEGIN() \ - std::stringstream stream; \ - stream << "{ " - -// Emits a closing " }" on |stream| and returns the string that has been built. -#define END() \ - stream << " }"; \ - return stream.str() - -// Defines a trivial ToString method for a type (which just returns "<type>"). -#define DEFINE_TRIVIAL_TO_STRING(type) \ - DEFINE_TO_STRING(type) { \ - return "<" #type ">"; \ - } - -// Emits "field: <field value as string>" if |field| is present in |message|. -#define OPTIONAL(field) \ - if (message.has_##field()) { \ - stream << #field << ": " << ToString(message.field()) << " "; \ - } - -// Emits "field: <field value as string>" for each instance of field in message. -#define REPEATED(field) \ - for (int i = 0; i < message.field##_size(); ++i) { \ - stream << #field << ": " << ToString(message.field(i)) << " "; \ - } - -// Expands to a case branch that returns "name" if the implicitly tested -// expression is equal to the enum constant |name| in the given |type|. -#define ENUM_VALUE(type, name) case type##_##name: return #name - -// Expands to a default case branch that returns the string representation of -// |message|. -#define ENUM_UNKNOWN() default: return SimpleItoa(message) - -DEFINE_TO_STRING(bool) { - return message ? "true" : "false"; -} - -DEFINE_TO_STRING(int) { - std::stringstream stream; - stream << message; - return stream.str(); -} - -DEFINE_TO_STRING(int64) { - std::stringstream stream; - stream << message; - return stream.str(); -} - -/* - * Three arrays that store the representation of each character from 0 to 255. - * The ith number's octal representation is: CHAR_OCTAL_STRINGS1[i], - * CHAR_OCTAL_STRINGS2[i], CHAR_OCTAL_STRINGS3[i] - * <p> - * E.g., if the number 128, these arrays contain 2, 0, 0 at index 128. We use - * 3 char arrays instead of an array of strings since the code path for a - * character append operation is quite a bit shorterthan the append operation - * for strings. - */ -char ProtoHelpers::CHAR_OCTAL_STRINGS1[]; -char ProtoHelpers::CHAR_OCTAL_STRINGS2[]; -char ProtoHelpers::CHAR_OCTAL_STRINGS3[]; -bool ProtoHelpers::is_initialized = false; - -template<> -string ProtoHelpers::ToString(const string& bytes) { - // This is a racy initialization but that is ok since we are initializing to - // the same values. - if (!is_initialized) { - // Initialize the array with the Octal string values so that we do not have - // to do string.format for every byte during runtime. - for (int i = 0; i < ProtoHelpers::NUM_CHARS; i++) { - string value = StringPrintf("%03o", i); - ProtoHelpers::CHAR_OCTAL_STRINGS1[i] = value[0]; - ProtoHelpers::CHAR_OCTAL_STRINGS2[i] = value[1]; - ProtoHelpers::CHAR_OCTAL_STRINGS3[i] = value[2]; - } - is_initialized = true; - } - string builder; - builder.reserve(3 * bytes.length() + 2); - builder += "\""; - for (size_t i = 0; i < bytes.length(); i++) { - char c = bytes[i]; - switch (c) { - case '\n': builder += '\\'; builder += 'n'; break; - case '\r': builder += '\\'; builder += 'r'; break; - case '\t': builder += '\\'; builder += 't'; break; - case '\"': builder += '\\'; builder += '"'; break; - case '\\': builder += '\\'; builder += '\\'; break; - default: - if ((c >= 32) && (c < 127) && c != '\'') { - builder += c; - } else { - int byteValue = c; - if (c < 0) { - byteValue = c + 256; - } - builder += '\\'; - builder += CHAR_OCTAL_STRINGS1[byteValue]; - builder += CHAR_OCTAL_STRINGS2[byteValue]; - builder += CHAR_OCTAL_STRINGS3[byteValue]; - } - break; - } - } - builder += "\""; - return builder; -} - -void ProtoHelpers::InitRegistrationP(const ObjectIdP& oid, - RegistrationP::OpType op_type, RegistrationP* reg) { - reg->mutable_object_id()->CopyFrom(oid); - reg->set_op_type(op_type); -} - -void ProtoHelpers::InitRateLimitP(int window_ms, int count, - RateLimitP *rate_limit) { - rate_limit->set_window_ms(window_ms); - rate_limit->set_count(count); -} - -void ProtoHelpers::InitInitializeMessage( - const ApplicationClientIdP& application_client_id, const string& nonce, - InitializeMessage* init_msg) { - init_msg->set_client_type(application_client_id.client_type()); - init_msg->mutable_application_client_id()->CopyFrom( - application_client_id); - init_msg->set_nonce(nonce); - init_msg->set_digest_serialization_type( - InitializeMessage_DigestSerializationType_BYTE_BASED); -} - -void ProtoHelpers::InitClientVersion(const string& platform, - const string& application_info, ClientVersion* client_version) { - Version* version = client_version->mutable_version(); - version->set_major_version(Constants::kClientMajorVersion); - version->set_minor_version(Constants::kClientMinorVersion); - client_version->set_platform(platform); - client_version->set_language("C++"); - client_version->set_application_info(application_info); -} - -void ProtoHelpers::InitProtocolVersion(ProtocolVersion* protocol_version) { - Version* version = protocol_version->mutable_version(); - version->set_major_version(Constants::kProtocolMajorVersion); - version->set_minor_version(Constants::kProtocolMinorVersion); -} - -void ProtoHelpers::InitConfigVersion(Version* config_version) { - config_version->set_major_version(Constants::kConfigMajorVersion); - config_version->set_minor_version(Constants::kConfigMinorVersion); -} - -DEFINE_TO_STRING(ErrorMessage::Code) { - switch (message) { - ENUM_VALUE(ErrorMessage_Code, AUTH_FAILURE); - ENUM_VALUE(ErrorMessage_Code, UNKNOWN_FAILURE); - ENUM_UNKNOWN(); - } -} -DEFINE_TO_STRING(InfoRequestMessage::InfoType) { - switch (message) { - ENUM_VALUE(InfoRequestMessage_InfoType, GET_PERFORMANCE_COUNTERS); - ENUM_UNKNOWN(); - } -} - -DEFINE_TO_STRING(InitializeMessage::DigestSerializationType) { - switch (message) { - ENUM_VALUE(InitializeMessage_DigestSerializationType, BYTE_BASED); - ENUM_VALUE(InitializeMessage_DigestSerializationType, NUMBER_BASED); - ENUM_UNKNOWN(); - } -} - -DEFINE_TO_STRING(StatusP::Code) { - switch (message) { - ENUM_VALUE(StatusP_Code, SUCCESS); - ENUM_VALUE(StatusP_Code, TRANSIENT_FAILURE); - ENUM_VALUE(StatusP_Code, PERMANENT_FAILURE); - ENUM_UNKNOWN(); - } -} - -DEFINE_TO_STRING(RegistrationP::OpType) { - switch (message) { - ENUM_VALUE(RegistrationP_OpType, REGISTER); - ENUM_VALUE(RegistrationP_OpType, UNREGISTER); - ENUM_UNKNOWN(); - } -} - -DEFINE_TO_STRING(RegistrationSyncRequestMessage) { - BEGIN(); - END(); -} - -DEFINE_TO_STRING(Version) { - BEGIN(); - OPTIONAL(major_version); - OPTIONAL(minor_version); - END(); -} - -DEFINE_TO_STRING(ClientVersion) { - BEGIN(); - OPTIONAL(version); - OPTIONAL(platform); - OPTIONAL(language); - OPTIONAL(application_info); - END(); -} - -DEFINE_TO_STRING(ProtocolVersion) { - BEGIN(); - OPTIONAL(version); - END(); -} - -DEFINE_TO_STRING(InfoRequestMessage) { - BEGIN(); - REPEATED(info_type); - END(); -} - -DEFINE_TO_STRING(ConfigChangeMessage) { - BEGIN(); - OPTIONAL(next_message_delay_ms); - END(); -} - -DEFINE_TO_STRING(PropertyRecord) { - BEGIN(); - OPTIONAL(name); - OPTIONAL(value); - END(); -} - -DEFINE_TO_STRING(RateLimitP) { - BEGIN(); - OPTIONAL(window_ms); - OPTIONAL(count); - END(); -} - -DEFINE_TO_STRING(ProtocolHandlerConfigP) { - BEGIN(); - OPTIONAL(batching_delay_ms); - REPEATED(rate_limit); - END(); -} - -DEFINE_TO_STRING(ClientConfigP) { - BEGIN(); - OPTIONAL(version); - OPTIONAL(network_timeout_delay_ms); - OPTIONAL(write_retry_delay_ms); - OPTIONAL(heartbeat_interval_ms); - OPTIONAL(perf_counter_delay_ms); - OPTIONAL(max_exponential_backoff_factor); - OPTIONAL(smear_percent); - OPTIONAL(is_transient); - OPTIONAL(initial_persistent_heartbeat_delay_ms); - OPTIONAL(protocol_handler_config); - END(); -} - -DEFINE_TO_STRING(InfoMessage) { - BEGIN(); - OPTIONAL(client_version); - REPEATED(config_parameter); - REPEATED(performance_counter); - OPTIONAL(server_registration_summary_requested); - END(); -} - -DEFINE_TO_STRING(ErrorMessage) { - BEGIN(); - OPTIONAL(code); - OPTIONAL(description); - END(); -} - -DEFINE_TO_STRING(RegistrationSummary) { - BEGIN(); - OPTIONAL(num_registrations); - OPTIONAL(registration_digest); - END(); -} - -DEFINE_TO_STRING(ObjectIdP) { - BEGIN(); - OPTIONAL(source); - OPTIONAL(name); - END(); -} - -DEFINE_TO_STRING(InvalidationP) { - BEGIN(); - OPTIONAL(object_id); - OPTIONAL(is_known_version); - OPTIONAL(version); - OPTIONAL(is_trickle_restart); - OPTIONAL(payload); - END(); -} - -DEFINE_TO_STRING(AckHandleP) { - BEGIN(); - OPTIONAL(invalidation); - END(); -} - -DEFINE_TO_STRING(ApplicationClientIdP) { - BEGIN(); - OPTIONAL(client_type); - OPTIONAL(client_name); - END(); -} - -DEFINE_TO_STRING(StatusP) { - BEGIN(); - OPTIONAL(code); - OPTIONAL(description); - END(); -} - -DEFINE_TO_STRING(RegistrationP) { - BEGIN(); - OPTIONAL(object_id); - OPTIONAL(op_type); - END(); -} - -DEFINE_TO_STRING(RegistrationStatus) { - BEGIN(); - OPTIONAL(registration); - OPTIONAL(status); - END(); -} - -DEFINE_TO_STRING(ClientHeader) { - BEGIN(); - OPTIONAL(protocol_version); - OPTIONAL(client_token); - OPTIONAL(registration_summary); - OPTIONAL(client_time_ms); - OPTIONAL(max_known_server_time_ms); - OPTIONAL(message_id); - END(); -} - -DEFINE_TO_STRING(InitializeMessage) { - BEGIN(); - OPTIONAL(client_type); - OPTIONAL(nonce); - OPTIONAL(application_client_id); - OPTIONAL(digest_serialization_type); - END(); -} - -DEFINE_TO_STRING(RegistrationMessage) { - BEGIN(); - REPEATED(registration); - END(); -} - -DEFINE_TO_STRING(InvalidationMessage) { - BEGIN(); - REPEATED(invalidation); - END(); -} - -DEFINE_TO_STRING(RegistrationSubtree) { - BEGIN(); - REPEATED(registered_object); - END(); -} -DEFINE_TO_STRING(RegistrationSyncMessage) { - BEGIN(); - REPEATED(subtree); - END(); -} - -DEFINE_TO_STRING(ClientToServerMessage) { - BEGIN(); - OPTIONAL(header); - OPTIONAL(initialize_message); - OPTIONAL(registration_message); - OPTIONAL(registration_sync_message); - OPTIONAL(invalidation_ack_message); - OPTIONAL(info_message); - END(); -} - -DEFINE_TO_STRING(ServerHeader) { - BEGIN(); - OPTIONAL(protocol_version); - OPTIONAL(client_token); - OPTIONAL(registration_summary); - OPTIONAL(server_time_ms); - OPTIONAL(message_id); - END(); -} - -DEFINE_TO_STRING(TokenControlMessage) { - BEGIN(); - OPTIONAL(new_token); - END(); -} - -DEFINE_TO_STRING(RegistrationStatusMessage) { - BEGIN(); - REPEATED(registration_status); - END(); -} - -DEFINE_TO_STRING(ServerToClientMessage) { - BEGIN(); - OPTIONAL(header); - OPTIONAL(token_control_message); - OPTIONAL(invalidation_message); - OPTIONAL(registration_status_message); - OPTIONAL(registration_sync_request_message); - OPTIONAL(info_request_message); - END(); -} - -DEFINE_TO_STRING(RegistrationManagerStateP) { - BEGIN(); - OPTIONAL(client_summary); - OPTIONAL(server_summary); - REPEATED(registered_objects); - END(); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-helpers.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-helpers.h deleted file mode 100644 index aa6023eb583d0b5451716bce561e1ec4777b43a9..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/proto-helpers.h +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Helper utilities for dealing with protocol buffers. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_PROTO_HELPERS_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_PROTO_HELPERS_H_ - -#include <sstream> -#include <string> - -#include "google/cacheinvalidation/client_protocol.pb.h" -#include "google/cacheinvalidation/deps/logging.h" -#include "google/cacheinvalidation/deps/stl-namespace.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" -#include "google/cacheinvalidation/impl/constants.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::string; -using ::ipc::invalidation::ProtocolVersion; - -// Functor to compare various protocol messages. -struct ProtoCompareLess { - bool operator()(const ObjectIdP& object_id1, - const ObjectIdP& object_id2) const { - // If the sources differ, then the one with the smaller source is the - // smaller object id. - int source_diff = object_id1.source() - object_id2.source(); - if (source_diff != 0) { - return source_diff < 0; - } - // Otherwise, the one with the smaller name is the smaller object id. - return object_id1.name().compare(object_id2.name()) < 0; - } - - bool operator()(const InvalidationP& inv1, - const InvalidationP& inv2) const { - const ProtoCompareLess& compare_less_than = *this; - // If the object ids differ, then the one with the smaller object id is the - // smaller invalidation. - if (compare_less_than(inv1.object_id(), inv2.object_id())) { - return true; - } - if (compare_less_than(inv2.object_id(), inv1.object_id())) { - return false; - } - - // Otherwise, the object ids are the same, so we need to look at the - // versions. - - // We define an unknown version to be less than a known version. - int64 known_version_diff = - inv1.is_known_version() - inv2.is_known_version(); - if (known_version_diff != 0) { - return known_version_diff < 0; - } - - // Otherwise, they're both known both unknown, so the one with the smaller - // version is the smaller invalidation. - return inv1.version() < inv2.version(); - } - - bool operator()(const RegistrationSubtree& reg_subtree1, - const RegistrationSubtree& reg_subtree2) const { - const RepeatedPtrField<ObjectIdP>& objects1 = - reg_subtree1.registered_object(); - const RepeatedPtrField<ObjectIdP>& objects2 = - reg_subtree2.registered_object(); - // If they have different numbers of objects, the one with fewer is smaller. - if (objects1.size() != objects2.size()) { - return objects1.size() < objects2.size(); - } - // Otherwise, compare the object ids in order. - RepeatedPtrField<ObjectIdP>::const_iterator iter1, iter2; - const ProtoCompareLess& compare_less_than = *this; - for (iter1 = objects1.begin(), iter2 = objects2.begin(); - iter1 != objects1.end(); ++iter1, ++iter2) { - if (compare_less_than(*iter1, *iter2)) { - return true; - } - if (compare_less_than(*iter2, *iter1)) { - return false; - } - } - // The registration subtrees are the same. - return false; - } -}; - -// Other protocol message utilities. -class ProtoHelpers { - public: - // Converts a value to a printable/readable string format. - template<typename T> - static string ToString(const T& value); - - // Initializes |reg| to be a (un) registration for object |oid|. - static void InitRegistrationP(const ObjectIdP& oid, - RegistrationP::OpType op_type, RegistrationP* reg); - - static void InitInitializeMessage( - const ApplicationClientIdP& application_client_id, const string& nonce, - InitializeMessage* init_msg); - - // Initializes |protocol_version| to the current protocol version. - static void InitProtocolVersion(ProtocolVersion* protocol_version); - - // Initializes |client_version| to the current client version. - static void InitClientVersion(const string& platform, - const string& application_info, ClientVersion* client_version); - - // Initializes |config_version| to the current config version. - static void InitConfigVersion(Version* config_version); - - // Initializes |rate_limit| with the given window interval and count of - // messages. - static void InitRateLimitP(int window_ms, int count, RateLimitP *rate_limit); - - private: - static const int NUM_CHARS = 256; - static char CHAR_OCTAL_STRINGS1[NUM_CHARS]; - static char CHAR_OCTAL_STRINGS2[NUM_CHARS]; - static char CHAR_OCTAL_STRINGS3[NUM_CHARS]; - - // Have the above arrays been initialized or not. - static bool is_initialized; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_PROTO_HELPERS_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler.cc deleted file mode 100644 index abcec63b5e93bc1aa794033e88e1b2df8ca31b65..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler.cc +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Client for interacting with low-level protocol messages. - -#include "google/cacheinvalidation/impl/protocol-handler.h" - -#include "google/cacheinvalidation/deps/string_util.h" -#include "google/cacheinvalidation/impl/constants.h" -#include "google/cacheinvalidation/impl/invalidation-client-core.h" -#include "google/cacheinvalidation/impl/log-macro.h" -#include "google/cacheinvalidation/impl/proto-helpers.h" -#include "google/cacheinvalidation/impl/recurring-task.h" - -namespace invalidation { - -using ::ipc::invalidation::ConfigChangeMessage; -using ::ipc::invalidation::InfoMessage; -using ::ipc::invalidation::InitializeMessage; -using ::ipc::invalidation::InitializeMessage_DigestSerializationType_BYTE_BASED; -using ::ipc::invalidation::InvalidationMessage; -using ::ipc::invalidation::PropertyRecord; -using ::ipc::invalidation::RegistrationMessage; -using ::ipc::invalidation::RegistrationSyncMessage; -using ::ipc::invalidation::ServerHeader; -using ::ipc::invalidation::ServerToClientMessage; -using ::ipc::invalidation::TokenControlMessage; - -string ServerMessageHeader::ToString() const { - return StringPrintf( - "Token: %s, Summary: %s", ProtoHelpers::ToString(*token_).c_str(), - ProtoHelpers::ToString(*registration_summary_).c_str()); -} - -void ParsedMessage::InitFrom(const ServerToClientMessage& raw_message) { - base_message = raw_message; // Does a deep copy. - - // For each field, assign it to the corresponding protobuf field if - // present, else NULL. - header.InitFrom(&base_message.header().client_token(), - base_message.header().has_registration_summary() ? - &base_message.header().registration_summary() : NULL); - - token_control_message = base_message.has_token_control_message() ? - &base_message.token_control_message() : NULL; - - invalidation_message = base_message.has_invalidation_message() ? - &base_message.invalidation_message() : NULL; - - registration_status_message = - base_message.has_registration_status_message() ? - &base_message.registration_status_message() : NULL; - - registration_sync_request_message = - base_message.has_registration_sync_request_message() ? - &base_message.registration_sync_request_message() : NULL; - - config_change_message = base_message.has_config_change_message() ? - &base_message.config_change_message() : NULL; - - info_request_message = base_message.has_info_request_message() ? - &base_message.info_request_message() : NULL; - - error_message = base_message.has_error_message() ? - &base_message.error_message() : NULL; -} - -ProtocolHandler::ProtocolHandler( - const ProtocolHandlerConfigP& config, SystemResources* resources, - Smearer* smearer, Statistics* statistics, int client_type, - const string& application_name, ProtocolListener* listener, - TiclMessageValidator* msg_validator) - : logger_(resources->logger()), - internal_scheduler_(resources->internal_scheduler()), - network_(resources->network()), - throttle_(config.rate_limit(), internal_scheduler_, - NewPermanentCallback(this, &ProtocolHandler::SendMessageToServer)), - listener_(listener), - msg_validator_(msg_validator), - message_id_(1), - last_known_server_time_ms_(0), - next_message_send_time_ms_(0), - statistics_(statistics), - batcher_(resources->logger(), statistics), - client_type_(client_type) { - // Initialize client version. - ProtoHelpers::InitClientVersion(resources->platform(), application_name, - &client_version_); -} - -void ProtocolHandler::InitConfig(ProtocolHandlerConfigP* config) { - // Add rate limits. - - // Allow at most 3 messages every 5 seconds. - int window_ms = 5 * 1000; - int num_messages_per_window = 3; - - ProtoHelpers::InitRateLimitP(window_ms, num_messages_per_window, - config->add_rate_limit()); -} - -void ProtocolHandler::InitConfigForTest(ProtocolHandlerConfigP* config) { - // No rate limits. - int small_batch_delay_for_test = 200; - config->set_batching_delay_ms(small_batch_delay_for_test); - - // At most one message per second. - ProtoHelpers::InitRateLimitP(1000, 1, config->add_rate_limit()); - // At most six messages per minute. - ProtoHelpers::InitRateLimitP(60 * 1000, 6, config->add_rate_limit()); -} - -bool ProtocolHandler::HandleIncomingMessage(const string& incoming_message, - ParsedMessage* parsed_message) { - ServerToClientMessage message; - message.ParseFromString(incoming_message); - if (!message.IsInitialized()) { - TLOG(logger_, WARNING, "Incoming message is unparseable: %s", - ProtoHelpers::ToString(incoming_message).c_str()); - return false; - } - - // Validate the message. If this passes, we can blindly assume valid messages - // from here on. - TLOG(logger_, FINE, "Incoming message: %s", - ProtoHelpers::ToString(message).c_str()); - - if (!msg_validator_->IsValid(message)) { - statistics_->RecordError( - Statistics::ClientErrorType_INCOMING_MESSAGE_FAILURE); - TLOG(logger_, SEVERE, "Received invalid message: %s", - ProtoHelpers::ToString(message).c_str()); - return false; - } - - // Check the version of the message. - const ServerHeader& message_header = message.header(); - if (message_header.protocol_version().version().major_version() != - Constants::kProtocolMajorVersion) { - statistics_->RecordError( - Statistics::ClientErrorType_PROTOCOL_VERSION_FAILURE); - TLOG(logger_, SEVERE, "Dropping message with incompatible version: %s", - ProtoHelpers::ToString(message).c_str()); - return false; - } - - // Check if it is a ConfigChangeMessage which indicates that messages should - // no longer be sent for a certain duration. Perform this check before the - // token is even checked. - if (message.has_config_change_message()) { - const ConfigChangeMessage& config_change_msg = - message.config_change_message(); - statistics_->RecordReceivedMessage( - Statistics::ReceivedMessageType_CONFIG_CHANGE); - if (config_change_msg.has_next_message_delay_ms()) { - // Validator has ensured that it is positive. - next_message_send_time_ms_ = GetCurrentTimeMs() + - config_change_msg.next_message_delay_ms(); - } - return false; // Ignore all other messages in the envelope. - } - - if (message_header.server_time_ms() > last_known_server_time_ms_) { - last_known_server_time_ms_ = message_header.server_time_ms(); - } - parsed_message->InitFrom(message); - return true; -} - -bool ProtocolHandler::CheckServerToken(const string& server_token) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - const string& client_token = listener_->GetClientToken(); - - // If we do not have a client token yet, there is nothing to compare. The - // message must have an initialize message and the upper layer will do the - // appropriate checks. Hence, we return true if client_token is empty. - if (client_token.empty()) { - // No token. Return true so that we'll attempt to deliver a token control - // message (if any) to the listener in handleIncomingMessage. - return true; - } - - if (client_token != server_token) { - // Bad token - reject whole message. However, our channel can send us - // messages intended for other clients belonging to the same user, so don't - // log too loudly. - TLOG(logger_, INFO, "Incoming message has bad token: %s, %s", - ProtoHelpers::ToString(client_token).c_str(), - ProtoHelpers::ToString(server_token).c_str()); - statistics_->RecordError(Statistics::ClientErrorType_TOKEN_MISMATCH); - return false; - } - return true; -} - -void ProtocolHandler::SendInitializeMessage( - const ApplicationClientIdP& application_client_id, - const string& nonce, - BatchingTask* batching_task, - const string& debug_string) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - if (application_client_id.client_type() != client_type_) { - // This condition is not fatal, but it probably represents a bug somewhere - // if it occurs. - TLOG(logger_, WARNING, "Client type in application id does not match " - "constructor-provided type: %s vs %s", - ProtoHelpers::ToString(application_client_id).c_str(), client_type_); - } - - // Simply store the message in pending_initialize_message_ and send it - // when the batching task runs. - InitializeMessage* message = new InitializeMessage(); - ProtoHelpers::InitInitializeMessage(application_client_id, nonce, message); - TLOG(logger_, INFO, "Batching initialize message for client: %s, %s", - debug_string.c_str(), - ProtoHelpers::ToString(*message).c_str()); - batcher_.SetInitializeMessage(message); - batching_task->EnsureScheduled(debug_string); -} - -void ProtocolHandler::SendInfoMessage( - const vector<pair<string, int> >& performance_counters, - ClientConfigP* client_config, - bool request_server_registration_summary, - BatchingTask* batching_task) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - // Simply store the message in pending_info_message_ and send it - // when the batching task runs. - InfoMessage* message = new InfoMessage(); - message->mutable_client_version()->CopyFrom(client_version_); - - // Add configuration parameters. - if (client_config != NULL) { - message->mutable_client_config()->CopyFrom(*client_config); - } - - // Add performance counters. - for (size_t i = 0; i < performance_counters.size(); ++i) { - PropertyRecord* counter = message->add_performance_counter(); - counter->set_name(performance_counters[i].first); - counter->set_value(performance_counters[i].second); - } - - // Indicate whether we want the server's registration summary sent back. - message->set_server_registration_summary_requested( - request_server_registration_summary); - - TLOG(logger_, INFO, "Batching info message for client: %s", - ProtoHelpers::ToString(*message).c_str()); - batcher_.SetInfoMessage(message); - batching_task->EnsureScheduled("Send-info"); -} - -void ProtocolHandler::SendRegistrations( - const vector<ObjectIdP>& object_ids, - RegistrationP::OpType reg_op_type, - BatchingTask* batching_task) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - for (size_t i = 0; i < object_ids.size(); ++i) { - batcher_.AddRegistration(object_ids[i], reg_op_type); - } - batching_task->EnsureScheduled("Send-registrations"); -} - -void ProtocolHandler::SendInvalidationAck(const InvalidationP& invalidation, - BatchingTask* batching_task) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - // We could do squelching - we don't since it is unlikely to be too beneficial - // here. - batcher_.AddAck(invalidation); - batching_task->EnsureScheduled("Send-ack"); -} - -void ProtocolHandler::SendRegistrationSyncSubtree( - const RegistrationSubtree& reg_subtree, - BatchingTask* batching_task) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - TLOG(logger_, INFO, "Adding subtree: %s", - ProtoHelpers::ToString(reg_subtree).c_str()); - batcher_.AddRegSubtree(reg_subtree); - batching_task->EnsureScheduled("Send-reg-sync"); -} - -void ProtocolHandler::SendMessageToServer() { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - - if (next_message_send_time_ms_ > GetCurrentTimeMs()) { - TLOG(logger_, WARNING, "In quiet period: not sending message to server: " - "%s > %s", - SimpleItoa(next_message_send_time_ms_).c_str(), - SimpleItoa(GetCurrentTimeMs()).c_str()); - return; - } - - const bool has_client_token(!listener_->GetClientToken().empty()); - ClientToServerMessage builder; - if (!batcher_.ToBuilder(&builder, has_client_token)) { - TLOG(logger_, WARNING, "Unable to build message"); - return; - } - ClientHeader* outgoing_header = builder.mutable_header(); - InitClientHeader(outgoing_header); - - // Validate the message and send it. - ++message_id_; - if (!msg_validator_->IsValid(builder)) { - TLOG(logger_, SEVERE, "Tried to send invalid message: %s", - ProtoHelpers::ToString(builder).c_str()); - statistics_->RecordError( - Statistics::ClientErrorType_OUTGOING_MESSAGE_FAILURE); - return; - } - - TLOG(logger_, FINE, "Sending message to server: %s", - ProtoHelpers::ToString(builder).c_str()); - statistics_->RecordSentMessage(Statistics::SentMessageType_TOTAL); - string serialized; - builder.SerializeToString(&serialized); - network_->SendMessage(serialized); - - // Record that the message was sent. We do this inline to match what the - // Java Ticl, which is constrained by Android requirements, does. - listener_->HandleMessageSent(); -} - -void ProtocolHandler::InitClientHeader(ClientHeader* builder) { - CHECK(internal_scheduler_->IsRunningOnThread()) << "Not on internal thread"; - ProtoHelpers::InitProtocolVersion(builder->mutable_protocol_version()); - builder->set_client_time_ms(GetCurrentTimeMs()); - builder->set_message_id(StringPrintf("%d", message_id_)); - builder->set_max_known_server_time_ms(last_known_server_time_ms_); - builder->set_client_type(client_type_); - listener_->GetRegistrationSummary(builder->mutable_registration_summary()); - const string& client_token = listener_->GetClientToken(); - if (!client_token.empty()) { - TLOG(logger_, FINE, "Sending token on client->server message: %s", - ProtoHelpers::ToString(client_token).c_str()); - builder->set_client_token(client_token); - } -} - -bool Batcher::ToBuilder(ClientToServerMessage* builder, bool has_client_token) { - // Check if an initialize message needs to be sent. - if (pending_initialize_message_.get() != NULL) { - statistics_->RecordSentMessage(Statistics::SentMessageType_INITIALIZE); - builder->mutable_initialize_message()->CopyFrom( - *pending_initialize_message_); - pending_initialize_message_.reset(); - } - - // Note: Even if an initialize message is being sent, we can send additional - // messages such as registration messages, etc to the server. But if there is - // no token and an initialize message is not being sent, we cannot send any - // other message. - - if (!has_client_token && !builder->has_initialize_message()) { - // Cannot send any message. - TLOG(logger_, WARNING, - "Cannot send message since no token and no initialize msg: %s", - ProtoHelpers::ToString(*builder).c_str()); - statistics_->RecordError(Statistics::ClientErrorType_TOKEN_MISSING_FAILURE); - return false; - } - - // Check for pending batched operations and add to message builder if needed. - - // Add reg, acks, reg subtrees - clear them after adding. - if (!pending_acked_invalidations_.empty()) { - InitAckMessage(builder->mutable_invalidation_ack_message()); - statistics_->RecordSentMessage( - Statistics::SentMessageType_INVALIDATION_ACK); - } - - // Check regs. - if (!pending_registrations_.empty()) { - InitRegistrationMessage(builder->mutable_registration_message()); - statistics_->RecordSentMessage(Statistics::SentMessageType_REGISTRATION); - } - - // Check reg substrees. - if (!pending_reg_subtrees_.empty()) { - RegistrationSyncMessage* sync_message = - builder->mutable_registration_sync_message(); - set<RegistrationSubtree, ProtoCompareLess>::const_iterator iter; - for (iter = pending_reg_subtrees_.begin(); - iter != pending_reg_subtrees_.end(); ++iter) { - sync_message->add_subtree()->CopyFrom(*iter); - } - pending_reg_subtrees_.clear(); - statistics_->RecordSentMessage( - Statistics::SentMessageType_REGISTRATION_SYNC); - } - - // Check info message. - if (pending_info_message_.get() != NULL) { - statistics_->RecordSentMessage(Statistics::SentMessageType_INFO); - builder->mutable_info_message()->CopyFrom(*pending_info_message_); - pending_info_message_.reset(); - } - return true; -} - -void Batcher::InitRegistrationMessage( - RegistrationMessage* reg_message) { - CHECK(!pending_registrations_.empty()); - - // Run through the pending_registrations map. - map<ObjectIdP, RegistrationP::OpType, ProtoCompareLess>::iterator iter; - for (iter = pending_registrations_.begin(); - iter != pending_registrations_.end(); ++iter) { - ProtoHelpers::InitRegistrationP(iter->first, iter->second, - reg_message->add_registration()); - } - pending_registrations_.clear(); -} - -void Batcher::InitAckMessage(InvalidationMessage* ack_message) { - CHECK(!pending_acked_invalidations_.empty()); - - // Run through pending_acked_invalidations_ set. - set<InvalidationP, ProtoCompareLess>::iterator iter; - for (iter = pending_acked_invalidations_.begin(); - iter != pending_acked_invalidations_.end(); iter++) { - ack_message->add_invalidation()->CopyFrom(*iter); - } - pending_acked_invalidations_.clear(); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler.h deleted file mode 100644 index c9e00c478eb7d9e4592cd2cccdf4fa4568672ba0..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler.h +++ /dev/null @@ -1,424 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// A layer for interacting with low-level protocol messages. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_PROTOCOL_HANDLER_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_PROTOCOL_HANDLER_H_ - -#include <map> -#include <set> -#include <sstream> -#include <string> -#include <utility> -#include <vector> - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/deps/scoped_ptr.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" -#include "google/cacheinvalidation/impl/invalidation-client-util.h" -#include "google/cacheinvalidation/impl/proto-helpers.h" -#include "google/cacheinvalidation/impl/recurring-task.h" -#include "google/cacheinvalidation/impl/statistics.h" -#include "google/cacheinvalidation/impl/smearer.h" -#include "google/cacheinvalidation/impl/throttle.h" -#include "google/cacheinvalidation/impl/ticl-message-validator.h" - -namespace invalidation { - -class ProtocolHandler; - -using INVALIDATION_STL_NAMESPACE::make_pair; -using INVALIDATION_STL_NAMESPACE::map; -using INVALIDATION_STL_NAMESPACE::pair; -using INVALIDATION_STL_NAMESPACE::set; -using INVALIDATION_STL_NAMESPACE::string; - -/* - * Representation of a message header for use in a server message. - */ -struct ServerMessageHeader { - public: - ServerMessageHeader() { - } - - /* Initializes an instance. Note that this call *does not* make copies of - * the pointed-to data. Instances are always allocated inside a ParsedMessage, - * and the containing ParsedMessage owns the data. - * - * Arguments: - * init_token - server-sent token. - * init_registration_summary - summary over server registration state. - * If num_registations is not set, means no registration summary was - * received from the server. - */ - void InitFrom(const string* init_token, - const RegistrationSummary* init_registration_summary) { - token_ = init_token; - registration_summary_ = init_registration_summary; - } - - const string& token() const { - return *token_; - } - - // Returns the registration summary if any. - const RegistrationSummary* registration_summary() const { - return registration_summary_; - } - - // Returns a human-readable representation of this object for debugging. - string ToString() const; - - private: - // Server-sent token. - const string* token_; - - // Summary of the client's registration state at the server. - const RegistrationSummary* registration_summary_; - - DISALLOW_COPY_AND_ASSIGN(ServerMessageHeader); -}; - -/* - * Representation of a message receiver for the server. Such a message is - * guaranteed to be valid (i.e. checked by the message validator), but - * the session token is NOT checked. - */ -struct ParsedMessage { - public: - ParsedMessage() { - } - - ServerMessageHeader header; - - /* - * Each of these fields points to a field in the base_message - * ServerToClientMessage protobuf. It is non-null iff the corresponding hasYYY - * method in the protobuf would return true. - */ - const TokenControlMessage* token_control_message; - const InvalidationMessage* invalidation_message; - const RegistrationStatusMessage* registration_status_message; - const RegistrationSyncRequestMessage* registration_sync_request_message; - const ConfigChangeMessage* config_change_message; - const InfoRequestMessage* info_request_message; - const ErrorMessage* error_message; - - /* - * Initializes an instance from a |raw_message|. This function makes a copy of - * the message internally. - */ - void InitFrom(const ServerToClientMessage& raw_message); - - private: - ServerToClientMessage base_message; - DISALLOW_COPY_AND_ASSIGN(ParsedMessage); -}; - -/* - * Class that batches messages to be sent to the data center. - */ -class Batcher { - public: - Batcher(Logger* logger, Statistics* statistics) - : logger_(logger), statistics_(statistics) {} - - /* Sets the initialize |message| to be sent to the server. */ - void SetInitializeMessage(const InitializeMessage* message) { - pending_initialize_message_.reset(message); - } - - /* Sets the info |message| to be sent to the server. */ - void SetInfoMessage(const InfoMessage* message) { - pending_info_message_.reset(message); - } - - /* Adds a registration on |object_id| to be sent to the server. */ - void AddRegistration(const ObjectIdP& object_id, - const RegistrationP::OpType& reg_op_type) { - pending_registrations_[object_id] = reg_op_type; - } - - /* Adds an acknowledgment of |invalidation| to be sent to the server. */ - void AddAck(const InvalidationP& invalidation) { - pending_acked_invalidations_.insert(invalidation); - } - - /* Adds a registration subtree |reg_subtree| to be sent to the server. */ - void AddRegSubtree(const RegistrationSubtree& reg_subtree) { - pending_reg_subtrees_.insert(reg_subtree); - } - - /* - * Builds a message from the batcher state and resets the batcher. Returns - * whether the message could be built. - * - * Note that the returned message does NOT include a header. - */ - bool ToBuilder(ClientToServerMessage* builder, - bool has_client_token); - - /* - * Initializes a registration message based on registrations from - * |pending_registrations|. - * - * REQUIRES: pending_registrations.size() > 0 - */ - void InitRegistrationMessage(RegistrationMessage* reg_message); - - /* Initializes an invalidation ack message based on acks from - * |pending_acked_invalidations|. - * <p> - * REQUIRES: pending_acked_invalidations.size() > 0 - */ - void InitAckMessage(InvalidationMessage* ack_message); - - private: - Logger* const logger_; - - Statistics* const statistics_; - - /* Set of pending registrations stored as a map for overriding later - * operations. - */ - map<ObjectIdP, RegistrationP::OpType, ProtoCompareLess> - pending_registrations_; - - /* Set of pending invalidation acks. */ - set<InvalidationP, ProtoCompareLess> pending_acked_invalidations_; - - /* Set of pending registration sub trees for registration sync. */ - set<RegistrationSubtree, ProtoCompareLess> pending_reg_subtrees_; - - /* Pending initialization message to send to the server, if any. */ - scoped_ptr<const InitializeMessage> pending_initialize_message_; - - /* Pending info message to send to the server, if any. */ - scoped_ptr<const InfoMessage> pending_info_message_; - - DISALLOW_COPY_AND_ASSIGN(Batcher); -}; - -/* Listener for protocol events. The protocol client calls these methods when - * a message is received from the server. It guarantees that the call will be - * made on the internal thread that the SystemResources provides. When the - * protocol listener is called, the token has been checked and message - * validation has been completed (using the {@link TiclMessageValidator2}). - * That is, all of the methods below can assume that the nonce is null and the - * server token is valid. - */ -class ProtocolListener { - public: - ProtocolListener() {} - virtual ~ProtocolListener() {} - - /* Records that a message was sent to the server at the current time. */ - virtual void HandleMessageSent() = 0; - - /* Handles a change in network connectivity. */ - virtual void HandleNetworkStatusChange(bool is_online) = 0; - - /* Stores a summary of the current desired registrations. */ - virtual void GetRegistrationSummary(RegistrationSummary* summary) = 0; - - /* Returns the current server-assigned client token, if any. */ - virtual string GetClientToken() = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(ProtocolListener); -}; - -// Forward-declare the BatchingTask so that send* methods can take it. -class BatchingTask; - -/* Parses messages from the server and calls appropriate functions on the - * ProtocolListener to handle various types of message content. Also buffers - * message data from the client and constructs and sends messages to the server. - */ -class ProtocolHandler { - public: - /* Creates an instance. - * - * config - configuration for the client - * resources - resources to use - * smearer - a smearer to randomize delays - * statistics - track information about messages sent/received, etc - * client_type - client typecode - * application_name - name of the application using the library (for - * debugging/monitoring) - * listener - callback for protocol events - * msg_validator - validator for protocol messages - * Caller continues to own space for smearer. - */ - ProtocolHandler(const ProtocolHandlerConfigP& config, - SystemResources* resources, - Smearer* smearer, Statistics* statistics, - int client_type, const string& application_name, - ProtocolListener* listener, - TiclMessageValidator* msg_validator); - - /* Initializes |config| with default protocol handler config parameters. */ - static void InitConfig(ProtocolHandlerConfigP* config); - - /* Initializes |config| with protocol handler config parameters for unit - * tests. - */ - static void InitConfigForTest(ProtocolHandlerConfigP* config); - - /* Returns the next time a message is allowed to be sent to the server. - * Typically, this will be in the past, meaning that the client is free to - * send a message at any time. - */ - int64 GetNextMessageSendTimeMsForTest() { - return next_message_send_time_ms_; - } - - /* Sends a message to the server to request a client token. - * - * Arguments: - * client_type - client type code as assigned by the notification system's - * backend - * application_client_id - application-specific client id - * nonce - nonce for the request - * batching_task - recurring task to trigger batching. No ownership taken. - * debug_string - information to identify the caller - */ - void SendInitializeMessage( - const ApplicationClientIdP& application_client_id, - const string& nonce, - BatchingTask* batching_task, - const string& debug_string); - - /* Sends an info message to the server with the performance counters supplied - * in performance_counters and the config supplies in client_config (which - * could be null). - */ - void SendInfoMessage(const vector<pair<string, int> >& performance_counters, - ClientConfigP* client_config, - bool request_server_registration_summary, - BatchingTask* batching_task); - - /* Sends a registration request to the server. - * - * Arguments: - * object_ids - object ids on which to (un)register - * reg_op_type - whether to register or unregister - * batching_task - recurring task to trigger batching. No ownership taken. - */ - void SendRegistrations(const vector<ObjectIdP>& object_ids, - RegistrationP::OpType reg_op_type, - BatchingTask* batching_task); - - /* Sends an acknowledgement for invalidation to the server. */ - void SendInvalidationAck(const InvalidationP& invalidation, - BatchingTask* batching_task); - - /* Sends a single registration subtree to the server. - * - * Arguments: - * reg_subtree - subtree to send - * batching_task - recurring task to trigger batching. No ownership taken. - */ - void SendRegistrationSyncSubtree(const RegistrationSubtree& reg_subtree, - BatchingTask* batching_task); - - /* Sends pending data to the server (e.g., registrations, acks, registration - * sync messages). - * - * REQUIRES: caller do no further work after the method returns. - */ - void SendMessageToServer(); - - /* - * Handles a message from the server. If the message can be processed (i.e., - * is valid, is of the right version, and is not a silence message), returns - * a ParsedMessage representing it. Otherwise, returns NULL. - * - * This class intercepts and processes silence messages. In this case, it will - * discard any other data in the message. - * - * Note that this method does not check the session token of any message. - */ - bool HandleIncomingMessage(const string& incoming_message, - ParsedMessage* parsed_message); - - private: - /* Verifies that server_token matches the token currently held by the client. - */ - bool CheckServerToken(const string& server_token); - - /* Stores the header to include on a message to the server. */ - void InitClientHeader(ClientHeader* header); - - // Returns the current time in milliseconds. - int64 GetCurrentTimeMs() { - return InvalidationClientUtil::GetCurrentTimeMs(internal_scheduler_); - } - - friend class BatchingTask; - - // Information about the client, e.g., application name, OS, etc. - - ClientVersion client_version_; - - // A logger. - Logger* logger_; - - // Scheduler for the client's internal processing. - Scheduler* internal_scheduler_; - - // Network channel for sending and receiving messages to and from the server. - NetworkChannel* network_; - - // A throttler to prevent the client from sending too many messages in a given - // interval. - Throttle throttle_; - - // The protocol listener. - ProtocolListener* listener_; - - // Checks that messages (inbound and outbound) conform to basic validity - // constraints. - TiclMessageValidator* msg_validator_; - - /* A debug message id that is added to every message to the server. */ - int message_id_; - - // State specific to a client. If we want to support multiple clients, this - // could be in a map or could be eliminated (e.g., no batching). - - /* The last known time from the server. */ - int64 last_known_server_time_ms_; - - /* The next time before which a message cannot be sent to the server. If - * this is less than current time, a message can be sent at any time. - */ - int64 next_message_send_time_ms_; - - /* Statistics objects to track number of sent messages, etc. */ - Statistics* statistics_; - - // Batches messages to be sent to the server. - Batcher batcher_; - - // Type code for the client. - int client_type_; - - DISALLOW_COPY_AND_ASSIGN(ProtocolHandler); -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_PROTOCOL_HANDLER_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler_test.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler_test.cc deleted file mode 100644 index 1ca15685f416729ac325c1850352f41f7ff794d3..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/protocol-handler_test.cc +++ /dev/null @@ -1,674 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Unit tests for the ProtocolHandler class. - -#include "google/cacheinvalidation/types.pb.h" -#include "google/cacheinvalidation/include/types.h" -#include "google/cacheinvalidation/deps/gmock.h" -#include "google/cacheinvalidation/deps/googletest.h" -#include "google/cacheinvalidation/deps/string_util.h" -#include "google/cacheinvalidation/impl/basic-system-resources.h" -#include "google/cacheinvalidation/impl/constants.h" -#include "google/cacheinvalidation/impl/invalidation-client-impl.h" -#include "google/cacheinvalidation/impl/protocol-handler.h" -#include "google/cacheinvalidation/impl/statistics.h" -#include "google/cacheinvalidation/impl/throttle.h" -#include "google/cacheinvalidation/impl/ticl-message-validator.h" -#include "google/cacheinvalidation/test/deterministic-scheduler.h" -#include "google/cacheinvalidation/test/test-logger.h" -#include "google/cacheinvalidation/test/test-utils.h" - -namespace invalidation { - -using ::ipc::invalidation::ClientType_Type_TEST; -using ::ipc::invalidation::ObjectSource_Type_TEST; -using ::testing::_; -using ::testing::AllOf; -using ::testing::ByRef; -using ::testing::DoAll; -using ::testing::ElementsAre; -using ::testing::EqualsProto; -using ::testing::Eq; -using ::testing::Matcher; -using ::testing::Property; -using ::testing::Return; -using ::testing::ReturnPointee; -using ::testing::SaveArg; -using ::testing::SetArgPointee; -using ::testing::StrictMock; -using ::testing::proto::WhenDeserializedAs; - -/* Returns whether two headers are equal. */ -bool HeaderEqual(const ServerMessageHeader& expected, - const ServerMessageHeader& actual) { - // If the token is different or if one of the registration summaries is NULL - // and the other is non-NULL, return false. - if (((expected.registration_summary() != NULL) != - (actual.registration_summary() != NULL)) || - (expected.token() != actual.token())) { - return false; - } - - // The tokens are the same and registration summaries are either both - // null or non-null. - return (expected.registration_summary() == NULL) || - ((expected.registration_summary()->num_registrations() == - actual.registration_summary()->num_registrations()) && - (expected.registration_summary()->registration_digest() == - actual.registration_summary()->registration_digest())); -} - -// A mock of the ProtocolListener interface. -class MockProtocolListener : public ProtocolListener { - public: - MOCK_METHOD0(HandleMessageSent, void()); - - MOCK_METHOD1(HandleNetworkStatusChange, void(bool)); // NOLINT - - MOCK_METHOD1(GetRegistrationSummary, void(RegistrationSummary*)); // NOLINT - - MOCK_METHOD0(GetClientToken, string()); -}; - -// Tests the basic functionality of the protocol handler. -class ProtocolHandlerTest : public UnitTestBase { - public: - virtual ~ProtocolHandlerTest() {} - - // Performs setup for protocol handler unit tests, e.g. creating resource - // components and setting up common expectations for certain mock objects. - virtual void SetUp() { - // Use a strict mock scheduler for the listener, since it shouldn't be used - // at all by the protocol handler. - UnitTestBase::SetUp(); - InitListenerExpectations(); - validator.reset(new TiclMessageValidator(logger)); // Create msg validator - - // Create the protocol handler object. - random.reset(new Random(InvalidationClientUtil::GetCurrentTimeMs( - resources.get()->internal_scheduler()))); - smearer.reset(new Smearer(random.get(), kDefaultSmearPercent)); - protocol_handler.reset( - new ProtocolHandler( - config, resources.get(), smearer.get(), statistics.get(), - ClientType_Type_TEST, "unit-test", &listener, validator.get())); - batching_task.reset( - new BatchingTask(protocol_handler.get(), smearer.get(), - TimeDelta::FromMilliseconds(config.batching_delay_ms()))); - } - - // Configuration for the protocol handler (uses defaults). - ProtocolHandlerConfigP config; - - // The protocol handler being tested. Created fresh for each test function. - scoped_ptr<ProtocolHandler> protocol_handler; - - // A mock protocol listener. We make this strict in order to have tight - // control over the interactions between this and the protocol handler. - // SetUp() installs expectations to allow GetClientToken() and - // GetRegistrationSummary() to be called any time and to give them - // reasonable behavior. - StrictMock<MockProtocolListener> listener; - - // Ticl message validator. We do not mock this, since the correctness of the - // protocol handler depends on it. - scoped_ptr<TiclMessageValidator> validator; - - // Token and registration summary for the mock listener to return when - // the protocol handler requests them. - string token; - RegistrationSummary summary; - - // A smearer to randomize delays. - scoped_ptr<Smearer> smearer; - - // A random number generator. - scoped_ptr<Random> random; - - // Batching task for the protocol handler. - scoped_ptr<BatchingTask> batching_task; - - void AddExpectationForHandleMessageSent() { - EXPECT_CALL(listener, HandleMessageSent()); - } - - /* - * Processes a |message| using the protocol handler, initializing - * |parsed_message| with the result. - * - * Returns whether the message could be parsed. - */ - bool ProcessMessage(ServerToClientMessage message, - ParsedMessage* parsed_message) { - string serialized; - message.SerializeToString(&serialized); - bool accepted = protocol_handler->HandleIncomingMessage( - serialized, parsed_message); - return accepted; - } - - private: - void InitListenerExpectations() { - // When the handler asks the listener for the client token, return whatever - // |token| currently is. - EXPECT_CALL(listener, GetClientToken()) - .WillRepeatedly(ReturnPointee(&token)); - - // If the handler asks the listener for a registration summary, respond by - // supplying a fake summary. - InitZeroRegistrationSummary(&summary); - EXPECT_CALL(listener, GetRegistrationSummary(_)) - .WillRepeatedly(SetArgPointee<0>(summary)); - } -}; - -// Asks the protocol handler to send an initialize message. Waits for the -// batching delay to pass. Checks that appropriate calls are made on the -// listener and that a proper message is sent on the network. -TEST_F(ProtocolHandlerTest, SendInitializeOnly) { - ApplicationClientIdP app_client_id; - app_client_id.set_client_name("unit-test-client-id"); - app_client_id.set_client_type(ClientType_Type_TEST); - - // Client's token is initially empty. Give it an arbitrary nonce. - token = ""; - string nonce = "unit-test-nonce"; - - // SendInitializeMessage checks that it's running on the work queue thread, so - // we need to schedule the call. - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), &ProtocolHandler::SendInitializeMessage, - app_client_id, nonce, batching_task.get(), "Startup")); - - AddExpectationForHandleMessageSent(); - ClientToServerMessage expected_message; - - // Build the header. - ClientHeader* header = expected_message.mutable_header(); - ProtoHelpers::InitProtocolVersion(header->mutable_protocol_version()); - header->mutable_registration_summary()->CopyFrom(summary); - header->set_max_known_server_time_ms(0); - header->set_message_id("1"); - - // Note: because the batching task is smeared, we don't know what the client's - // timestamp will be. We omit it from this proto and do a partial match in - // the EXPECT_CALL but also save the proto and check later that it doesn't - // contain anything we don't expect. - - // Create the expected initialize message. - InitializeMessage* initialize_message = - expected_message.mutable_initialize_message(); - initialize_message->set_client_type(ClientType_Type_TEST); - initialize_message->set_nonce(nonce); - initialize_message->mutable_application_client_id()->CopyFrom(app_client_id); - initialize_message->set_digest_serialization_type( - InitializeMessage_DigestSerializationType_BYTE_BASED); - - string actual_serialized; - EXPECT_CALL( - *network, - SendMessage(WhenDeserializedAs<ClientToServerMessage>( - // Check that the deserialized message has the initialize message and - // header fields we expect. - AllOf(Property(&ClientToServerMessage::initialize_message, - EqualsProto(*initialize_message)), - Property(&ClientToServerMessage::header, - ClientHeaderMatches(header)))))) - .WillOnce(SaveArg<0>(&actual_serialized)); - - // The actual message won't be sent until after the batching delay, which is - // smeared, so double it to be sure enough time will have passed. - TimeDelta wait_time = GetMaxBatchingDelay(config); - internal_scheduler->PassTime(wait_time); - - // By now we expect the message to have been sent, so we'll deserialize it - // and check that it doesn't have anything we don't expect. - ClientToServerMessage actual_message; - actual_message.ParseFromString(actual_serialized); - ASSERT_FALSE(actual_message.has_info_message()); - ASSERT_FALSE(actual_message.has_invalidation_ack_message()); - ASSERT_FALSE(actual_message.has_registration_message()); - ASSERT_FALSE(actual_message.has_registration_sync_message()); - ASSERT_GE(actual_message.header().client_time_ms(), - InvalidationClientUtil::GetTimeInMillis(start_time)); - ASSERT_LE(actual_message.header().client_time_ms(), - InvalidationClientUtil::GetTimeInMillis(start_time + wait_time)); -} - -// Tests the receipt of a token control message like what we'd expect in -// response to an initialize message. Check that appropriate calls are made on -// the protocol listener. -TEST_F(ProtocolHandlerTest, ReceiveTokenControlOnly) { - ServerToClientMessage message; - ServerHeader* header = message.mutable_header(); - string nonce = "fake nonce"; - InitServerHeader(nonce, header); - - string new_token = "new token"; - message.mutable_token_control_message()->set_new_token(new_token); - - ServerMessageHeader expected_header; - expected_header.InitFrom(&nonce, &header->registration_summary()); - ParsedMessage parsed_message; - ProcessMessage(message, &parsed_message); - ASSERT_TRUE(HeaderEqual(expected_header, parsed_message.header)); - ASSERT_TRUE(parsed_message.token_control_message != NULL); -} - -// Test that the protocol handler correctly buffers multiple message types. -// Tell it to send registrations, then unregistrations (with some overlap in the -// sets of objects). Then send some invalidation acks and finally a -// registration subtree. Wait for the batching interval to pass, and then check -// that the message sent out contains everything we expect. -TEST_F(ProtocolHandlerTest, SendMultipleMessageTypes) { - // Concoct some performance counters and config parameters, and ask to send - // an info message with them. - vector<pair<string, int> > perf_counters; - perf_counters.push_back(make_pair("x", 3)); - perf_counters.push_back(make_pair("y", 81)); - ClientConfigP client_config; - InvalidationClientImpl::InitConfig(&client_config); - - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), &ProtocolHandler::SendInfoMessage, - perf_counters, &client_config, true, batching_task.get())); - - // Synthesize a few test object ids. - vector<ObjectIdP> oids; - InitTestObjectIds(3, &oids); - - // Register for the first two. - vector<ObjectIdP> oid_vec; - oid_vec.push_back(oids[0]); - oid_vec.push_back(oids[1]); - - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), &ProtocolHandler::SendRegistrations, - oid_vec, RegistrationP_OpType_REGISTER, batching_task.get())); - - // Then unregister for the second and third. This overrides the registration - // on oids[1]. - oid_vec.clear(); - oid_vec.push_back(oids[1]); - oid_vec.push_back(oids[2]); - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), &ProtocolHandler::SendRegistrations, - oid_vec, RegistrationP_OpType_UNREGISTER, batching_task.get())); - - // Send a couple of invalidations. - vector<InvalidationP> invalidations; - MakeInvalidationsFromObjectIds(oids, &invalidations); - invalidations.pop_back(); - for (size_t i = 0; i < invalidations.size(); ++i) { - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), &ProtocolHandler::SendInvalidationAck, - invalidations[i], batching_task.get())); - } - - // Send a simple registration subtree. - RegistrationSubtree subtree; - subtree.add_registered_object()->CopyFrom(oids[0]); - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), &ProtocolHandler::SendRegistrationSyncSubtree, - subtree, batching_task.get())); - - AddExpectationForHandleMessageSent(); - - token = "test token"; - - // The message it sends should contain all of the expected information: - ClientToServerMessage expected_message; - - // Header. - ClientHeader* header = expected_message.mutable_header(); - ProtoHelpers::InitProtocolVersion(header->mutable_protocol_version()); - header->mutable_registration_summary()->CopyFrom(summary); - header->set_client_token(token); - header->set_max_known_server_time_ms(0); - header->set_message_id("1"); - - // Note: because the batching task is smeared, we don't know what the client's - // timestamp will be. We omit it from this proto and do a partial match in - // the EXPECT_CALL but also save the proto and check later that it doesn't - // contain anything we don't expect. - - // Registrations. - RegistrationMessage* reg_message = - expected_message.mutable_registration_message(); - RegistrationP* registration; - registration = reg_message->add_registration(); - registration->mutable_object_id()->CopyFrom(oids[0]); - registration->set_op_type(RegistrationP_OpType_REGISTER); - - registration = reg_message->add_registration(); - registration->mutable_object_id()->CopyFrom(oids[1]); - registration->set_op_type(RegistrationP_OpType_UNREGISTER); - - registration = reg_message->add_registration(); - registration->mutable_object_id()->CopyFrom(oids[2]); - registration->set_op_type(RegistrationP_OpType_UNREGISTER); - - // Registration sync message. - expected_message.mutable_registration_sync_message()->add_subtree() - ->CopyFrom(subtree); - - // Invalidation acks. - InvalidationMessage* invalidation_message = - expected_message.mutable_invalidation_ack_message(); - InitInvalidationMessage(invalidations, invalidation_message); - - // Info message. - InfoMessage* info_message = expected_message.mutable_info_message(); - ProtoHelpers::InitClientVersion("unit-test", "unit-test", - info_message->mutable_client_version()); - info_message->set_server_registration_summary_requested(true); - info_message->mutable_client_config()->CopyFrom(client_config); - PropertyRecord* prop_rec; - for (uint32 i = 0; i < perf_counters.size(); ++i) { - prop_rec = info_message->add_performance_counter(); - prop_rec->set_name(perf_counters[i].first); - prop_rec->set_value(perf_counters[i].second); - } - - string actual_serialized; - EXPECT_CALL( - *network, - SendMessage( - WhenDeserializedAs<ClientToServerMessage>( - // Check that the deserialized message has the invalidation acks, - // registrations, info message, and header fields we expect. - AllOf(Property(&ClientToServerMessage::invalidation_ack_message, - EqualsProto(*invalidation_message)), - Property(&ClientToServerMessage::registration_message, - EqualsProto(*reg_message)), - Property(&ClientToServerMessage::info_message, - EqualsProto(*info_message)), - Property(&ClientToServerMessage::header, - ClientHeaderMatches(header)))))) - .WillOnce(SaveArg<0>(&actual_serialized)); - - TimeDelta wait_time = GetMaxBatchingDelay(config); - internal_scheduler->PassTime(wait_time); - - ClientToServerMessage actual_message; - actual_message.ParseFromString(actual_serialized); - - ASSERT_FALSE(actual_message.has_initialize_message()); - ASSERT_GE(actual_message.header().client_time_ms(), - InvalidationClientUtil::GetTimeInMillis(start_time)); - ASSERT_LE(actual_message.header().client_time_ms(), - InvalidationClientUtil::GetTimeInMillis(start_time + wait_time)); -} - -// Check that if the protocol handler receives a message with several sub- -// messages set, it makes all the appropriate calls on the listener. -TEST_F(ProtocolHandlerTest, IncomingCompositeMessage) { - // Build up a message with a number of sub-messages in it: - ServerToClientMessage message; - - // First the header. - token = "test token"; - InitServerHeader(token, message.mutable_header()); - - // Fabricate a few object ids for use in invalidations and registration - // statuses. - vector<ObjectIdP> object_ids; - InitTestObjectIds(3, &object_ids); - - // Add invalidations. - vector<InvalidationP> invalidations; - MakeInvalidationsFromObjectIds(object_ids, &invalidations); - for (int i = 0; i < 3; ++i) { - message.mutable_invalidation_message()->add_invalidation()->CopyFrom( - invalidations[i]); - } - - // Add registration statuses. - vector<RegistrationStatus> registration_statuses; - MakeRegistrationStatusesFromObjectIds(object_ids, true, true, - ®istration_statuses); - for (int i = 0; i < 3; ++i) { - message.mutable_registration_status_message() - ->add_registration_status()->CopyFrom(registration_statuses[i]); - } - - // Add a registration sync request message. - message.mutable_registration_sync_request_message(); - - // Add an info request message. - message.mutable_info_request_message()->add_info_type( - InfoRequestMessage_InfoType_GET_PERFORMANCE_COUNTERS); - - // The header we expect the listener to be called with. - ServerMessageHeader expected_header; - expected_header.InitFrom(&token, &summary); - - ParsedMessage parsed_message; - ProcessMessage(message, &parsed_message); - ASSERT_TRUE(HeaderEqual(expected_header, parsed_message.header)); - ASSERT_TRUE(parsed_message.invalidation_message != NULL); - ASSERT_TRUE(parsed_message.registration_status_message != NULL); - ASSERT_TRUE(parsed_message.registration_sync_request_message != NULL); - ASSERT_TRUE(parsed_message.info_request_message != NULL); -} - -// Test that the protocol handler drops an invalid message. -TEST_F(ProtocolHandlerTest, InvalidInboundMessage) { - // Make an invalid message (omit protocol version from header). - ServerToClientMessage message; - string token = "test token"; - ServerHeader* header = message.mutable_header(); - InitServerHeader(token, header); - header->clear_protocol_version(); - - // Add an info request message to check that it doesn't get processed. - message.mutable_info_request_message()->add_info_type( - InfoRequestMessage_InfoType_GET_PERFORMANCE_COUNTERS); - ParsedMessage parsed_message; - ProcessMessage(message, &parsed_message); - ASSERT_EQ(1, statistics->GetClientErrorCounterForTest( - Statistics::ClientErrorType_INCOMING_MESSAGE_FAILURE)); -} - -// Test that the protocol handler drops a message whose major version doesn't -// match what it understands. -TEST_F(ProtocolHandlerTest, MajorVersionMismatch) { - // Make a message with a different protocol major version. - ServerToClientMessage message; - token = "test token"; - ServerHeader* header = message.mutable_header(); - InitServerHeader(token, header); - header->mutable_protocol_version()->mutable_version()->set_major_version(1); - - // Add an info request message to check that it doesn't get processed. - message.mutable_info_request_message()->add_info_type( - InfoRequestMessage_InfoType_GET_PERFORMANCE_COUNTERS); - - ParsedMessage parsed_message; - ProcessMessage(message, &parsed_message); - ASSERT_EQ(1, statistics->GetClientErrorCounterForTest( - Statistics::ClientErrorType_PROTOCOL_VERSION_FAILURE)); -} - -// Test that the protocol handler doesn't drop a message whose minor version -// doesn't match what it understands. -TEST_F(ProtocolHandlerTest, MinorVersionMismatch) { - // Make a message with a different protocol minor version. - ServerToClientMessage message; - token = "test token"; - ServerHeader* header = message.mutable_header(); - InitServerHeader(token, header); - header->mutable_protocol_version()->mutable_version()->set_minor_version(4); - - ServerMessageHeader expected_header; - expected_header.InitFrom(&token, &summary); - - ParsedMessage parsed_message; - ProcessMessage(message, &parsed_message); - ASSERT_TRUE(HeaderEqual(expected_header, parsed_message.header)); - ASSERT_EQ(0, statistics->GetClientErrorCounterForTest( - Statistics::ClientErrorType_PROTOCOL_VERSION_FAILURE)); -} - -// Test that the protocol handler honors a config message (even if the server -// token doesn't match) and does not call any listener methods. -TEST_F(ProtocolHandlerTest, ConfigMessage) { - // Fabricate a config message. - ServerToClientMessage message; - token = "test token"; - InitServerHeader(token, message.mutable_header()); - token = "token-that-should-mismatch"; - - int next_message_delay_ms = 2000 * 1000; - message.mutable_config_change_message()->set_next_message_delay_ms( - next_message_delay_ms); - - ParsedMessage parsed_message; - ProcessMessage(message, &parsed_message); - - // Check that the protocol handler recorded receiving the config change - // message, and that it has updated the next time it will send a message. - ASSERT_EQ(1, statistics->GetReceivedMessageCounterForTest( - Statistics::ReceivedMessageType_CONFIG_CHANGE)); - ASSERT_EQ( - InvalidationClientUtil::GetTimeInMillis( - start_time + TimeDelta::FromMilliseconds(next_message_delay_ms)), - protocol_handler->GetNextMessageSendTimeMsForTest()); - - // Request to send an info message, and check that it doesn't get sent. - vector<pair<string, int> > empty_vector; - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), &ProtocolHandler::SendInfoMessage, - empty_vector, NULL, false, batching_task.get())); - - // Keep simulating passage of time until just before the quiet period ends. - // Nothing should be sent. (The mock network will catch any attempts to send - // and fail the test.) - internal_scheduler->PassTime( - TimeDelta::FromMilliseconds(next_message_delay_ms - 1)); -} - -// Test that the protocol handler properly delivers an error message to the -// listener. -TEST_F(ProtocolHandlerTest, ErrorMessage) { - // Fabricate an error message. - ServerToClientMessage message; - token = "test token"; - InitServerHeader(token, message.mutable_header()); - - // Add an error message. - ErrorMessage::Code error_code = ErrorMessage_Code_AUTH_FAILURE; - string description = "invalid auth token"; - InitErrorMessage(error_code, description, message.mutable_error_message()); - ServerMessageHeader expected_header; - expected_header.InitFrom(&token, &summary); - - // Deliver the message. - ParsedMessage parsed_message; - ProcessMessage(message, &parsed_message); - ASSERT_TRUE(HeaderEqual(expected_header, parsed_message.header)); - ASSERT_TRUE(parsed_message.error_message != NULL); -} - -// Tests that the protocol handler accepts a message from the server if the -// token doesn't match the client's (the caller is responsible for checking -// the token). -TEST_F(ProtocolHandlerTest, TokenMismatch) { - // Create the server message with one token. - token = "test token"; - ServerToClientMessage message; - InitServerHeader(token, message.mutable_header()); - - // Give the client a different token. - token = "token-that-should-mismatch"; - - // Deliver the message. - ParsedMessage parsed_message; - bool accepted = ProcessMessage(message, &parsed_message); - ASSERT_TRUE(accepted); - - ASSERT_EQ(0, statistics->GetClientErrorCounterForTest( - Statistics::ClientErrorType_TOKEN_MISMATCH)); -} - -// Tests that the protocol handler won't send out a non-initialize message if -// the client has no token. -TEST_F(ProtocolHandlerTest, TokenMissing) { - token = ""; - vector<pair<string, int> > empty_vector; - - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), - &ProtocolHandler::SendInfoMessage, empty_vector, NULL, true, - batching_task.get())); - - internal_scheduler->PassTime(GetMaxBatchingDelay(config)); - - ASSERT_EQ(1, statistics->GetClientErrorCounterForTest( - Statistics::ClientErrorType_TOKEN_MISSING_FAILURE)); -} - -// Tests that the protocol handler won't send out a message that fails -// validation (in this case, an invalidation ack with a missing version). -TEST_F(ProtocolHandlerTest, InvalidOutboundMessage) { - token = "test token"; - - vector<ObjectIdP> object_ids; - InitTestObjectIds(1, &object_ids); - vector<InvalidationP> invalidations; - MakeInvalidationsFromObjectIds(object_ids, &invalidations); - invalidations[0].clear_version(); - - internal_scheduler->Schedule( - Scheduler::NoDelay(), - NewPermanentCallback( - protocol_handler.get(), - &ProtocolHandler::SendInvalidationAck, - invalidations[0], - batching_task.get())); - - internal_scheduler->PassTime(GetMaxBatchingDelay(config)); - - ASSERT_EQ(1, statistics->GetClientErrorCounterForTest( - Statistics::ClientErrorType_OUTGOING_MESSAGE_FAILURE)); -} - -// Tests that the protocol handler drops an unparseable message. -TEST_F(ProtocolHandlerTest, UnparseableInboundMessage) { - // Make an unparseable message. - string serialized = "this can't be a valid protocol buffer!"; - ParsedMessage parsed_message; - bool accepted = protocol_handler->HandleIncomingMessage(serialized, - &parsed_message); - ASSERT_FALSE(accepted); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task.cc deleted file mode 100644 index 3196c8fa9dbd5b15c3e9a38b190ec6f9c714784c..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task.cc +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An abstraction for scheduling recurring tasks. -// - -#include "google/cacheinvalidation/impl/recurring-task.h" -#include "google/cacheinvalidation/impl/log-macro.h" - -namespace invalidation { - -RecurringTask::RecurringTask(string name, Scheduler* scheduler, Logger* logger, - Smearer* smearer, ExponentialBackoffDelayGenerator* delay_generator, - TimeDelta initial_delay, TimeDelta timeout_delay) : name_(name), - scheduler_(scheduler), logger_(logger), smearer_(smearer), - delay_generator_(delay_generator), initial_delay_(initial_delay), - timeout_delay_(timeout_delay), is_scheduled_(false) { -} - -void RecurringTask::EnsureScheduled(string debug_reason) { - RecurringTask::EnsureScheduled(false, debug_reason); -} - -void RecurringTask::EnsureScheduled(bool is_retry, string debug_reason) { - CHECK(scheduler_->IsRunningOnThread()); - if (is_scheduled_) { - return; - } - TimeDelta delay; - if (is_retry) { - // For a retried task, determine the delay to be timeout + extra delay - // (depending on whether a delay generator was provided or not). - if (delay_generator_.get() != NULL) { - delay = timeout_delay_ + delay_generator_->GetNextDelay(); - } else { - delay = timeout_delay_ + smearer_->GetSmearedDelay(initial_delay_); - } - } else { - delay = smearer_->GetSmearedDelay(initial_delay_); - } - - TLOG(logger_, FINE, "[%s] Scheduling %d with a delay %d, Now = %d", - debug_reason.c_str(), name_.c_str(), delay.ToInternalValue(), - scheduler_->GetCurrentTime().ToInternalValue()); - scheduler_->Schedule(delay, NewPermanentCallback(this, - &RecurringTask::RunTaskAndRescheduleIfNeeded)); - is_scheduled_ = true; -} - -void RecurringTask::RunTaskAndRescheduleIfNeeded() { - CHECK(scheduler_->IsRunningOnThread()) << "Not on scheduler thread"; - is_scheduled_ = false; - - // Run the task. If the task asks for a retry, reschedule it after at a - // timeout delay. Otherwise, resets the delay_generator. - if (RunTask()) { - // The task asked to be rescheduled, so reschedule it after a timeout has - // occurred. - CHECK((delay_generator_ != NULL) || - (initial_delay_ > Scheduler::NoDelay())) - << "Spinning: No exp back off and initial delay is zero"; - EnsureScheduled(true, "Retry"); - } else if (delay_generator_ != NULL) { - // The task asked not to be rescheduled. Treat it as having "succeeded" - // and reset the delay generator. - delay_generator_->Reset(); - } -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task.h deleted file mode 100644 index 492a0f0af0f826d0c18b1747b1bdaecd3f0bab04..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task.h +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// -// An abstraction for scheduling recurring tasks. Combines idempotent scheduling -// and smearing with conditional retries and exponential backoff. Does not -// implement throttling. Designed to support a variety of use cases, including -// the following capabilities. -// -// * Idempotent scheduling, e.g., ensuring that a batching task is scheduled -// exactly once. -// * Recurring tasks, e.g., periodic heartbeats. -// * Retriable actions aimed at state change, e.g., sending initialization -// messages. -// -// Each instance of this class manages the state for a single task. See the -// invalidation-client-impl.cc for examples. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_RECURRING_TASK_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_RECURRING_TASK_H_ - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/impl/exponential-backoff-delay-generator.h" -#include "google/cacheinvalidation/impl/smearer.h" - -namespace invalidation { - -class RecurringTask { - public: - /* Creates a recurring task with the given parameters. The specs of the - * parameters are given in the instance variables. - * - * The created task is first scheduled with a smeared delay of - * |initial_delay|. If the |this->run()| returns true on its execution, the - * task is rescheduled after a |timeout_delay| + smeared delay of - * |initial_delay| or |timeout_delay| + |delay_generator->GetNextDelay()| - * depending on whether the |delay_generator| is null or not. - * - * Space for |scheduler|, |logger|, |smearer| is owned by the caller. - * Space for |delay_generator| is owned by the callee. - */ - RecurringTask(string name, Scheduler* scheduler, Logger* logger, - Smearer* smearer, ExponentialBackoffDelayGenerator* delay_generator, - TimeDelta initial_delay, TimeDelta timeout_delay); - - virtual ~RecurringTask() {} - - /* Run the task and return true if the task should be rescheduled after a - * timeout. If false is returned, the task is not scheduled again until - * |ensure_scheduled| is called again. - */ - virtual bool RunTask() = 0; - - /* Ensures that the task is scheduled (with |debug_reason| as the reason to be - * printed for debugging purposes). If the task has been scheduled, it is - * not scheduled again. - * - * REQUIRES: Must be called from the scheduler thread. - */ - void EnsureScheduled(string debug_reason); - - /* Space for the returned Smearer is still owned by this class. */ - Smearer* smearer() { - return smearer_; - } - - private: - /* Run the task and check if it needs to be rescheduled. If so, reschedule it - * after the appropriate delay. - */ - void RunTaskAndRescheduleIfNeeded(); - - /* Ensures that the task is scheduled if it is already not scheduled. If - * already scheduled, this method is a no-op. If |is_retry| is |false|, smears - * the |initial_delay_| and uses that delay for scheduling. If |is_retry| is - * true, it determines the new delay to be - * |timeout_delay_ + delay_generator.GetNextDelay()| if |delay_generator| is - * non-null. If |delay_generator| is null, schedules the task after a delay of - * |timeout_delay_| + smeared value of |initial_delay_|. - * - * REQUIRES: Must be called from the scheduler thread. - */ - void EnsureScheduled(bool is_retry, string debug_reason); - - /* Name of the task (for debugging purposes mostly). */ - string name_; - - /* Scheduler for the scheduling the task as needed. */ - Scheduler* scheduler_; - - /* A logger. */ - Logger* logger_; - - /* A smearer for spreading the delays. */ - Smearer* smearer_; - - /* A delay generator for exponential backoff. */ - scoped_ptr<ExponentialBackoffDelayGenerator> delay_generator_; - - /* - * The time after which the task is scheduled first. If no delayGenerator is - * specified, this is also the delay used for retries. - */ - TimeDelta initial_delay_; - - /* For a task that is retried, add this time to the delay. */ - TimeDelta timeout_delay_; - - /* If the task has been currently scheduled. */ - bool is_scheduled_; - - DISALLOW_COPY_AND_ASSIGN(RecurringTask); -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_RECURRING_TASK_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task_test.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task_test.cc deleted file mode 100644 index cbe45e216f859af533760bb0fda108dff318e082..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/recurring-task_test.cc +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Unit tests for the RecurringTask class. - -#include "google/cacheinvalidation/client_test_internal.pb.h" -#include "google/cacheinvalidation/deps/googletest.h" -#include "google/cacheinvalidation/deps/random.h" -#include "google/cacheinvalidation/deps/string_util.h" -#include "google/cacheinvalidation/impl/recurring-task.h" -#include "google/cacheinvalidation/test/deterministic-scheduler.h" -#include "google/cacheinvalidation/test/test-logger.h" -#include "google/cacheinvalidation/test/test-utils.h" - -namespace invalidation { - -class RecurringTaskTest; - -/* A Test task that tracks how many times it has been called and returns - * true when the number of times, it has been called is less than the expected - * number. - */ -class TestTask : public RecurringTask { - public: - /* Initial delay used by the TestTask. */ - static TimeDelta initial_delay; - - /* Timeout delay used by the TestTask. */ - static TimeDelta timeout_delay; - - /* Creates a test task. - * - * |scheduler| Scheduler for the scheduling the task as needed. - * |logger| A logger. - * |smearer| For spreading/randomizing the delays. - * |delay_generator| An exponential backoff generator for task retries (if - * any). - * |test_name| The name of the current test. - * |max_runs| Maximum number of runs that are allowed. - * - * Space for all the objects with pointers is owned by the caller. - */ - TestTask(Scheduler* scheduler, Logger* logger, Smearer* smearer, - ExponentialBackoffDelayGenerator* delay_generator, - const string& test_name, int max_runs) - : RecurringTask(test_name, scheduler, logger, smearer, delay_generator, - initial_delay, timeout_delay), - current_runs(0), - max_runs_(max_runs), - scheduler_(scheduler), - logger_(logger) { - } - - virtual ~TestTask() {} - - // The actual implementation as required by the RecurringTask. - virtual bool RunTask() { - current_runs++; - TLOG(logger_, INFO, "(%d) Task running: %d", - scheduler_->GetCurrentTime().ToInternalValue(), current_runs); - return current_runs < max_runs_; - } - - /* The number of times that the task has been run. */ - int current_runs; - - private: - /* Maximum number of runs that are allowed. */ - int max_runs_; - - /* Scheduler for the task. */ - Scheduler* scheduler_; - - /* A logger. */ - Logger* logger_; -}; - -// Tests the basic functionality of the RecurringTask abstraction. -class RecurringTaskTest : public testing::Test { - public: - virtual ~RecurringTaskTest() {} - - // Performs setup for RecurringTask test. - virtual void SetUp() { - // Initialize values that are really constants. - initial_exp_backoff_delay = TimeDelta::FromMilliseconds(100); - TestTask::initial_delay = TimeDelta::FromMilliseconds(10); - TestTask::timeout_delay = TimeDelta::FromMilliseconds(50); - end_of_test_delay = 1000 * TestTask::timeout_delay; - - // Initialize state for every test. - random.reset(new FakeRandom(0.99)); // The test expects a value close to 1. - logger.reset(new TestLogger()); - scheduler.reset(new SimpleDeterministicScheduler(logger.get())); - smearer.reset(new Smearer(random.get(), 0)); - delay_generator = new ExponentialBackoffDelayGenerator( - random.get(), initial_exp_backoff_delay, kMaxExpBackoffFactor); - scheduler->StartScheduler(); - } - - /* Maximum delay factory used by the ExponentialBackoffDelayGenerator. */ - static const int kMaxExpBackoffFactor; - - /* Default number of runs that runTask is called in TestTask. */ - static const int kDefaultNumRuns; - - /* Initial delay used by the ExponentialBackoffDelayGenerator. */ - static TimeDelta initial_exp_backoff_delay; - - /* A long time delay that the scheduler is run for at the end of the test. */ - static TimeDelta end_of_test_delay; - - // - // Test state maintained for every test. - // - - // A logger. - scoped_ptr<Logger> logger; - - // Deterministic scheduler for careful scheduling of the tasks. - scoped_ptr<DeterministicScheduler> scheduler; - - // For randomizing delays. - scoped_ptr<Smearer> smearer; - - // A random number generator that always generates 1. - scoped_ptr<Random> random; - - // A delay generator (if used in the test). Not a scoped_ptr since it ends - // up being owned by the RecurringTask. - ExponentialBackoffDelayGenerator* delay_generator; -}; - -// Definitions for the static variables. -TimeDelta TestTask::initial_delay; -TimeDelta TestTask::timeout_delay; -TimeDelta RecurringTaskTest::initial_exp_backoff_delay; -TimeDelta RecurringTaskTest::end_of_test_delay; -const int RecurringTaskTest::kMaxExpBackoffFactor = 10; -const int RecurringTaskTest::kDefaultNumRuns = 8; - -/* Tests a task that is run periodically at regular intervals (not exponential - * backoff). - */ -TEST_F(RecurringTaskTest, PeriodicTask) { - /* Create a periodic task and pass time - make sure that the task runs exactly - * the number of times as expected. - */ - TestTask task(scheduler.get(), logger.get(), smearer.get(), NULL, - "PeriodicTask", kDefaultNumRuns); - task.EnsureScheduled("testPeriodicTask"); - - TimeDelta delay = TestTask::initial_delay + TestTask::timeout_delay; - - // Pass time so that the task is run kDefaultNumRuns times. - // First time, the task is scheduled after initial_delay. Then for - // numRuns - 1, it is scheduled after a delay of - // initial_delay + timeout_delay. - scheduler->PassTime(TestTask::initial_delay + - ((kDefaultNumRuns - 1) * delay)); - ASSERT_EQ(kDefaultNumRuns, task.current_runs); - - // Check that the passage of more time does not cause any more runs. - scheduler->PassTime(end_of_test_delay); - ASSERT_EQ(kDefaultNumRuns, task.current_runs); - delete delay_generator; -} - -/* Tests a task that is run periodically at regular intervals with - * exponential backoff. - */ -TEST_F(RecurringTaskTest, ExponentialBackoffTask) { - /* Create a periodic task and pass time - make sure that the task runs - * exactly the number of times as expected. - */ - TestTask task(scheduler.get(), logger.get(), smearer.get(), - delay_generator, "ExponentialBackoffTask", kDefaultNumRuns); - task.EnsureScheduled("testExponentialBackoffTask"); - - // Pass enough time so that exactly one event runs, two events run etc. - scheduler->PassTime(TestTask::initial_delay); - ASSERT_EQ(1, task.current_runs); - scheduler->PassTime(TestTask::timeout_delay + initial_exp_backoff_delay); - ASSERT_EQ(2, task.current_runs); - scheduler->PassTime( - TestTask::timeout_delay + (2 * initial_exp_backoff_delay)); - ASSERT_EQ(3, task.current_runs); - scheduler->PassTime( - TestTask::timeout_delay + (4 * initial_exp_backoff_delay)); - ASSERT_EQ(4, task.current_runs); - - // Check that the passage of more time does not cause any more runs. - scheduler->PassTime(end_of_test_delay); - ASSERT_EQ(kDefaultNumRuns, task.current_runs); -} - -/* Tests a one-shot task (i.e. no repetition) that is run twice. */ -TEST_F(RecurringTaskTest, OneShotTask) { - /* Create a no-repeating task and pass time - make sure that the task runs - * exactly once. Run it again - and make sure it is run again. - */ - - // Call ensureScheduled multiple times; ensure that the event is not scheduled - // multiple times. - TestTask task(scheduler.get(), logger.get(), smearer.get(), - delay_generator, "OneShotTask", 1); - task.EnsureScheduled("testOneShotTask"); - task.EnsureScheduled("testOneShotTask-2"); - task.EnsureScheduled("testOneShotTask-3"); - - // Pass enough time so that exactly one event runs. - scheduler->PassTime(TestTask::initial_delay); - ASSERT_EQ(1, task.current_runs); - - // Pass enough time so that exactly another event runs. - task.EnsureScheduled("testOneShotTask-4"); - scheduler->PassTime(TestTask::initial_delay); - ASSERT_EQ(2, task.current_runs); - - // Check that the passage of more time does not cause any more runs. - scheduler->PassTime(end_of_test_delay); - ASSERT_EQ(2, task.current_runs); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/registration-manager.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/registration-manager.cc deleted file mode 100644 index 3e4574ef15aa4a3a53e3c1f19d8330b2892b9de5..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/registration-manager.cc +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Object to track desired client registrations. This class belongs to caller -// (e.g., InvalidationClientImpl) and is not thread-safe - the caller has to use -// this class in a thread-safe manner. - -#include "google/cacheinvalidation/impl/registration-manager.h" - -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" -#include "google/cacheinvalidation/impl/log-macro.h" -#include "google/cacheinvalidation/impl/proto-helpers.h" -#include "google/cacheinvalidation/impl/simple-registration-store.h" - -namespace invalidation { - -RegistrationManager::RegistrationManager( - Logger* logger, Statistics* statistics, DigestFunction* digest_function) - : desired_registrations_(new SimpleRegistrationStore(digest_function)), - statistics_(statistics), - logger_(logger) { - // Initialize the server summary with a 0 size and the digest corresponding to - // it. Using defaultInstance would wrong since the server digest will not - // match unnecessarily and result in an info message being sent. - GetClientSummary(&last_known_server_summary_); -} - -void RegistrationManager::PerformOperations( - const vector<ObjectIdP>& object_ids, RegistrationP::OpType reg_op_type, - vector<ObjectIdP>* oids_to_send) { - // Record that we have pending operations on the objects. - vector<ObjectIdP>::const_iterator iter = object_ids.begin(); - for (; iter != object_ids.end(); iter++) { - pending_operations_[*iter] = reg_op_type; - } - // Update the digest appropriately. - if (reg_op_type == RegistrationP_OpType_REGISTER) { - desired_registrations_->Add(object_ids, oids_to_send); - } else { - desired_registrations_->Remove(object_ids, oids_to_send); - } -} - -void RegistrationManager::GetRegistrations( - const string& digest_prefix, int prefix_len, RegistrationSubtree* builder) { - vector<ObjectIdP> oids; - desired_registrations_->GetElements(digest_prefix, prefix_len, &oids); - for (size_t i = 0; i < oids.size(); ++i) { - builder->add_registered_object()->CopyFrom(oids[i]); - } -} - -void RegistrationManager::HandleRegistrationStatus( - const RepeatedPtrField<RegistrationStatus>& registration_statuses, - vector<bool>* success_status) { - - // Local-processing result code for each element of - // registrationStatuses. Indicates whether the registration status was - // compatible with the client's desired state (e.g., a successful unregister - // from the server when we desire a registration is incompatible). - for (int i = 0; i < registration_statuses.size(); ++i) { - const RegistrationStatus& registration_status = - registration_statuses.Get(i); - const ObjectIdP& object_id_proto = - registration_status.registration().object_id(); - - // The object is no longer pending, since we have received a server status - // for it, so remove it from the pendingOperations map. (It may or may not - // have existed in the map, since we can receive spontaneous status messages - // from the server.) - pending_operations_.erase(object_id_proto); - - // We start off with the local-processing set as success, then potentially - // fail. - bool is_success = true; - - // if the server operation succeeded, then local processing fails on - // "incompatibility" as defined above. - if (registration_status.status().code() == StatusP_Code_SUCCESS) { - bool app_wants_registration = - desired_registrations_->Contains(object_id_proto); - bool is_op_registration = - (registration_status.registration().op_type() == - RegistrationP_OpType_REGISTER); - bool discrepancy_exists = is_op_registration ^ app_wants_registration; - if (discrepancy_exists) { - // Remove the registration and set isSuccess to false, which will cause - // the caller to issue registration-failure to the application. - desired_registrations_->Remove(object_id_proto); - statistics_->RecordError( - Statistics::ClientErrorType_REGISTRATION_DISCREPANCY); - TLOG(logger_, INFO, - "Ticl discrepancy detected: registered = %d, requested = %d. " - "Removing %s from requested", - is_op_registration, app_wants_registration, - ProtoHelpers::ToString(object_id_proto).c_str()); - is_success = false; - } - } else { - // If the server operation failed, then local processing also fails. - desired_registrations_->Remove(object_id_proto); - TLOG(logger_, FINE, "Removing %s from committed", - ProtoHelpers::ToString(object_id_proto).c_str()); - is_success = false; - } - success_status->push_back(is_success); - } -} - -void RegistrationManager::GetClientSummary(RegistrationSummary* summary) { - summary->set_num_registrations(desired_registrations_->size()); - summary->set_registration_digest(desired_registrations_->GetDigest()); -} - -string RegistrationManager::ToString() { - return StringPrintf( - "Last known digest: %s, Requested regs: %s", - ProtoHelpers::ToString(last_known_server_summary_).c_str(), - desired_registrations_->ToString().c_str()); -} - -const char* RegistrationManager::kEmptyPrefix = ""; - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/registration-manager.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/registration-manager.h deleted file mode 100644 index 3490399ef711631dffda60a9862df7e909d2764e..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/registration-manager.h +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Object to track desired client registrations. This class belongs to caller -// (e.g., InvalidationClientImpl) and is not thread-safe - the caller has to use -// this class in a thread-safe manner. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_REGISTRATION_MANAGER_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_REGISTRATION_MANAGER_H_ - -#include <map> -#include <set> - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/deps/digest-function.h" -#include "google/cacheinvalidation/deps/scoped_ptr.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" -#include "google/cacheinvalidation/impl/digest-store.h" -#include "google/cacheinvalidation/impl/proto-helpers.h" -#include "google/cacheinvalidation/impl/statistics.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::map; -using INVALIDATION_STL_NAMESPACE::set; - -class RegistrationManager { - public: - RegistrationManager(Logger* logger, Statistics* statistics, - DigestFunction* digest_function); - - /* Sets the digest store to be digest_store for testing purposes. - * - * REQUIRES: This method is called before the Ticl has done any operations on - * this object. - */ - void SetDigestStoreForTest(DigestStore<ObjectIdP>* digest_store) { - desired_registrations_.reset(digest_store); - GetClientSummary(&last_known_server_summary_); - } - - void GetRegisteredObjectsForTest(vector<ObjectIdP>* registrations) { - desired_registrations_->GetElements(kEmptyPrefix, 0, registrations); - } - - /* (Un)registers for object_ids. When the function returns, oids_to_send will - * have been modified to contain those object ids for which registration - * messages must be sent to the server. - */ - void PerformOperations(const vector<ObjectIdP>& object_ids, - RegistrationP::OpType reg_op_type, - vector<ObjectIdP>* oids_to_send); - - /* Initializes a registration subtree for registrations where the digest of - * the object id begins with the prefix digest_prefix of prefix_len bits. This - * method may also return objects whose digest prefix does not match - * digest_prefix. - */ - void GetRegistrations(const string& digest_prefix, int prefix_len, - RegistrationSubtree* builder); - - /* - * Handles registration operation statuses from the server. Modifies |result| - * to contain one boolean per registration status, that indicates whether the - * registration operation was both successful and agreed with the desired - * client state (i.e., for each registration status, - * (status.optype == register) == - * desiredRegistrations.contains(status.objectid)). - * <p> - * REQUIRES: the caller subsequently make an informRegistrationStatus or - * informRegistrationFailure upcall on the listener for each registration in - * {@code registrationStatuses}. - */ - void HandleRegistrationStatus( - const RepeatedPtrField<RegistrationStatus>& registration_statuses, - vector<bool>* result); - - /* - * Removes all desired registrations and pending operations. Returns all - * object ids that were affected. - * <p> - * REQUIRES: the caller issue a permanent failure upcall to the listener for - * all returned object ids. - */ - void RemoveRegisteredObjects(vector<ObjectIdP>* result) { - // Add the formerly desired- and pending- registrations to result. - desired_registrations_->RemoveAll(result); - map<ObjectIdP, RegistrationP::OpType, ProtoCompareLess>::iterator - pending_iter = pending_operations_.begin(); - for (; pending_iter != pending_operations_.end(); pending_iter++) { - result->push_back(pending_iter->first); - } - pending_operations_.clear(); - - // De-dup result. - set<ObjectIdP, ProtoCompareLess> unique_oids(result->begin(), - result->end()); - result->assign(unique_oids.begin(), unique_oids.end()); - } - - // - // Digest-related methods - // - - /* Modifies client_summary to contain the summary of the desired - * registrations (by the client). */ - void GetClientSummary(RegistrationSummary* client_summary); - - /* Modifies server_summary to contain the last known summary from the server. - * If none, modifies server_summary to contain the summary corresponding - * to 0 registrations. */ - void GetServerSummary(RegistrationSummary* server_summary) { - server_summary->CopyFrom(last_known_server_summary_); - } - - /* Informs the manager of a new registration state summary from the server. - * Modifies upcalls to contain zero or more RegistrationP. For each added - * RegistrationP, the caller should make an inform-registration-status upcall - * on the listener. - */ - void InformServerRegistrationSummary(const RegistrationSummary& reg_summary, - vector<RegistrationP>* upcalls) { - last_known_server_summary_.CopyFrom(reg_summary); - if (IsStateInSyncWithServer()) { - // If we are now in sync with the server, then the caller should make - // inform-reg-status upcalls for all operations that we had pending, if - // any; they are also no longer pending. - map<ObjectIdP, RegistrationP::OpType, ProtoCompareLess>::iterator - pending_iter = pending_operations_.begin(); - for (; pending_iter != pending_operations_.end(); pending_iter++) { - RegistrationP reg_p; - ProtoHelpers::InitRegistrationP(pending_iter->first, - pending_iter->second, ®_p); - upcalls->push_back(reg_p); - } - pending_operations_.clear(); - } - } - - /* Returns whether the local registration state and server state agree, based - * on the last received server summary (from InformServerRegistrationSummary). - */ - bool IsStateInSyncWithServer() { - RegistrationSummary summary; - GetClientSummary(&summary); - return (last_known_server_summary_.num_registrations() == - summary.num_registrations()) && - (last_known_server_summary_.registration_digest() == - summary.registration_digest()); - } - - string ToString(); - - // Empty hash prefix. - static const char* kEmptyPrefix; - - private: - /* The set of regisrations that the application has requested for. */ - scoped_ptr<DigestStore<ObjectIdP> > desired_registrations_; - - /* Statistics objects to track number of sent messages, etc. */ - Statistics* statistics_; - - /* Latest known server registration state summary. */ - RegistrationSummary last_known_server_summary_; - - /* - * Map of object ids and operation types for which we have not yet issued any - * registration-status upcall to the listener. We need this so that we can - * synthesize success upcalls if registration sync, rather than a server - * message, communicates to us that we have a successful (un)registration. - * <p> - * This is a map from object id to type, rather than a set of RegistrationP, - * because a set of RegistrationP would assume that we always get a response - * for every operation we issue, which isn't necessarily true (i.e., the - * server might send back an unregistration status in response to a - * registration request). - */ - map<ObjectIdP, RegistrationP::OpType, ProtoCompareLess> - pending_operations_; - - Logger* logger_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_REGISTRATION_MANAGER_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/repeated-field-namespace-fix.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/repeated-field-namespace-fix.h deleted file mode 100644 index 94ba25ad5d5f96b7a3a1e9cde8804f56a03e506f..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/repeated-field-namespace-fix.h +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2013 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// -// Brings RepeatedField classes into invalidation namespace. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_REPEATED_FIELD_NAMESPACE_FIX_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_REPEATED_FIELD_NAMESPACE_FIX_H_ - -#include "google/protobuf/repeated_field.h" - -namespace invalidation { - -using ::google::protobuf::RepeatedField; -using ::google::protobuf::RepeatedPtrField; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_REPEATED_FIELD_NAMESPACE_FIX_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/run-state.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/run-state.h deleted file mode 100644 index f330438a637203d7bffddcf383daa9ac74e3c960..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/run-state.h +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An abstraction that keeps track of whether the caller is started or stopped -// and only allows the following transitions NOT_STARTED -> STARTED -> -// STOPPED. This class is thread-safe. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_RUN_STATE_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_RUN_STATE_H_ - -#include "google/cacheinvalidation/client.pb.h" -#include "google/cacheinvalidation/deps/logging.h" -#include "google/cacheinvalidation/deps/mutex.h" -#include "google/cacheinvalidation/deps/string_util.h" - -namespace invalidation { - -using ::ipc::invalidation::RunStateP_State; -using ::ipc::invalidation::RunStateP_State_NOT_STARTED; -using ::ipc::invalidation::RunStateP_State_STARTED; -using ::ipc::invalidation::RunStateP_State_STOPPED; - -class RunState { - public: - RunState() : current_state_(RunStateP_State_NOT_STARTED) {} - - /* Marks the current state to be STARTED. - * - * REQUIRES: Current state is NOT_STARTED. - */ - void Start() { - MutexLock m(&lock_); - CHECK(current_state_ == RunStateP_State_NOT_STARTED) << "Cannot start: " - << current_state_; - current_state_ = RunStateP_State_STARTED; - } - - /* Marks the current state to be STOPPED. - * - * REQUIRES: Current state is STARTED. - */ - void Stop() { - MutexLock m(&lock_); - CHECK(current_state_ == RunStateP_State_STARTED) << "Cannot stop: " - << current_state_; - current_state_ = RunStateP_State_STOPPED; - } - - /* Returns true iff Start has been called on this but Stop has not been - * called. - */ - bool IsStarted() const { - // Don't treat locking a mutex as mutation. - MutexLock m((Mutex *) &lock_); // NOLINT - return current_state_ == RunStateP_State_STARTED; - } - - /* Returns true iff Start and Stop have been called on this object. */ - bool IsStopped() const { - // Don't treat locking a mutex as mutation. - MutexLock m((Mutex *) &lock_); // NOLINT - return current_state_ == RunStateP_State_STOPPED; - } - - string ToString() { - return StringPrintf("<RunState %d>", current_state_); - } - - private: - RunStateP_State current_state_; - Mutex lock_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_RUN_STATE_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/safe-storage.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/safe-storage.cc deleted file mode 100644 index f418fbd31bd7612d2bda897e0ab43b00baf61b08..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/safe-storage.cc +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An implementation of the Storage resource that schedules the callbacks on the -// given scheduler thread. -// - -#include "google/cacheinvalidation/impl/safe-storage.h" - -namespace invalidation { - -void SafeStorage::SetSystemResources(SystemResources* resources) { - scheduler_ = resources->internal_scheduler(); -} - -void SafeStorage::WriteKey(const string& key, const string& value, - WriteKeyCallback* done) { - delegate_->WriteKey(key, value, - NewPermanentCallback(this, &SafeStorage::WriteCallback, done)); -} - -void SafeStorage::WriteCallback(WriteKeyCallback* done, Status status) { - scheduler_->Schedule( - Scheduler::NoDelay(), - /* Owns 'done'. */ NewPermanentCallback(done, status)); -} - -void SafeStorage::ReadKey(const string& key, ReadKeyCallback* done) { - delegate_->ReadKey(key, - NewPermanentCallback(this, &SafeStorage::ReadCallback, done)); -} - -void SafeStorage::ReadCallback(ReadKeyCallback* done, - StatusStringPair read_result) { - scheduler_->Schedule( - Scheduler::NoDelay(), - /* Owns 'done'. */ NewPermanentCallback(done, read_result)); -} - -void SafeStorage::DeleteKey(const string& key, DeleteKeyCallback* done) { - delegate_->DeleteKey(key, - NewPermanentCallback(this, &SafeStorage::DeleteCallback, done)); -} - -void SafeStorage::DeleteCallback(DeleteKeyCallback* done, bool result) { - scheduler_->Schedule( - Scheduler::NoDelay(), - /* Owns 'done'. */ NewPermanentCallback(done, result)); -} - -void SafeStorage::ReadAllKeys(ReadAllKeysCallback* key_callback) { - delegate_->ReadAllKeys( - NewPermanentCallback(this, &SafeStorage::ReadAllCallback, key_callback)); -} - -void SafeStorage::ReadAllCallback(ReadAllKeysCallback* key_callback, - StatusStringPair result) { - scheduler_->Schedule( - Scheduler::NoDelay(), - /* Owns 'key_callback'. */ NewPermanentCallback(key_callback, result)); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/safe-storage.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/safe-storage.h deleted file mode 100644 index b6ec2dcbbb26a1bb94676eb47993a4bfa26911db..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/safe-storage.h +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// -// An implementation of the Storage resource that schedules the callbacks on the -// given scheduler thread. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_SAFE_STORAGE_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_SAFE_STORAGE_H_ - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/include/types.h" - -namespace invalidation { - -// An implementation of the Storage resource that schedules the callbacks on the -// given scheduler thread. -class SafeStorage : public Storage { - public: - /* Creates a new instance. Storage for |delegate| is owned by caller. */ - explicit SafeStorage(Storage* delegate) : delegate_(delegate) { - } - - virtual ~SafeStorage() {} - - // All public methods below are methods of the Storage interface. - virtual void SetSystemResources(SystemResources* resources); - - virtual void WriteKey(const string& key, const string& value, - WriteKeyCallback* done); - - virtual void ReadKey(const string& key, ReadKeyCallback* done); - - virtual void DeleteKey(const string& key, DeleteKeyCallback* done); - - virtual void ReadAllKeys(ReadAllKeysCallback* key_callback); - - private: - /* Callback invoked when WriteKey finishes. */ - void WriteCallback(WriteKeyCallback* done, Status status); - - /* Callback invoked when ReadKey finishes. */ - void ReadCallback(ReadKeyCallback* done, StatusStringPair read_result); - - /* Callback invoked when DeleteKey finishes. */ - void DeleteCallback(DeleteKeyCallback* done, bool result); - - /* Callback invoked when ReadAllKeys finishes. */ - void ReadAllCallback(ReadAllKeysCallback* key_callback, - StatusStringPair result); - - /* The delegate to which the calls are forwarded. */ - Storage* delegate_; - - /* The scheduler on which the callbacks are scheduled. */ - Scheduler* scheduler_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_SAFE_STORAGE_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/simple-registration-store.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/simple-registration-store.cc deleted file mode 100644 index 98d284ace8d329cbd331ded7135dcca3a63fa8bb..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/simple-registration-store.cc +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Simple, map-based implementation of DigestStore. - -#include "google/cacheinvalidation/impl/simple-registration-store.h" - -#include "google/cacheinvalidation/impl/object-id-digest-utils.h" - -namespace invalidation { - -bool SimpleRegistrationStore::Add(const ObjectIdP& oid) { - const string digest = ObjectIdDigestUtils::GetDigest(oid, digest_function_); - bool will_add = (registrations_.find(digest) == registrations_.end()); - if (will_add) { - registrations_[digest] = oid; - RecomputeDigest(); - } - return will_add; -} - -void SimpleRegistrationStore::Add(const vector<ObjectIdP>& oids, - vector<ObjectIdP>* oids_to_send) { - for (size_t i = 0; i < oids.size(); ++i) { - const ObjectIdP& oid = oids[i]; - const string digest = ObjectIdDigestUtils::GetDigest(oid, digest_function_); - bool will_add = (registrations_.find(digest) == registrations_.end()); - if (will_add) { - registrations_[digest] = oid; - oids_to_send->push_back(oid); - } - } - if (!oids_to_send->empty()) { - // Only recompute the digest if we made changes. - RecomputeDigest(); - } -} - -bool SimpleRegistrationStore::Remove(const ObjectIdP& oid) { - const string digest = ObjectIdDigestUtils::GetDigest(oid, digest_function_); - bool will_remove = (registrations_.find(digest) != registrations_.end()); - if (will_remove) { - registrations_.erase(digest); - RecomputeDigest(); - } - return will_remove; -} - -void SimpleRegistrationStore::Remove(const vector<ObjectIdP>& oids, - vector<ObjectIdP>* oids_to_send) { - for (size_t i = 0; i < oids.size(); ++i) { - const ObjectIdP& oid = oids[i]; - const string digest = ObjectIdDigestUtils::GetDigest(oid, digest_function_); - bool will_remove = (registrations_.find(digest) != registrations_.end()); - if (will_remove) { - registrations_.erase(digest); - oids_to_send->push_back(oid); - } - } - if (!oids_to_send->empty()) { - // Only recompute the digest if we made changes. - RecomputeDigest(); - } -} - -void SimpleRegistrationStore::RemoveAll(vector<ObjectIdP>* oids) { - for (map<string, ObjectIdP>::const_iterator iter = registrations_.begin(); - iter != registrations_.end(); ++iter) { - oids->push_back(iter->second); - } - registrations_.clear(); - RecomputeDigest(); -} - -bool SimpleRegistrationStore::Contains(const ObjectIdP& oid) { - return registrations_.find( - ObjectIdDigestUtils::GetDigest(oid, digest_function_)) != - registrations_.end(); -} - -void SimpleRegistrationStore::GetElements( - const string& oid_digest_prefix, int prefix_len, - vector<ObjectIdP>* result) { - // We always return all the registrations and let the Ticl sort it out. - for (map<string, ObjectIdP>::iterator iter = registrations_.begin(); - iter != registrations_.end(); ++iter) { - result->push_back(iter->second); - } -} - -void SimpleRegistrationStore::RecomputeDigest() { - digest_ = ObjectIdDigestUtils::GetDigest( - registrations_, digest_function_); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/simple-registration-store.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/simple-registration-store.h deleted file mode 100644 index 226cb876755390c0010ec025c97daac639637e19..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/simple-registration-store.h +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Simple, map-based implementation of DigestStore. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_SIMPLE_REGISTRATION_STORE_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_SIMPLE_REGISTRATION_STORE_H_ - -#include <map> - -#include "google/cacheinvalidation/deps/digest-function.h" -#include "google/cacheinvalidation/deps/string_util.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" -#include "google/cacheinvalidation/impl/digest-store.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::map; - -class SimpleRegistrationStore : public DigestStore<ObjectIdP> { - public: - explicit SimpleRegistrationStore(DigestFunction* digest_function) - : digest_function_(digest_function) { - RecomputeDigest(); - } - - virtual ~SimpleRegistrationStore() {} - - virtual bool Add(const ObjectIdP& oid); - - virtual void Add(const vector<ObjectIdP>& oids, - vector<ObjectIdP>* oids_to_send); - - virtual bool Remove(const ObjectIdP& oid); - - virtual void Remove(const vector<ObjectIdP>& oids, - vector<ObjectIdP>* oids_to_send); - - virtual void RemoveAll(vector<ObjectIdP>* oids); - - virtual bool Contains(const ObjectIdP& oid); - - virtual int size() { - return registrations_.size(); - } - - virtual string GetDigest() { - return digest_; - } - - virtual void GetElements(const string& oid_digest_prefix, int prefix_len, - vector<ObjectIdP>* result); - - virtual string ToString() { - return StringPrintf("SimpleRegistrationStore: %d registrations", - static_cast<int>(registrations_.size())); - } - - private: - /* Recomputes the digests over all objects and sets this.digest. */ - void RecomputeDigest(); - - /* All the registrations in the store mappd from the digest to the ibject id. - */ - map<string, ObjectIdP> registrations_; - - /* The function used to compute digests of objects. */ - DigestFunction* digest_function_; - - /* The memoized digest of all objects in registrations. */ - string digest_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_SIMPLE_REGISTRATION_STORE_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/smearer.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/smearer.h deleted file mode 100644 index 7fc43f0bca13c7d2f0e4a59c87893edd9440a53d..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/smearer.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An abstraction to "smear" values by a given percent. Useful for randomizing -// delays a little bit so that (say) processes do not get synchronized on time -// inadvertently, e.g., a heartbeat task that sends a message every few minutes -// is smeared so that all clients do not end up sending a message at the same -// time. In particular, given a |delay|, returns a value that is randomly -// distributed between -// [delay - smearPercent * delay, delay + smearPercent * delay] - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_SMEARER_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_SMEARER_H_ - -#include "google/cacheinvalidation/deps/logging.h" -#include "google/cacheinvalidation/deps/random.h" -#include "google/cacheinvalidation/deps/scoped_ptr.h" - -namespace invalidation { - -class Smearer { - public: - /* Creates a smearer with the given random number generator. - * REQUIRES: 0 <= smear_percent <= 100 - * Caller continues to own space for random. - */ - Smearer(Random* random, int smear_percent) : random_(random), - smear_fraction_(smear_percent / 100.0) { - CHECK((smear_percent >= 0) && (smear_percent <= 100)); - } - - /* Given a delay, returns a value that is randomly distributed between - * (delay - smear_percent * delay, delay + smear_percent * delay) - */ - TimeDelta GetSmearedDelay(TimeDelta delay) { - // Get a random number between -1 and 1 and then multiply that by the - // smear fraction. - double smear_factor = (2 * random_->RandDouble() - 1.0) * smear_fraction_; - return TimeDelta::FromMilliseconds( - delay.InMilliseconds() * (1.0 + smear_factor)); - } - - private: - Random* random_; - - /* The percentage (0, 1.0] for smearing the delay. */ - double smear_fraction_; -}; -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_SMEARER_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/statistics.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/statistics.cc deleted file mode 100644 index 382d45cfdb1d47a4bb8abcb64024db0195c43a5e..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/statistics.cc +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Statistics for the Ticl, e.g., number of registration calls, number of token -// mismatches, etc. - -#include "google/cacheinvalidation/impl/statistics.h" - -namespace invalidation { - -const char* Statistics::SentMessageType_names[] = { - "INFO", - "INITIALIZE", - "INVALIDATION_ACK", - "REGISTRATION", - "REGISTRATION_SYNC", - "TOTAL", -}; - -const char* Statistics::ReceivedMessageType_names[] = { - "INFO_REQUEST", - "INVALIDATION", - "REGISTRATION_STATUS", - "REGISTRATION_SYNC_REQUEST", - "TOKEN_CONTROL", - "ERROR", - "CONFIG_CHANGE", - "TOTAL", -}; - -const char* Statistics::IncomingOperationType_names[] = { - "ACKNOWLEDGE", - "REGISTRATION", - "UNREGISTRATION", -}; - -const char* Statistics::ListenerEventType_names[] = { - "INFORM_ERROR", - "INFORM_REGISTRATION_FAILURE", - "INFORM_REGISTRATION_STATUS", - "INVALIDATE", - "INVALIDATE_ALL", - "INVALIDATE_UNKNOWN", - "REISSUE_REGISTRATIONS", -}; - -const char* Statistics::ClientErrorType_names[] = { - "ACKNOWLEDGE_HANDLE_FAILURE", - "INCOMING_MESSAGE_FAILURE", - "OUTGOING_MESSAGE_FAILURE", - "PERSISTENT_DESERIALIZATION_FAILURE", - "PERSISTENT_READ_FAILURE", - "PERSISTENT_WRITE_FAILURE", - "PROTOCOL_VERSION_FAILURE", - "REGISTRATION_DISCREPANCY", - "NONCE_MISMATCH", - "TOKEN_MISMATCH", - "TOKEN_MISSING_FAILURE", - "TOKEN_TRANSIENT_FAILURE", -}; - -Statistics::Statistics() { - InitializeMap(sent_message_types_, SentMessageType_MAX + 1); - InitializeMap(received_message_types_, ReceivedMessageType_MAX + 1); - InitializeMap(incoming_operation_types_, IncomingOperationType_MAX + 1); - InitializeMap(listener_event_types_, ListenerEventType_MAX + 1); - InitializeMap(client_error_types_, ClientErrorType_MAX + 1); -} - -void Statistics::GetNonZeroStatistics( - vector<pair<string, int> >* performance_counters) { - // Add the non-zero values from the different maps to performance_counters. - FillWithNonZeroStatistics( - sent_message_types_, SentMessageType_MAX + 1, SentMessageType_names, - "SentMessageType.", performance_counters); - FillWithNonZeroStatistics( - received_message_types_, ReceivedMessageType_MAX + 1, - ReceivedMessageType_names, "ReceivedMessageType.", - performance_counters); - FillWithNonZeroStatistics( - incoming_operation_types_, IncomingOperationType_MAX + 1, - IncomingOperationType_names, "IncomingOperationType.", - performance_counters); - FillWithNonZeroStatistics( - listener_event_types_, ListenerEventType_MAX + 1, ListenerEventType_names, - "ListenerEventType.", performance_counters); - FillWithNonZeroStatistics( - client_error_types_, ClientErrorType_MAX + 1, ClientErrorType_names, - "ClientErrorType.", performance_counters); -} - -/* Modifies result to contain those statistics from map whose value is > 0. */ -void Statistics::FillWithNonZeroStatistics( - int map[], int size, const char* names[], const char* prefix, - vector<pair<string, int> >* destination) { - for (int i = 0; i < size; ++i) { - if (map[i] > 0) { - destination->push_back( - make_pair(StringPrintf("%s%s", prefix, names[i]), map[i])); - } - } -} - -void Statistics::InitializeMap(int map[], int size) { - for (int i = 0; i < size; ++i) { - map[i] = 0; - } -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/statistics.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/statistics.h deleted file mode 100644 index fcbc49ebce363cfe1508c4cacf58f57dcae35063..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/statistics.h +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Statistics for the Ticl, e.g., number of registration calls, number of token -// mismatches, etc. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_STATISTICS_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_STATISTICS_H_ - -#include <string> -#include <utility> -#include <vector> - -#include "google/cacheinvalidation/deps/stl-namespace.h" -#include "google/cacheinvalidation/deps/string_util.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::pair; -using INVALIDATION_STL_NAMESPACE::string; -using INVALIDATION_STL_NAMESPACE::vector; - -class Statistics { - public: - // Implementation: To classify the statistics a bit better, we have a few - // enums to track different different types of statistics, e.g., sent message - // types, errors, etc. For each statistic type, we create a map and provide a - // method to record an event for each type of statistic. - - /* Types of messages sent to the server: ClientToServerMessage for their - * description. - */ - enum SentMessageType { - SentMessageType_INFO, - SentMessageType_INITIALIZE, - SentMessageType_INVALIDATION_ACK, - SentMessageType_REGISTRATION, - SentMessageType_REGISTRATION_SYNC, - SentMessageType_TOTAL, // Refers to the actual ClientToServerMessage - // message sent on the network. - }; - static const SentMessageType SentMessageType_MIN = SentMessageType_INFO; - static const SentMessageType SentMessageType_MAX = SentMessageType_TOTAL; - static const char* SentMessageType_names[]; - - /* Types of messages received from the server: ServerToClientMessage for their - * description. - */ - enum ReceivedMessageType { - ReceivedMessageType_INFO_REQUEST, - ReceivedMessageType_INVALIDATION, - ReceivedMessageType_REGISTRATION_STATUS, - ReceivedMessageType_REGISTRATION_SYNC_REQUEST, - ReceivedMessageType_TOKEN_CONTROL, - ReceivedMessageType_ERROR, - ReceivedMessageType_CONFIG_CHANGE, - ReceivedMessageType_TOTAL, // Refers to the actual ServerToClientMessage - // messages received from the network. - }; - static const ReceivedMessageType ReceivedMessageType_MIN = - ReceivedMessageType_INFO_REQUEST; - static const ReceivedMessageType ReceivedMessageType_MAX = - ReceivedMessageType_TOTAL; - static const char* ReceivedMessageType_names[]; - - /* Interesting API calls coming from the application (see InvalidationClient). - */ - enum IncomingOperationType { - IncomingOperationType_ACKNOWLEDGE, - IncomingOperationType_REGISTRATION, - IncomingOperationType_UNREGISTRATION, - }; - static const IncomingOperationType IncomingOperationType_MIN = - IncomingOperationType_ACKNOWLEDGE; - static const IncomingOperationType IncomingOperationType_MAX = - IncomingOperationType_UNREGISTRATION; - static const char* IncomingOperationType_names[]; - - /* Different types of events issued by the InvalidationListener. */ - enum ListenerEventType { - ListenerEventType_INFORM_ERROR, - ListenerEventType_INFORM_REGISTRATION_FAILURE, - ListenerEventType_INFORM_REGISTRATION_STATUS, - ListenerEventType_INVALIDATE, - ListenerEventType_INVALIDATE_ALL, - ListenerEventType_INVALIDATE_UNKNOWN, - ListenerEventType_REISSUE_REGISTRATIONS, - }; - static const ListenerEventType ListenerEventType_MIN = - ListenerEventType_INFORM_ERROR; - static const ListenerEventType ListenerEventType_MAX = - ListenerEventType_REISSUE_REGISTRATIONS; - static const char* ListenerEventType_names[]; - - /* Different types of errors observed by the Ticl. */ - enum ClientErrorType { - /* Acknowledge call received from client with a bad handle. */ - ClientErrorType_ACKNOWLEDGE_HANDLE_FAILURE, - - /* Incoming message dropped due to parsing, validation problems. */ - ClientErrorType_INCOMING_MESSAGE_FAILURE, - - /* Tried to send an outgoing message that was invalid. */ - ClientErrorType_OUTGOING_MESSAGE_FAILURE, - - /* Persistent state failed to deserialize correctly. */ - ClientErrorType_PERSISTENT_DESERIALIZATION_FAILURE, - - /* Read of blob from persistent state failed. */ - ClientErrorType_PERSISTENT_READ_FAILURE, - - /* Write of blob from persistent state failed. */ - ClientErrorType_PERSISTENT_WRITE_FAILURE, - - /* Message received with incompatible protocol version. */ - ClientErrorType_PROTOCOL_VERSION_FAILURE, - - /* Registration at client and server is different, e.g., client thinks it is - * registered while the server says it is unregistered (of course, sync will - * fix it). - */ - ClientErrorType_REGISTRATION_DISCREPANCY, - - /* The nonce from the server did not match the current nonce by the client. - */ - ClientErrorType_NONCE_MISMATCH, - - /* The current token at the client is different from the token in the - * incoming message. - */ - ClientErrorType_TOKEN_MISMATCH, - - /* No message sent due to token missing. */ - ClientErrorType_TOKEN_MISSING_FAILURE, - - /* Received a message with a token (transient) failure. */ - ClientErrorType_TOKEN_TRANSIENT_FAILURE, - }; - static const ClientErrorType ClientErrorType_MIN = - ClientErrorType_ACKNOWLEDGE_HANDLE_FAILURE; - static const ClientErrorType ClientErrorType_MAX = - ClientErrorType_TOKEN_TRANSIENT_FAILURE; - static const char* ClientErrorType_names[]; - - // Arrays for each type of Statistic to keep track of how many times each - // event has occurred. - - Statistics(); - - /* Returns the counter value for client_error_type. */ - int GetClientErrorCounterForTest(ClientErrorType client_error_type) { - return client_error_types_[client_error_type]; - } - - /* Returns the counter value for sent_message_type. */ - int GetSentMessageCounterForTest(SentMessageType sent_message_type) { - return sent_message_types_[sent_message_type]; - } - - /* Returns the counter value for received_message_type. */ - int GetReceivedMessageCounterForTest( - ReceivedMessageType received_message_type) { - return received_message_types_[received_message_type]; - } - - /* Records the fact that a message of type sent_message_type has been sent. */ - void RecordSentMessage(SentMessageType sent_message_type) { - ++sent_message_types_[sent_message_type]; - } - - /* Records the fact that a message of type received_message_type has been - * received. - */ - void RecordReceivedMessage(ReceivedMessageType received_message_type) { - ++received_message_types_[received_message_type]; - } - - /* Records the fact that the application has made a call of type - * incoming_operation_type. - */ - void RecordIncomingOperation(IncomingOperationType incoming_operation_type) { - ++incoming_operation_types_[incoming_operation_type]; - } - - /* Records the fact that the listener has issued an event of type - * listener_event_type. - */ - void RecordListenerEvent(ListenerEventType listener_event_type) { - ++listener_event_types_[listener_event_type]; - } - - /* Records the fact that the client has observed an error of type - * client_error_type. - */ - void RecordError(ClientErrorType client_error_type) { - ++client_error_types_[client_error_type]; - } - - /* Modifies performance_counters to contain all the statistics that are - * non-zero. Each pair has the name of the statistic event and the number of - * times that event has occurred since the client started. - */ - void GetNonZeroStatistics(vector<pair<string, int> >* performance_counters); - - /* Modifies result to contain those statistics from map whose value is > 0. */ - static void FillWithNonZeroStatistics( - int map[], int size, const char* names[], const char* prefix, - vector<pair<string, int> >* destination); - - /* Initialzes all values for keys in map to be 0. */ - static void InitializeMap(int map[], int size); - - private: - int sent_message_types_[SentMessageType_MAX + 1]; - int received_message_types_[ReceivedMessageType_MAX + 1]; - int incoming_operation_types_[IncomingOperationType_MAX + 1]; - int listener_event_types_[ListenerEventType_MAX + 1]; - int client_error_types_[ClientErrorType_MAX + 1]; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_STATISTICS_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle.cc deleted file mode 100644 index fa84fc870cda307dd08472592740303c7d61e1ea..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle.cc +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Throttles calls to a function. - -#include "google/cacheinvalidation/impl/throttle.h" - -#include <algorithm> - -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/deps/callback.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::max; - -Throttle::Throttle( - const RepeatedPtrField<RateLimitP>& rate_limits, Scheduler* scheduler, - Closure* listener) - : rate_limits_(rate_limits), scheduler_(scheduler), listener_(listener), - timer_scheduled_(false) { - - // Find the largest 'count' in all of the rate limits, as this is the size of - // the buffer of recent messages we need to retain. - max_recent_events_ = 1; - for (size_t i = 0; i < static_cast<size_t>(rate_limits_.size()); ++i) { - const RateLimitP& rate_limit = rate_limits.Get(i); - CHECK(rate_limit.window_ms() > rate_limit.count()) << - "Windows size too small"; - max_recent_events_ = max(static_cast<int>(max_recent_events_), - rate_limits_.Get(i).count()); - } -} - -void Throttle::Fire() { - if (timer_scheduled_) { - // We're already rate-limited and have a deferred call scheduled. Just - // return. The flag will be reset when the deferred task runs. - return; - } - // Go through all of the limits to see if we've hit one. If so, schedule a - // task to try again once that limit won't be violated. If no limits would be - // violated, send. - Time now = scheduler_->GetCurrentTime(); - for (size_t i = 0; i < static_cast<size_t>(rate_limits_.size()); ++i) { - RateLimitP rate_limit = rate_limits_.Get(i); - - // We're now checking whether sending would violate a rate limit of 'count' - // messages per 'window_size'. - int count = rate_limit.count(); - TimeDelta window_size = TimeDelta::FromMilliseconds(rate_limit.window_ms()); - - // First, see how many messages we've sent so far (up to the size of our - // recent message buffer). - int num_recent_messages = recent_event_times_.size(); - - // Check whether we've sent enough messages yet that we even need to - // consider this rate limit. - if (num_recent_messages >= count) { - // If we've sent enough messages to reach this limit, see how long ago we - // sent the first message in the interval, and add sufficient delay to - // avoid violating the rate limit. - - // We have sent at least 'count' messages. See how long ago we sent the - // 'count'-th last message. This defines the start of a window in which - // no more than 'count' messages may be sent. - Time window_start = recent_event_times_[num_recent_messages - count]; - - // The end of this window is 'window_size' after the start. - Time window_end = window_start + window_size; - - // Check where the end of the window is relative to the current time. If - // the end of the window is in the future, then sending now would violate - // the rate limit, so we must defer. - TimeDelta window_end_from_now = window_end - now; - if (window_end_from_now > TimeDelta::FromSeconds(0)) { - // Rate limit would be violated, so schedule a task to try again. - - // Set the flag to indicate we have a deferred task scheduled. No need - // to continue checking other rate limits now. - timer_scheduled_ = true; - scheduler_->Schedule( - window_end_from_now, - NewPermanentCallback(this, &Throttle::RetryFire)); - return; - } - } - } - // We checked all the rate limits, and none would have been violated, so it's - // safe to call the listener. - listener_->Run(); - - // Record the fact that we're triggering an event now. - recent_event_times_.push_back(scheduler_->GetCurrentTime()); - - // Only save up to max_recent_events_ event times. - if (recent_event_times_.size() > max_recent_events_) { - recent_event_times_.pop_front(); - } -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle.h deleted file mode 100644 index 448dcf85414297264f62ca863d5fbff2248e07e5..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle.h +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Throttles calls to a function. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_THROTTLE_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_THROTTLE_H_ - -#include <cstddef> -#include <deque> -#include <vector> - -#include "google/cacheinvalidation/deps/callback.h" -#include "google/cacheinvalidation/deps/logging.h" -#include "google/cacheinvalidation/deps/scoped_ptr.h" -#include "google/cacheinvalidation/deps/stl-namespace.h" -#include "google/cacheinvalidation/deps/time.h" -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" - -namespace invalidation { - -class Scheduler; - -using INVALIDATION_STL_NAMESPACE::deque; -using INVALIDATION_STL_NAMESPACE::vector; - -// Provides an abstraction for multi-level rate-limiting. For example, the -// default limits state that no more than one message should be sent per second, -// or six per minute. Rate-limiting is implemented by maintaining a buffer of -// recent messages, which is as large as the highest 'count' property. Note: -// this means the object consumes space proportional to the _largest_ 'count'. -class Throttle { - public: - // Constructs a throttler to enforce the given rate limits for the given - // listener, using the given system resources. Ownership of scheduler is - // retained by the caller, but the throttle takes ownership of the listener. - Throttle(const RepeatedPtrField<RateLimitP>& rate_limits, - Scheduler* scheduler, Closure* listener); - - // If calling the listener would not violate the rate limits, does so. - // Otherwise, schedules a timer to do so as soon as doing so would not violate - // the rate limits, unless such a timer is already set, in which case does - // nothing. I.e., once the rate limit is reached, additional calls are not - // queued. - void Fire(); - - private: - // Retries a call to Fire() after some delay. - void RetryFire() { - timer_scheduled_ = false; - Fire(); - } - - // Rate limits to be enforced by this object. - RepeatedPtrField<RateLimitP> rate_limits_; - - // Scheduler for reading the current time and scheduling tasks that need to be - // delayed. - Scheduler* scheduler_; - - // The closure whose calls are throttled. - scoped_ptr<Closure> listener_; - - // Whether we've already scheduled a deferred call. - bool timer_scheduled_; - - // A buffer of recent events, so we can determine the length of the interval - // in which we made the most recent K events. - deque<Time> recent_event_times_; - - // The maximum size of the recent_event_times_ buffer. - size_t max_recent_events_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_THROTTLE_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle_test.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle_test.cc deleted file mode 100644 index 2df0de00378761d819c8ed65c8225cf0bf028c1a..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/throttle_test.cc +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Tests the throttle. - -#include "google/cacheinvalidation/deps/googletest.h" -#include "google/cacheinvalidation/impl/proto-helpers.h" -#include "google/cacheinvalidation/impl/throttle.h" -#include "google/cacheinvalidation/test/deterministic-scheduler.h" -#include "google/cacheinvalidation/test/test-logger.h" - -namespace invalidation { - -class ThrottleTest : public testing::Test { - public: - ThrottleTest() : call_count_(0) {} - - virtual ~ThrottleTest() {} - - // Increments the call count. - void IncrementCounter() { - ++call_count_; - } - - // Increments the call count and checks state to ensure that rate limits are - // being observed. - void IncrementAndCheckRateLimits() { - // Increment the call count. - ++call_count_; - // Check that we haven't been called within the last one second. - Time now = scheduler_->GetCurrentTime(); - ASSERT_TRUE((now - last_call_time_) >= TimeDelta::FromSeconds(1)); - // Update the last time we were called to now. - last_call_time_ = now; - // Check that enough time has passed to allow the number of calls we've - // received. - Time min_time = start_time_ + TimeDelta::FromMinutes( - (call_count_ - 1) / kMessagesPerMinute); - ASSERT_TRUE(min_time <= now); - } - - void SetUp() { - logger_.reset(new TestLogger()); - scheduler_.reset(new DeterministicScheduler(logger_.get())); - start_time_ = scheduler_->GetCurrentTime(); - call_count_ = 0; - last_call_time_ = Time() - TimeDelta::FromHours(1); - ProtoHelpers::InitRateLimitP(1000, kMessagesPerSecond, rate_limits_.Add()); - ProtoHelpers::InitRateLimitP(60 * 1000, kMessagesPerMinute, - rate_limits_.Add()); - } - - int call_count_; - Time start_time_; - Time last_call_time_; - scoped_ptr<DeterministicScheduler> scheduler_; - scoped_ptr<Logger> logger_; - RepeatedPtrField<RateLimitP> rate_limits_; - - static const int kMessagesPerSecond; - static const int kMessagesPerMinute; -}; - -const int ThrottleTest::kMessagesPerSecond = 1; -const int ThrottleTest::kMessagesPerMinute = 6; - -/* Make a throttler similar to what we expect the Ticl to use and check that it - * behaves as expected when called at a number of specific times. More - * specifically: - * - * 1. Check that the first call to Fire() triggers a call immediately. - * 2. Subsequent calls within the next one second don't trigger any calls. - * 3. After one second, one (and only one) buffered call is triggered. - * 4. If we Fire() slowly, each will trigger an immediate call until we reach - * the per-minute rate limit. - * 5. However, after a minute, another call i. - */ -TEST_F(ThrottleTest, ThrottlingScripted) { - scheduler_->StartScheduler(); - Closure* listener = - NewPermanentCallback(this, &ThrottleTest::IncrementCounter); - - scoped_ptr<Throttle> throttle( - new Throttle(rate_limits_, scheduler_.get(), listener)); - - // The first time we fire(), it should call right away. - throttle->Fire(); - scheduler_->PassTime(TimeDelta()); - ASSERT_EQ(1, call_count_); - - // However, if we now fire() a bunch more times within one second, there - // should be no more calls to the listener ... - TimeDelta short_interval = TimeDelta::FromMilliseconds(80); - int fire_count = 10; - ASSERT_TRUE(short_interval * fire_count < TimeDelta::FromSeconds(1)); - for (int i = 0; i < fire_count; ++i) { - scheduler_->PassTime(short_interval); - throttle->Fire(); - ASSERT_EQ(1, call_count_); - } - - // Time since first event is now fireCount * intervalBetweenFires, i.e., 800. - - // ... until the short throttle interval passes, at which time it should be - // called once more. - scheduler_->PassTime( - start_time_ + TimeDelta::FromSeconds(1) - scheduler_->GetCurrentTime()); - - ASSERT_EQ(2, call_count_); - - // However, the prior fire() calls don't get queued up, so no more calls to - // the listener will occur unless we fire() again. - scheduler_->PassTime(TimeDelta::FromSeconds(2)); - ASSERT_EQ(2, call_count_); - - // At this point, we've fired twice within a few seconds. We can fire - // (kMessagesPerMinute - 2) more times within a minute until we get - // throttled. - TimeDelta long_interval = TimeDelta::FromSeconds(3); - for (int i = 0; i < kMessagesPerMinute - 2; ++i) { - throttle->Fire(); - ASSERT_EQ(3 + i, call_count_); - scheduler_->PassTime(long_interval); - ASSERT_EQ(3 + i, call_count_); - } - - // Now we've sent kMessagesPerMinute times. If we fire again, nothing should - // happen. - throttle->Fire(); - scheduler_->PassTime(TimeDelta()); - ASSERT_EQ(kMessagesPerMinute, call_count_); - - // Now if we fire slowly, we still shouldn't make calls, since we'd violate - // the larger rate limit interval. - int fire_attempts = - ((start_time_ + TimeDelta::FromMinutes(1) - scheduler_->GetCurrentTime()) - / long_interval) - 1; - // This value should be 20. - for (int i = 0; i < fire_attempts; ++i) { - scheduler_->PassTime(long_interval); - throttle->Fire(); - ASSERT_EQ(kMessagesPerMinute, call_count_); - } - - Time time_to_send_again = start_time_ + TimeDelta::FromMinutes(1); - scheduler_->PassTime(time_to_send_again - scheduler_->GetCurrentTime()); - - ASSERT_EQ(kMessagesPerMinute + 1, call_count_); -} - -/* Test that if we keep calling fire() every millisecond, we never violate the - * rate limits, and the expected number of total events is allowed through. - */ -TEST_F(ThrottleTest, ThrottlingStorm) { - scheduler_->StartScheduler(); - Closure* listener = - NewPermanentCallback(this, &ThrottleTest::IncrementAndCheckRateLimits); - - // Throttler allowing one call per second and six per minute. - scoped_ptr<Throttle> throttle( - new Throttle(rate_limits_, scheduler_.get(), listener)); - - // For five minutes, call Fire() every ten milliseconds, and make sure the - // rate limits are respected. - TimeDelta fine_interval = TimeDelta::FromMilliseconds(10); - int duration_minutes = 5; - TimeDelta duration = TimeDelta::FromMinutes(duration_minutes); - int num_iterations = duration / fine_interval; - for (int i = 0; i < num_iterations; ++i) { - throttle->Fire(); - scheduler_->PassTime(fine_interval); - } - - // Expect kMessagesPerMinute to be sent per minute for duration_minutes, plus - // one extra because we end on the precise boundary at which the next message - // is allowed to be sent. - ASSERT_EQ((kMessagesPerMinute * duration_minutes) + 1, call_count_); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/ticl-message-validator.cc b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/ticl-message-validator.cc deleted file mode 100644 index 9a602cb8690bdd05de7a96579dba8bdf2a8fb802..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/ticl-message-validator.cc +++ /dev/null @@ -1,369 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Validator for v2 protocol messages. - -#include "google/cacheinvalidation/impl/ticl-message-validator.h" - -#include "google/cacheinvalidation/impl/log-macro.h" -#include "google/cacheinvalidation/impl/proto-helpers.h" -#include "google/cacheinvalidation/include/system-resources.h" - -namespace invalidation { - -// High-level design: validation works via the collaboration of a set of macros -// and template method specializations that obey a specific protocol. A -// validator for a particular type is defined by a specialization of the method: -// -// template<typename T> -// void TiclMessageValidator::Validate(const T& message, bool* result); -// -// A macro, DEFINE_VALIDATOR(type) is defined below to help prevent mistakes in -// these definitions and to improve code readability. For example, to define -// the validator for the type ObjectIdP, we'd write: -// -// DEFINE_VALIDATOR(ObjectIdP) { /* validation constraints ... */ } -// -// The choice of the names |message| and |result| is significant, as many of the -// macros assume that these refer respectively to the message being validated -// and the address in which the validation result is to be stored. -// -// When a validator is called, |*result| is initially |true|. To reject the -// message, the validator sets |*result| to |false| and returns. Otherwise, it -// simply allows control flow to continue; if no reason is found to reject the -// message, control eventually returns to the caller with |*result| still set to -// |true|, indicating that the message is acceptable. This protocol keeps the -// bodies of the validation methods clean--otherwise they would all need need to -// end with explicit |return| statements. -// -// A validator typically consists of a collection of constraints, at least one -// per field in the message. Several macros are defined for common constraints, -// including: -// -// REQUIRE(field): requires that (optional) |field| be present and valid. -// ALLOW(field): allows (optional) |field| if valid. -// ZERO_OR_MORE(field): validates each element of the (repeated) |field|. -// ONE_OR_MORE(field): like ZERO_OR_MORE, but requires at least one element. -// NON_EMPTY(field): checks that the string |field| is non-empty (if present). -// NON_NEGATIVE(field): checks that the integral |field| is >= 0 (if present). -// -// For custom constraints, the CONDITION(expr) macro allows an arbitrary boolean -// expression, which will generally refer to |message|. -// -// Note that REQUIRE, ALLOW, ZERO_OR_MORE, and ONE_OR_MORE all perform recursive -// validation of the mentioned fields. A validation method must therefore be -// defined for the type of the field, or there will be a link-time error. - - -// Macros: - -// Macro to define a specialization of the |Validate| method for the given -// |type|. This must be followed by a method body in curly braces defining -// constraints on |message|, which is bound to a value of the given type. If -// |message| is valid, no action is necessary; if invalid, a diagnostic message -// should be logged via |logger_|, and |*result| should be set to false. -#define DEFINE_VALIDATOR(type) \ - template<> \ - void TiclMessageValidator::Validate(const type& message, bool* result) - -// Expands into a conditional that checks whether |field| is present in -// |message| and valid. -#define REQUIRE(field) \ - if (!message.has_##field()) { \ - TLOG(logger_, SEVERE, "required field " #field " missing from %s", \ - ProtoHelpers::ToString(message).c_str()); \ - *result = false; \ - return; \ - } \ - ALLOW(field); - -// Expands into a conditional that checks whether |field| is present in -// |message|. If so, validates |message.field()|; otherwise, does nothing. -#define ALLOW(field) \ - if (message.has_##field()) { \ - Validate(message.field(), result); \ - if (!*result) { \ - TLOG(logger_, SEVERE, "field " #field " failed validation in %s", \ - ProtoHelpers::ToString(message).c_str()); \ - return; \ - } \ - } - -// Expands into a conditional that checks that, if |field| is present in -// |message|, then it is greater than or equal to |value|. -#define GREATER_OR_EQUAL(field, value) \ - if (message.has_##field() && (message.field() < value)) { \ - TLOG(logger_, SEVERE, \ - #field " must be greater than or equal to %d; was %d", \ - value, message.field()); \ - *result = false; \ - return; \ - } - -// Expands into a conditional that checks that, if the specified numeric |field| -// is present, that it is non-negative. -#define NON_NEGATIVE(field) GREATER_OR_EQUAL(field, 0) - -// Expands into a conditional that checks that, if the specified string |field| -// is present, that it is non-empty. -#define NON_EMPTY(field) \ - if (message.has_##field() && message.field().empty()) { \ - TLOG(logger_, SEVERE, #field " must be non-empty"); \ - *result = false; \ - return; \ - } - -// Expands into a loop that checks that all elements of the repeated |field| are -// valid. -#define ZERO_OR_MORE(field) \ - for (int i = 0; i < message.field##_size(); ++i) { \ - Validate(message.field(i), result); \ - if (!*result) { \ - TLOG(logger_, SEVERE, "field " #field " #%d failed validation in %s", \ - i, ProtoHelpers::ToString(message).c_str()); \ - *result = false; \ - return; \ - } \ - } - -// Expands into a loop that checks that there is at least one element of the -// repeated |field|, and that all are valid. -#define ONE_OR_MORE(field) \ - if (message.field##_size() == 0) { \ - TLOG(logger_, SEVERE, "at least one " #field " required in %s", \ - ProtoHelpers::ToString(message).c_str()); \ - *result = false; \ - return; \ - } \ - ZERO_OR_MORE(field) - -// Expands into code that checks that the arbitrary condition |expr| is true. -#define CONDITION(expr) \ - *result = expr; \ - if (!*result) { \ - TLOG(logger_, SEVERE, #expr " not satisfied by %s", \ - ProtoHelpers::ToString(message).c_str()); \ - return; \ - } - - -// Validators: - -// No constraints on primitive types by default. -DEFINE_VALIDATOR(bool) {} -DEFINE_VALIDATOR(int) {} -DEFINE_VALIDATOR(int64) {} -DEFINE_VALIDATOR(string) {} - -// Similarly, for now enum values are always considered valid. -DEFINE_VALIDATOR(ErrorMessage::Code) {} -DEFINE_VALIDATOR(InfoRequestMessage::InfoType) {} -DEFINE_VALIDATOR(InitializeMessage::DigestSerializationType) {} -DEFINE_VALIDATOR(RegistrationP::OpType) {} -DEFINE_VALIDATOR(StatusP::Code) {} - -DEFINE_VALIDATOR(Version) { - REQUIRE(major_version); - NON_NEGATIVE(major_version); - REQUIRE(minor_version); - NON_NEGATIVE(minor_version); -} - -DEFINE_VALIDATOR(ProtocolVersion) { - REQUIRE(version); -} - -DEFINE_VALIDATOR(ObjectIdP) { - REQUIRE(name); - REQUIRE(source); - NON_NEGATIVE(source); -} - -DEFINE_VALIDATOR(InvalidationP) { - REQUIRE(object_id); - REQUIRE(is_known_version); - REQUIRE(version); - NON_NEGATIVE(version); - ALLOW(payload); -} - -DEFINE_VALIDATOR(RegistrationP) { - REQUIRE(object_id); - REQUIRE(op_type); -} - -DEFINE_VALIDATOR(RegistrationSummary) { - REQUIRE(num_registrations); - NON_NEGATIVE(num_registrations); - REQUIRE(registration_digest); - NON_EMPTY(registration_digest); -} - -DEFINE_VALIDATOR(InvalidationMessage) { - ONE_OR_MORE(invalidation); -} - -DEFINE_VALIDATOR(ClientHeader) { - REQUIRE(protocol_version); - ALLOW(client_token); - NON_EMPTY(client_token); - ALLOW(registration_summary); - REQUIRE(client_time_ms); - REQUIRE(max_known_server_time_ms); - ALLOW(message_id); - ALLOW(client_type); -} - -DEFINE_VALIDATOR(ApplicationClientIdP) { - REQUIRE(client_type); - REQUIRE(client_name); - NON_EMPTY(client_name); -} - -DEFINE_VALIDATOR(InitializeMessage) { - REQUIRE(client_type); - REQUIRE(nonce); - NON_EMPTY(nonce); - REQUIRE(digest_serialization_type); - REQUIRE(application_client_id); -} - -DEFINE_VALIDATOR(RegistrationMessage) { - ONE_OR_MORE(registration); -} - -DEFINE_VALIDATOR(ClientVersion) { - REQUIRE(version); - REQUIRE(platform); - REQUIRE(language); - REQUIRE(application_info); -} - -DEFINE_VALIDATOR(PropertyRecord) { - REQUIRE(name); - REQUIRE(value); -} - -DEFINE_VALIDATOR(RateLimitP) { - REQUIRE(window_ms); - GREATER_OR_EQUAL(window_ms, 1000); - CONDITION(message.window_ms() > message.count()); - REQUIRE(count); -} - -DEFINE_VALIDATOR(ProtocolHandlerConfigP) { - ALLOW(batching_delay_ms); - ZERO_OR_MORE(rate_limit); -} - -DEFINE_VALIDATOR(ClientConfigP) { - REQUIRE(version); - ALLOW(network_timeout_delay_ms); - ALLOW(write_retry_delay_ms); - ALLOW(heartbeat_interval_ms); - ALLOW(perf_counter_delay_ms); - ALLOW(max_exponential_backoff_factor); - ALLOW(smear_percent); - ALLOW(is_transient); - ALLOW(initial_persistent_heartbeat_delay_ms); - ALLOW(channel_supports_offline_delivery); - REQUIRE(protocol_handler_config); - ALLOW(offline_heartbeat_threshold_ms); - ALLOW(allow_suppression); -} - -DEFINE_VALIDATOR(InfoMessage) { - REQUIRE(client_version); - ZERO_OR_MORE(config_parameter); - ZERO_OR_MORE(performance_counter); - ALLOW(client_config); - ALLOW(server_registration_summary_requested); -} - -DEFINE_VALIDATOR(RegistrationSubtree) { - ZERO_OR_MORE(registered_object); -} - -DEFINE_VALIDATOR(RegistrationSyncMessage) { - ONE_OR_MORE(subtree); -} - -DEFINE_VALIDATOR(ClientToServerMessage) { - REQUIRE(header); - ALLOW(info_message); - ALLOW(initialize_message); - ALLOW(invalidation_ack_message); - ALLOW(registration_message); - ALLOW(registration_sync_message); - CONDITION(message.has_initialize_message() ^ - message.header().has_client_token()); -} - -DEFINE_VALIDATOR(ServerHeader) { - REQUIRE(protocol_version); - REQUIRE(client_token); - NON_EMPTY(client_token); - ALLOW(registration_summary); - REQUIRE(server_time_ms); - NON_NEGATIVE(server_time_ms); - ALLOW(message_id); - NON_EMPTY(message_id); -} - -DEFINE_VALIDATOR(StatusP) { - REQUIRE(code); - ALLOW(description); -} - -DEFINE_VALIDATOR(TokenControlMessage) { - ALLOW(new_token); -} - -DEFINE_VALIDATOR(ErrorMessage) { - REQUIRE(code); - REQUIRE(description); -} - -DEFINE_VALIDATOR(RegistrationStatus) { - REQUIRE(registration); - REQUIRE(status); -} - -DEFINE_VALIDATOR(RegistrationStatusMessage) { - ONE_OR_MORE(registration_status); -} - -DEFINE_VALIDATOR(RegistrationSyncRequestMessage) {} - -DEFINE_VALIDATOR(InfoRequestMessage) { - ONE_OR_MORE(info_type); -} - -DEFINE_VALIDATOR(ConfigChangeMessage) { - ALLOW(next_message_delay_ms); - GREATER_OR_EQUAL(next_message_delay_ms, 1); -} - -DEFINE_VALIDATOR(ServerToClientMessage) { - REQUIRE(header); - ALLOW(token_control_message); - ALLOW(invalidation_message); - ALLOW(registration_status_message); - ALLOW(registration_sync_request_message); - ALLOW(config_change_message); - ALLOW(info_request_message); - ALLOW(error_message); -} - -} // namespace invalidation diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/ticl-message-validator.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/ticl-message-validator.h deleted file mode 100644 index ce0afcbc6fda1a10321e813a93f69768f2f939dd..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/impl/ticl-message-validator.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Validator for v2 protocol messages. - -#ifndef GOOGLE_CACHEINVALIDATION_IMPL_TICL_MESSAGE_VALIDATOR_H_ -#define GOOGLE_CACHEINVALIDATION_IMPL_TICL_MESSAGE_VALIDATOR_H_ - -#include "google/cacheinvalidation/impl/client-protocol-namespace-fix.h" - -namespace invalidation { - -class Logger; - -class TiclMessageValidator { - public: - TiclMessageValidator(Logger* logger) : logger_(logger) {} - - // Generic IsValid() method. Delegates to the private |Validate| helper - // method. - template<typename T> - bool IsValid(const T& message) { - bool result = true; - Validate(message, &result); - return result; - } - - private: - // Validates a message. For each type of message to be validated, there - // should be a specialization of this method. Instead of returning a boolean, - // the method stores |false| in |*result| if the message is invalid. Thus, - // the caller must initialize |*result| to |true|. Following this pattern - // allows the specific validation methods to be simpler (i.e., a method that - // accepts all messages has an empty body instead of having to return |true|). - template<typename T> - void Validate(const T& message, bool* result); - - private: - Logger* logger_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_IMPL_TICL_MESSAGE_VALIDATOR_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-client-factory.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-client-factory.h deleted file mode 100644 index 4b92495c1cd7eee23f96afd112d6a64920a77e9c..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-client-factory.h +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// -// Factory for the invalidation client library. - -#ifndef GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_CLIENT_FACTORY_H_ -#define GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_CLIENT_FACTORY_H_ - -#include <string> - -#include "google/cacheinvalidation/include/types.h" -#include "google/cacheinvalidation/include/invalidation-listener.h" -#include "google/cacheinvalidation/include/system-resources.h" -#include "google/cacheinvalidation/deps/stl-namespace.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::string; - -/* Application-provided configuration for an invalidation client. */ -class InvalidationClientConfig { - public: - /* Constructs an InvalidationClientConfig instance. - * - * Arguments: - * client_type Client type code as assigned by the notification system's - * backend. - * client_name Id/name of the client in the application's own naming - * scheme. - * application_name Name of the application using the library (for - * debugging/monitoring) - * allow_suppression If false, invalidateUnknownVersion() is called - * whenever suppression occurs. - */ - InvalidationClientConfig(int client_type, - const string& client_name, - const string& application_name, - bool allow_suppression) : - client_type_(client_type), client_name_(client_name), - application_name_(application_name), - allow_suppression_(allow_suppression) { - } - - int32 client_type() const { - return client_type_; - } - - const string& client_name() const { - return client_name_; - } - - const string& application_name() const { - return application_name_; - } - - bool allow_suppression() const { - return allow_suppression_; - } - - private: - const int32 client_type_; - const string client_name_; - const string application_name_; - const bool allow_suppression_; -}; - -// A class for new factory methods. These methods will be static, so this class -// is essentially just a namespace. This is more consistent with how the -// factory works in other languages, and it avoids overload issues with the old -// methods defined below. -class ClientFactory { - public: - /* Constructs an invalidation client library instance with a default - * configuration. Caller owns returned space. - * - * Arguments: - * resources SystemResources to use for logging, scheduling, persistence, - * and network connectivity - * config configuration provided by the application - * listener callback object for invalidation events - */ - static InvalidationClient* Create( - SystemResources* resources, - const InvalidationClientConfig& config, - InvalidationListener* listener); - - /* Constructs an invalidation client library instance with a configuration - * initialized for testing. Caller owns returned space. - * - * Arguments: - * resources SystemResources to use for logging, scheduling, persistence, - * and network connectivity - * client_type client type code as assigned by the notification system's - * backend - * client_name id/name of the client in the application's own naming scheme - * application_name name of the application using the library (for - * debugging/monitoring) - * listener callback object for invalidation events - */ - static InvalidationClient* CreateForTest( - SystemResources* resources, - const InvalidationClientConfig& config, - InvalidationListener* listener); -}; - -/* Constructs an invalidation client library instance with a default - * configuration. Deprecated, please use the version which takes an - * InvalidationClientConfig. Caller owns returned space. - * - * Arguments: - * resources SystemResources to use for logging, scheduling, persistence, - * and network connectivity - * client_type client type code as assigned by the notification system's - * backend - * client_name id/name of the client in the application's own naming scheme - * application_name name of the application using the library (for - * debugging/monitoring) - * listener callback object for invalidation events - */ -InvalidationClient* CreateInvalidationClient( - SystemResources* resources, - int client_type, - const string& client_name, - const string& application_name, - InvalidationListener* listener); - -/* Constructs an invalidation client library instance with a configuration - * initialized for testing. Deprecated, please use the version which takes an - * InvalidationClientConfig. Caller owns returned space. - * - * Arguments: - * resources SystemResources to use for logging, scheduling, persistence, - * and network connectivity - * client_type client type code as assigned by the notification system's - * backend - * client_name id/name of the client in the application's own naming scheme - * application_name name of the application using the library (for - * debugging/monitoring) - * listener callback object for invalidation events - */ -InvalidationClient* CreateInvalidationClientForTest( - SystemResources* resources, - int client_type, - const string& client_name, - const string& application_name, - InvalidationListener* listener); - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_CLIENT_FACTORY_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-client.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-client.h deleted file mode 100644 index ec4d955088bb75b5f0faa508f9ba1b544d7ed21c..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-client.h +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Interface for the invalidation client library. - -#ifndef GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_CLIENT_H_ -#define GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_CLIENT_H_ - -#include <vector> - -#include "google/cacheinvalidation/deps/stl-namespace.h" - -namespace invalidation { - -using ::INVALIDATION_STL_NAMESPACE::vector; - -class AckHandle; -class Invalidation; -class ObjectId; - -class InvalidationClient { - public: - virtual ~InvalidationClient() {} - - /* Starts the client. This method must be called before any other method is - * invoked. The client is considered to be started after - * InvalidationListener::Ready has received by the application. - * - * REQUIRES: Start has not already been called. - * The resources given to the client must have been started by the caller. - */ - virtual void Start() = 0; - - /* Stops the client. After this method has been called, it is an error to call - * any other method. - * - * REQUIRES: Start has already been called. - * Does not stop the resources bound to this client. - */ - virtual void Stop() = 0; - - /* Requests that the Ticl register to receive notifications for the object - * with id object_id. The library guarantees that the caller will be informed - * of the results of this call either via - * InvalidationListener::InformRegistrationStatus or - * InvalidationListener::InformRegistrationFailure unless the library informs - * the caller of a connection failure via - * InvalidationListener::InformError. The caller should consider the - * registration to have succeeded only if it gets a call - * InvalidationListener::InformRegistrationStatus for object_id with - * InvalidationListener::RegistrationState::REGISTERED. Note that if the - * network is disconnected, the listener events will probably show up when the - * network connection is repaired. - * - * REQUIRES: Start has been called and and InvalidationListener::Ready has - * been received by the application's listener. - */ - virtual void Register(const ObjectId& object_id) = 0; - - /* Registrations for multiple objects. See the specs on Register(const - * ObjectId&) for more details. If the caller needs to register for a number - * of object ids, this method is more efficient than calling Register in a - * loop. - */ - virtual void Register(const vector<ObjectId>& object_ids) = 0; - - /* Requests that the Ticl unregister for notifications for the object with id - * object_id. The library guarantees that the caller will be informed of the - * results of this call either via - * InvalidationListener::InformRegistrationStatus or - * InvalidationListener::InformRegistrationFailure unless the library informs - * the caller of a connection failure via - * InvalidationListener::InformError. The caller should consider the - * unregistration to have succeeded only if it gets a call - * InvalidationListener::InformRegistrationStatus for object_id with - * InvalidationListener::RegistrationState::UNREGISTERED. Note that if the - * network is disconnected, the listener events will probably show up when the - * network connection is repaired. - * - * REQUIRES: Start has been called and and InvalidationListener::Ready has - * been receiveed by the application's listener. - */ - virtual void Unregister(const ObjectId& object_id) = 0; - - /* Unregistrations for multiple objects. See the specs on Unregister(const - * ObjectId&) for more details. If the caller needs to unregister for a number - * of object ids, this method is more efficient than calling Unregister in a - * loop. - */ - virtual void Unregister(const vector<ObjectId>& object_ids) = 0; - - /* Acknowledges the InvalidationListener event that was delivered with the - * provided acknowledgement handle. This indicates that the client has - * accepted responsibility for processing the event and it does not need to be - * redelivered later. - * - * REQUIRES: Start been called and and InvalidationListener::Ready has been - * received by the application's listener. - */ - virtual void Acknowledge(const AckHandle& ackHandle) = 0; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_CLIENT_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-listener.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-listener.h deleted file mode 100644 index aa881e41d63d7729e576be911b55c7efd76f13c3..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/invalidation-listener.h +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Interface through which invalidation-related events are delivered by the -// library to the application. Each event must be acknowledged by the -// application. Each includes an AckHandle that the application must use to call -// InvalidationClient::Acknowledge after it is done handling that event. - -#ifndef GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_LISTENER_H_ -#define GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_LISTENER_H_ - -#include <string> - -#include "google/cacheinvalidation/deps/stl-namespace.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::string; - -class AckHandle; -class ErrorInfo; -class Invalidation; -class InvalidationClient; -class ObjectId; - -class InvalidationListener { - public: - /* Possible registration states for an object. */ - enum RegistrationState { - REGISTERED, - UNREGISTERED - }; - - virtual ~InvalidationListener() {} - - /* Called in response to the InvalidationClient::Start call. Indicates that - * the InvalidationClient is now ready for use, i.e., calls such as - * register/unregister can be performed on that object. - * - * Arguments: - * client - the InvalidationClient invoking the listener - */ - virtual void Ready(InvalidationClient* client) = 0; - - /* Indicates that an object has been updated to a particular version. - * - * The Ticl guarantees that this callback will be invoked at least once for - * every invalidation that it guaranteed to deliver. It does not guarantee - * exactly-once delivery or in-order delivery (with respect to the version - * number). - * - * The application should acknowledge this event by calling - * InvalidationClient::Acknowledge(const AckHandle&) with the provided - * ack_handle otherwise the event may be redelivered. - * - * Arguments: - * client - the InvalidationClient invoking the listener - * ack_handle - event acknowledgement handle - */ - virtual void Invalidate(InvalidationClient* client, - const Invalidation& invalidation, - const AckHandle& ack_handle) = 0; - - /* As Invalidate, but for an unknown application store version. The object may - * or may not have been updated - to ensure that the application does not miss - * an update from its backend, the application must check and/or fetch the - * latest version from its store. - */ - virtual void InvalidateUnknownVersion(InvalidationClient* client, - const ObjectId& object_id, - const AckHandle& ack_handle) = 0; - - /* Indicates that the application should consider all objects to have changed. - * This event is generally sent when the client has been disconnected from the - * network for too long a period and has been unable to resynchronize with the - * update stream, but it may be invoked arbitrarily (although the service - * tries hard not to invoke it under normal circumstances). - * - * The application should acknowledge this event by calling - * InvalidationClient::Acknowledge(const AckHandle&) with the provided - * ack_handle otherwise the event may be redelivered. - * - * Arguments: - * client - the InvalidationClient invoking the listener - * ack_handle - event acknowledgement handle - */ - virtual void InvalidateAll(InvalidationClient* client, - const AckHandle& ack_handle) = 0; - - /* Indicates that the registration state of an object has changed. - * - * The application should acknowledge this event by calling - * InvalidationClient::Acknowledge(AckHandle) with the provided ack_handle; - * otherwise the event may be redelivered. - * - * Arguments: - * client - the InvalidationClient invoking the listener - * object_id - the id of the object whose state changed - * reg_state - the new state - */ - virtual void InformRegistrationStatus(InvalidationClient* client, - const ObjectId& object_id, - RegistrationState reg_state) = 0; - - /* Indicates that an object registration or unregistration operation may have - * failed. - * - * The application should acknowledge this event by calling - * InvalidationClient::acknowledge(AckHandle) with the provided ack_handle; - * otherwise the event may be redelivered. - * - * For transient failures, the application can retry the registration later - - * if it chooses to do so, it must use a sensible backoff policy such as - * exponential backoff. For permanent failures, it must not automatically - * retry without fixing the situation (e.g., by presenting a dialog box to the - * user). - * - * Arguments: - * client - the {@link InvalidationClient} invoking the listener - * object_id - the id of the object whose state changed - * is_transient - whether the error is transient or permanent - * errorMessage - extra information about the message - */ - virtual void InformRegistrationFailure(InvalidationClient* client, - const ObjectId& object_id, - bool is_transient, - const string& error_message) = 0; - - /* Indicates that the all registrations for the client are in an unknown state - * (e.g., they could have been removed). The application MUST inform the - * InvalidationClient of its registrations once it receives this event. The - * requested objects are those for which the digest of their serialized object - * ids matches a particular prefix bit-pattern. The digest for an object id is - * computed as following (the digest chosen for this method is SHA-1): - * - * Digest digest(); - * digest.Update(Little endian encoding of object source type) - * digest.Update(object name) - * digest.GetDigestSummary() - * - * For a set of objects, digest is computed by sorting lexicographically based - * on their digests and then performing the update process given above (i.e., - * calling digest.update on each object's digest and then calling - * getDigestSummary at the end). - * - * IMPORTANT: A client can always register for more objects than what is - * requested here. For example, in response to this call, the client can - * ignore the prefix parameters and register for all its objects. - * - * The application should acknowledge this event by calling - * InvalidationClient::Acknowledge(const AckHandle&) with the provided - * ack_handle otherwise the event may be redelivered. The acknowledge using - * ack_handle must be called after all the InvalidationClient::Register calls - * have been made. - * - * Arguments: - * client - the InvalidationClient invoking the listener - * prefix - prefix of the object ids as described above. - * prefix_length - number of bits in prefix to consider. - */ - virtual void ReissueRegistrations(InvalidationClient* client, - const string& prefix, - int prefix_length) = 0; - - /* Informs the listener about errors that have occurred in the backend, e.g., - * authentication, authorization problems. - * - * The application should acknowledge this event by calling - * InvalidationClient::Acknowledge(const AckHandle&) with the provided - * ack_handle otherwise the event may be redelivered. - * - * Arguments: - * client - the InvalidationClient invoking the listener - * error_info - information about the error - */ - virtual void InformError(InvalidationClient* client, - const ErrorInfo& error_info) = 0; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_INCLUDE_INVALIDATION_LISTENER_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/system-resources.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/system-resources.h deleted file mode 100644 index 979140c3ed2d7375159611eaa56f24e936847b11..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/system-resources.h +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Interfaces for the system resources used by the Ticl. System resources are an -// abstraction layer over the host operating system that provides the Ticl with -// the ability to schedule events, send network messages, store data, and -// perform logging. -// -// NOTE: All the resource types and SystemResources are required to be -// thread-safe. - -#ifndef GOOGLE_CACHEINVALIDATION_INCLUDE_SYSTEM_RESOURCES_H_ -#define GOOGLE_CACHEINVALIDATION_INCLUDE_SYSTEM_RESOURCES_H_ - -#include <string> -#include <utility> - -#include "google/cacheinvalidation/deps/callback.h" -#include "google/cacheinvalidation/deps/stl-namespace.h" -#include "google/cacheinvalidation/deps/time.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::pair; -using INVALIDATION_STL_NAMESPACE::string; - -class Status; -class SystemResources; // Declared below. - -typedef pair<Status, string> StatusStringPair; -typedef INVALIDATION_CALLBACK1_TYPE(string) MessageCallback; -typedef INVALIDATION_CALLBACK1_TYPE(bool) NetworkStatusCallback; -typedef INVALIDATION_CALLBACK1_TYPE(StatusStringPair) ReadKeyCallback; -typedef INVALIDATION_CALLBACK1_TYPE(Status) WriteKeyCallback; -typedef INVALIDATION_CALLBACK1_TYPE(bool) DeleteKeyCallback; -typedef INVALIDATION_CALLBACK1_TYPE(StatusStringPair) ReadAllKeysCallback; - -/* Interface for a component of a SystemResources implementation constructed by - * calls to set* methods of SystemResourcesBuilder. - * - * The SystemResourcesBuilder allows applications to create a single - * SystemResources implementation by composing individual building blocks, each - * of which implements one of the four required interfaces (Logger, Storage, - * NetworkChannel, Scheduler). - * - * However, each interface implementation may require functionality from - * another. For example, the network implementation may need to do logging. In - * order to allow this, we require that the interface implementations also - * implement ResourceComponent, which specifies the single method - * SetSystemResources. It is guaranteed that this method will be invoked exactly - * once on each interface implementation and before any other calls are - * made. Implementations can then save a reference to the provided resources for - * later use. - * - * Note: for the obvious reasons of infinite recursion, implementations should - * not attempt to access themselves through the provided SystemResources. - */ -class ResourceComponent { - public: - virtual ~ResourceComponent() {} - - /* Supplies a |SystemResources| instance to the component. */ - virtual void SetSystemResources(SystemResources* resources) = 0; -}; - -/* Interface specifying the logging functionality provided by - * SystemResources. - */ -class Logger : public ResourceComponent { - public: - enum LogLevel { - FINE_LEVEL, - INFO_LEVEL, - WARNING_LEVEL, - SEVERE_LEVEL - }; - - virtual ~Logger() {} - - /* Logs a message. - * - * Arguments: - * level - the level at which the message should be logged (e.g., INFO) - * file - the file from which the message is being logged - * line - the line number from which the message is being logged - * template - the string to log, optionally containing %s sequences - * ... - values to substitute for %s sequences in template - */ - virtual void Log(LogLevel level, const char* file, int line, - const char* format, ...) = 0; -}; - -/* Interface specifying the scheduling functionality provided by - * SystemResources. - */ -class Scheduler : public ResourceComponent { - public: - virtual ~Scheduler() {} - - /* Function returning a zero time delta, for readability. */ - static TimeDelta NoDelay() { - return TimeDelta::FromMilliseconds(0); - } - - /* Schedules runnable to be run on scheduler's thread after at least - * delay. - * Callee owns the runnable and must delete it after the task has run - * (or if the scheduler is shut down before the task has run). - */ - virtual void Schedule(TimeDelta delay, Closure* runnable) = 0; - - /* Returns whether the current code is executing on the scheduler's thread. - */ - virtual bool IsRunningOnThread() const = 0; - - /* Returns the current time in milliseconds since *some* epoch (NOT - * necessarily the UNIX epoch). The only requirement is that this time - * advance at the rate of real time. - */ - virtual Time GetCurrentTime() const = 0; -}; - -/* Interface specifying the network functionality provided by - * SystemResources. - */ -class NetworkChannel : public ResourceComponent { - public: - virtual ~NetworkChannel() {} - - /* Sends outgoing_message to the data center. */ - // Implementation note: this is currently a serialized ClientToServerMessage - // protocol buffer. Implementors MAY NOT rely on this fact. - virtual void SendMessage(const string& outgoing_message) = 0; - - /* Sets the receiver to which messages from the data center will be delivered. - * Ownership of |incoming_receiver| is transferred to the network channel. - */ - // Implementation note: this is currently a serialized ServerToClientMessage - // protocol buffer. Implementors MAY NOT rely on this fact. - virtual void SetMessageReceiver(MessageCallback* incoming_receiver) = 0; - - /* Informs the network channel that network_status_receiver be informed about - * changes to network status changes. If the network is connected, the channel - * should call network_Status_Receiver->Run(true) and when the network is - * disconnected, it should call network_status_receiver->Run(false). Note that - * multiple receivers can be registered with the channel to receive such - * status updates. - * - * The informing of the status to the network_status_receiver can be - * implemented in a best-effort manner with the caveat that indicating - * incorrectly that the network is connected can result in unnecessary calls - * for SendMessage. Incorrect information that the network is disconnected can - * result in messages not being sent by the client library. - * - * Ownership of network_status_receiver is transferred to the network channel. - */ - virtual void AddNetworkStatusReceiver( - NetworkStatusCallback* network_status_receiver) = 0; -}; - -/* Interface specifying the storage functionality provided by - * SystemResources. Basically, the required functionality is a small subset of - * the method of a regular hash map. - */ -class Storage : public ResourceComponent { - public: - virtual ~Storage() {} - - /* Attempts to persist value for the given key. Invokes done when finished, - * passing a value that indicates whether it was successful. - * - * Note: If a wrie W1 finishes unsuccessfully and then W2 is issued for the - * same key and W2 finishes successfully, W1 must NOT later overwrite W2. - * Callee owns |done| after this call. After it calls |done->Run()|, it must - * delete |done|. - * - * REQUIRES: Neither key nor value is null. - */ - virtual void WriteKey(const string& key, const string& value, - WriteKeyCallback* done) = 0; - - /* Reads the value corresponding to key and calls done with the result. If it - * finds the key, passes a success status and the value. Else passes a failure - * status and a null value. - * Callee owns |done| after this call. After it calls |done->Run()|, it must - * delete |done|. - */ - virtual void ReadKey(const string& key, ReadKeyCallback* done) = 0; - - /* Deletes the key, value pair corresponding to key. If the deletion succeeds, - * calls done with true; else calls it with false. - * Callee owns |done| after this call. After it calls |done->Run()|, it must - * delete |done|. - */ - virtual void DeleteKey(const string& key, DeleteKeyCallback* done) = 0; - - /* Reads all the keys from the underlying store and then calls key_callback - * with each key that was written earlier and not deleted. When all the keys - * are done, calls key_callback with null. With each key, the code can - * indicate a failed status, in which case the iteration stops. - * Caller continues to own |key_callback|. - */ - virtual void ReadAllKeys(ReadAllKeysCallback* key_callback) = 0; -}; - -class SystemResources { - public: - virtual ~SystemResources() {} - - /* Starts the resources. - * - * REQUIRES: This method is called before the resources are used. - */ - virtual void Start() = 0; - - /* Stops the resources. After this point, all the resources will eventually - * stop doing any work (e.g., scheduling, sending/receiving messages from the - * network etc). They will eventually convert any further operations to - * no-ops. - * - * REQUIRES: Start has been called. - */ - virtual void Stop() = 0; - - /* Returns whether the resources are started. */ - virtual bool IsStarted() const = 0; - - /* Returns information about the client operating system/platform, e.g., - * Windows, ChromeOS (for debugging/monitoring purposes). - */ - virtual string platform() const = 0; - - /* Returns an object that can be used to do logging. */ - virtual Logger* logger() = 0; - - /* Returns an object that can be used to persist data locally. */ - virtual Storage* storage() = 0; - - /* Returns an object that can be used to send and receive messages. */ - virtual NetworkChannel* network() = 0; - - /* Returns an object that can be used by the client library to schedule its - * internal events. - */ - virtual Scheduler* internal_scheduler() = 0; - - /* Returns an object that can be used to schedule events for the - * application. - */ - virtual Scheduler* listener_scheduler() = 0; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_INCLUDE_SYSTEM_RESOURCES_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/types.h b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/types.h deleted file mode 100644 index 4e3be27c0ba2a5226053e659e44c6efcb563b4b6..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/include/types.h +++ /dev/null @@ -1,369 +0,0 @@ -// Copyright 2012 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Types used by the invalidation client library and its applications. - -#ifndef GOOGLE_CACHEINVALIDATION_INCLUDE_TYPES_H_ -#define GOOGLE_CACHEINVALIDATION_INCLUDE_TYPES_H_ - -#include <string> - -#include "google/cacheinvalidation/deps/logging.h" -#include "google/cacheinvalidation/deps/stl-namespace.h" - -namespace invalidation { - -using INVALIDATION_STL_NAMESPACE::string; - -/* Represents an opaque handle that can be used to acknowledge an invalidation - * event by calling InvalidationClient::Acknowledge(AckHandle) to indicate that - * the client has successfully handled the event. - */ -class AckHandle { - public: - /* Creates a new ack handle from the serialized handle_data representation. */ - explicit AckHandle(const string& handle_data) : handle_data_(handle_data) {} - - const string& handle_data() const { - return handle_data_; - } - - bool operator==(const AckHandle& ack_handle) const { - return handle_data() == ack_handle.handle_data(); - } - - bool IsNoOp() const { - return handle_data_.empty(); - } - - private: - /* The serialized representation of the handle. */ - string handle_data_; -}; - -/* An identifier for application clients in an application-defined way. I.e., a - * client name in an application naming scheme. This is not interpreted by the - * invalidation system - however, it is used opaquely to squelch invalidations - * for the cient causing an update, e.g., if a client C whose app client id is - * C.appClientId changes object X and the backend store informs the backend - * invalidation sytsem that X was modified by X.appClientId, the invalidation to - * C can then be squelched by the invalidation system. - */ -class ApplicationClientId { - public: - /* Creates an application id for the given client_Name. */ - explicit ApplicationClientId(const string& client_name) - : client_name_(client_name) {} - - const string& client_name() const { - return client_name_; - } - - bool operator==(const ApplicationClientId& app_client_id) const { - return client_name() == app_client_id.client_name(); - } - - private: - string client_name_; -}; - -/* Possible reasons for error in InvalidationListener::InformError. The - * application writer must NOT assume that this is complete list since error - * codes may be added later. That is, for error codes that it cannot handle, - * it should not necessarily just crash the code. It may want to present a - * dialog box to the user (say). For each ErrorReason, the ErrorInfo object - * has a context object. We describe the type and meaning of the context for - * each enum value below. - */ -class ErrorReason { - public: - /* The provided authentication/authorization token is not valid for use. */ - static const int AUTH_FAILURE = 1; - - /* An unknown failure - more human-readable information is in the error - * message. - */ - static const int UNKNOWN_FAILURE = -1; -}; - -/* Extra information about the error - cast to appropriate subtype as specified - * for the reason. - */ -class ErrorContext { - public: - virtual ~ErrorContext() {} -}; - -/* A context with numeric data. */ -class NumberContext : public ErrorContext { - public: - explicit NumberContext(int number) : number_(number) {} - - virtual ~NumberContext() {} - - int number() { - return number_; - } - - private: - int number_; -}; - -/* Information about an error given to the application. */ -class ErrorInfo { - public: - /* Constructs an ErrorInfo object given the reason for the error, whether it - * is transient or permanent, and a helpful message describing the error. - */ - ErrorInfo(int error_reason, bool is_transient, - const string& error_message, const ErrorContext& context) - : error_reason_(error_reason), - is_transient_(is_transient), - error_message_(error_message), - context_(context) {} - - int error_reason() const { - return error_reason_; - } - - bool is_transient() const { - return is_transient_; - } - - const string& error_message() const { - return error_message_; - } - - const ErrorContext& context() const { - return context_; - } - - private: - /* The cause of the failure. */ - int error_reason_; - - /* Is the error transient or permanent. See discussion in Status::Code for - * permanent and transient failure handling. - */ - bool is_transient_; - - /* Human-readable description of the error. */ - string error_message_; - - /* Extra information about the error - cast to appropriate object as specified - * for the reason. - */ - ErrorContext context_; -}; - -/* A class to represent a unique object id that an application can register or - * unregister for. - */ -class ObjectId { - public: - ObjectId() : is_initialized_(false) {} - - /* Creates an object id for the given source and name (the name is copied). */ - ObjectId(int source, const string& name) - : is_initialized_(true), source_(source), name_(name) {} - - void Init(int source, const string& name) { - is_initialized_ = true; - source_ = source; - name_ = name; - } - - int source() const { - CHECK(is_initialized_); - return source_; - } - - const string& name() const { - CHECK(is_initialized_); - return name_; - } - - bool operator==(const ObjectId& object_id) const { - CHECK(is_initialized_); - CHECK(object_id.is_initialized_); - return (source() == object_id.source()) && (name() == object_id.name()); - } - - private: - /* Whether the object id has been initialized. */ - bool is_initialized_; - - /* The invalidation source type. */ - int source_; - - /* The name/unique id for the object. */ - string name_; -}; - -/* A class to represent an invalidation for a given object/version and an - * optional payload. - */ -class Invalidation { - public: - Invalidation() : is_initialized_(false) {} - - /* Creates a restarted invalidation for the given object and version. */ - Invalidation(const ObjectId& object_id, int64 version) { - Init(object_id, version, true); - } - - /* Creates an invalidation for the given object, version, and payload. */ - Invalidation(const ObjectId& object_id, int64 version, - const string& payload) { - Init(object_id, version, payload, true); - } - - /* - * Creates an invalidation for the given object, version, payload, - * and restarted flag. - */ - Invalidation(const ObjectId& object_id, int64 version, const string& payload, - bool is_trickle_restart) { - Init(object_id, version, payload, is_trickle_restart); - } - - - void Init(const ObjectId& object_id, int64 version, bool is_trickle_restart) { - Init(object_id, version, false, "", is_trickle_restart); - } - - void Init(const ObjectId& object_id, int64 version, const string& payload, - bool is_trickle_restart) { - Init(object_id, version, true, payload, is_trickle_restart); - } - - const ObjectId& object_id() const { - return object_id_; - } - - int64 version() const { - return version_; - } - - bool has_payload() const { - return has_payload_; - } - - const string& payload() const { - return payload_; - } - - // This method is for internal use only. - bool is_trickle_restart_for_internal_use() const { - return is_trickle_restart_; - } - - bool operator==(const Invalidation& invalidation) const { - return (object_id() == invalidation.object_id()) && - (version() == invalidation.version()) && - (is_trickle_restart_for_internal_use() == - invalidation.is_trickle_restart_for_internal_use()) && - (has_payload() == invalidation.has_payload()) && - (payload() == invalidation.payload()); - } - - private: - void Init(const ObjectId& object_id, int64 version, bool has_payload, - const string& payload, bool is_trickle_restart) { - is_initialized_ = true; - object_id_.Init(object_id.source(), object_id.name()); - version_ = version; - has_payload_ = has_payload; - payload_ = payload; - is_trickle_restart_ = is_trickle_restart; - } - - /* Whether this invalidation has been initialized. */ - bool is_initialized_; - - /* The object being invalidated/updated. */ - ObjectId object_id_; - - /* The new version of the object. */ - int64 version_; - - /* Whether or not the invalidation includes a payload. */ - bool has_payload_; - - /* Optional payload for the client. */ - string payload_; - - /* Flag whether the trickle restarts at this invalidation. */ - bool is_trickle_restart_; -}; - -/* Information given to about a operation - success, temporary or permanent - * failure. - */ -class Status { - public: - /* Actual status of the operation: Whether successful, transient or permanent - * failure. - */ - enum Code { - /* Operation was successful. */ - SUCCESS, - - /* Operation had a transient failure. The application can retry the failed - * operation later - if it chooses to do so, it must use a sensible backoff - * policy such as exponential backoff. - */ - TRANSIENT_FAILURE, - - /* Opration has a permanent failure. Application must not automatically - * retry without fixing the situation (e.g., by presenting a dialog box to - * the user). - */ - PERMANENT_FAILURE - }; - - /* Creates a new Status object given the code and message. */ - Status(Code code, const string& message) : code_(code), message_(message) {} - - bool IsSuccess() const { - return code_ == SUCCESS; - } - - bool IsTransientFailure() const { - return code_ == TRANSIENT_FAILURE; - } - - bool IsPermanentFailure() const { - return code_ == PERMANENT_FAILURE; - } - - const string& message() const { - return message_; - } - - bool operator==(const Status& status) const { - return (code_ == status.code_) && (message() == status.message()); - } - - private: - /* Success or failure. */ - Code code_; - - /* A message describing why the state was unknown, for debugging. */ - string message_; -}; - -} // namespace invalidation - -#endif // GOOGLE_CACHEINVALIDATION_INCLUDE_TYPES_H_ diff --git a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/types.proto b/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/types.proto deleted file mode 100644 index f953b790054c59ce62abb550431dc35dee197406..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/google/cacheinvalidation/types.proto +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Enums definitions for main types in the cache invalidation system. - -syntax = "proto2"; - -option optimize_for = LITE_RUNTIME; - -package ipc.invalidation; - -// The type of client / application. -message ClientType { - enum Type { - INTERNAL = 1; - TEST = 2; // Uncontrolled client space for use by anyone for testing. - DEMO = 4; // A demo client type that can be used for testing. - - // Numbers below 1000 are reserved for internal use. - CHROME_SYNC = 1004; - CHROME_SYNC_ANDROID = 1018; - CHROME_SYNC_IOS = 1038; - CHROME_SYNC_GCM_DESKTOP = 1055; - CHROME_SYNC_GCM_IOS = 1056; - } - optional Type type = 1; -} - -// The property that hosts the object. -message ObjectSource { - // - // NOTE: This enum MUST be kept in sync with ObjectIdP.Source in - // internal.proto. - // - enum Type { - INTERNAL = 1; - TEST = 2; // Uncontrolled object space for use by anyone for testing. - DEMO = 4; // A demo object source that can be used for testing. - - // Numbers below 1000 are reserved for internal use. - CHROME_SYNC = 1004; - COSMO_CHANGELOG = 1014; - CHROME_COMPONENTS = 1025; - CHROME_PUSH_MESSAGING = 1030; - } - optional Type type = 1; -} - -// A dummy message to enclose various enum constant declarations. -message Constants { - // Constants related to object versions. - enum ObjectVersion { - // Version number used to indicate that an object's version is unknown. - UNKNOWN = 0; - } -} diff --git a/chromium/third_party/cacheinvalidation/src/java/COPYING b/chromium/third_party/cacheinvalidation/src/java/COPYING deleted file mode 100644 index d645695673349e3947e8e5ae42332d0ac3164cd7..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/java/COPYING +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/example_listener.proto b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/example_listener.proto deleted file mode 100644 index e9a01ba8f2c1908fa8dfe5e7294b6bed32274f49..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/examples/android2/example_listener.proto +++ /dev/null @@ -1,31 +0,0 @@ -syntax = "proto2"; -package ipc.invalidation.examples.android2; -option java_package = "com.google.ipc.invalidation.examples.android2"; -option java_outer_classname = "ExampleListenerProto"; -option optimize_for = LITE_RUNTIME; - -// Persistent state for the example listener. -message ExampleListenerStateProto { - - message ObjectIdProto { - optional int32 source = 1; - optional bytes name = 2; - } - - // State related to a particular object being tracked by the listener. See - // ExampleListenerState#ObjectState for information on fields. - message ObjectStateProto { - optional ObjectIdProto object_id = 1; - optional bool is_registered = 2; - optional bytes payload = 3; - optional int64 highest_version = 4; - optional int64 invalidation_time_millis = 5; - optional bool is_background = 6; - } - - // List of objects for which state is being tracked. - repeated ObjectStateProto object_state = 1; - - // (Optional) client id passed to the listener in ready() call. - optional bytes client_id = 2; -} diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationService.aidl b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationService.aidl deleted file mode 100644 index 6cc37321af7e66093198c22c1ad829f6cdb68435..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/InvalidationService.aidl +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.ipc.invalidation.external.client.android.service; - -import android.os.Bundle; - -/** - * Defines the bound service interface for the Invalidation service. The service exposes - * an intent-like model with a single {@link #handleRrequest} entry point that packages the - * action and its parameters into a {@link Bundle} but uses a synchronous calling model where - * a response bundle is also returned to the client containing status and any result or - * failure information. - * <p> - * Having a single entry point (as compared to a interface method per action with explicit - * parameters) will make it easier to evolve the interface over time. New action types or - * additional optional parameters can be added in subsequent versions without changing the - * service interface in ways that would be incompatible with existing clients. This is - * important because the service will be packaged (and updated) independently from clients - * of the invalidation service. - * <p> - * The synchronous nature of the interface (having a response object that can indicate success - * or failure of an action) is important to support reliable registrations. If a client - * sends a registration request, it's important to know that it has been successfully received - * by the local invalidation service. - * - * Before binding, the invalidation service should first ensure that the service is started by - * calling the {@code Context#startService} with the {@link ServiceParameter#SERVICE_INTENT}. - * The client can then bind to the service using {@code Context#bindService} with the same - * intent. Clients should never explicitly stop the service; the service itself will decide - * when it has successfully processed all requests from active clients and will stop itself. - */ -interface InvalidationService { - - /** - * Sends a request to the invalidation service and retrieves the response containing any - * return data or status/error information. The {@code action} parameter in the request - * bundle will indicate the type of request to be executed and the request parameters will - * also be stored in the bundle. The service will acknowledge successful processing of - * the request by returning a response bundle that contains a {@code status} parameter - * indicating the success or failure of the request. If successful, any other output - * parameters will be included as values in the response bundle. On failure, additional - * error or debug information will be included in the response bundle. - * - * @see Request - * @see Response - */ - void handleRequest(in Bundle request, out Bundle response); -} diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerService.aidl b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerService.aidl deleted file mode 100644 index fdbbb89e84e0f58bbacf624c20853c5f7b18a12f..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android/service/ListenerService.aidl +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.ipc.invalidation.external.client.android.service; - -import android.os.Bundle; - -/** - * Defines the bound service interface for an Invalidation listener service. The service - * exposes an intent-like model with a single {@link #handleEvent} entry point that packages - * the event action and its parameters into a {@link Bundle} but uses a synchronous calling - * model where a response bundle is also returned to the service containing status and/or - * <p> - * Having a single entry point (as compared to a interface method per action with explicit - * parameters) will make it easier to evolve the interface over time. New event types or - * additional optional parameters can be added in subsequent versions without changing the - * service interface in ways that would be incompatible with existing clients. This is - * important because the listener services will be packaged (and updated) independently from - * the invalidation service. - * <p> - * The synchronous nature of the interface (having a response object that can indicate success - * or failure of event handling) is important to support reliable events. If the service - * sends a registration request, it's important to know that it has been successfully received - * by the local invalidation service. - * - * The invalidation service will bind to the invalidation listener using an intent that - * contains the {@link Event.LISTENER} action along with the explicit listener class name - * that was provided to {@code AndroidClientFactory.create()}. - */ -interface ListenerService { - - /** - * Sends a request to the invalidation service and retrieves the response containing any - * return data or status/error information. The {@code action} parameter in the request - * bundle will indicate the type of request to be executed and the request parameters will - * also be stored in the bundle. The service will acknowledge successful processing of - * the request by returning a response bundle that contains a {@code status} parameter - * indicating the success or failure of the request. If successful, any other output - * parameters will be included as values in the response bundle. On failure, additional - * error or debug information will be included in the response bundle. - * - * @see Event - * @see Response - */ - void handleEvent(in Bundle event, out Bundle response); -} diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml deleted file mode 100644 index 840c41f8e8a0a13ac2efaac07055496a21568fe7..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/android2/AndroidManifest.xml +++ /dev/null @@ -1,58 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> - <!-- Copyright 2011 Google Inc. All Rights Reserved. --> - <!-- Common configuration settings for application using client invalidation library. --> -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.google.ipc.invalidation.client.android2"> - - <!-- App receives GCM messages. --> - <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> - <!-- GCM connects to Google Services. --> - <uses-permission android:name="android.permission.INTERNET" /> - <!-- GCM requires a Google account. --> - <uses-permission android:name="android.permission.GET_ACCOUNTS" /> - <uses-permission android:name="android.permission.USE_CREDENTIALS" /> - <!-- Keeps the processor from sleeping when a message is received. --> - <uses-permission android:name="android.permission.WAKE_LOCK" /> - - <application> - <!-- Ticl service. --> - <service android:exported="false" - android:name="com.google.ipc.invalidation.ticl.android2.TiclService"/> - - <!-- Ticl sender. --> - <service android:exported="false" - android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageSenderService"/> - - <!-- Receiver for scheduler alarms. --> - <receiver android:exported="false" - android:name="com.google.ipc.invalidation.ticl.android2.AndroidInternalScheduler$AlarmReceiver"/> - - <!-- GCM Broadcast Receiver --> - <receiver android:exported="true" - android:name="com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener$GCMReceiver" - android:permission="com.google.android.c2dm.permission.SEND"> - <intent-filter> - <action android:name="com.google.android.c2dm.intent.RECEIVE" /> - <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> - <category android:name="com.google.ipc.invalidation.ticl.android2" /> - </intent-filter> - </receiver> - - <!-- GCM multiplexer --> - <service android:exported="false" - android:name="com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener"> - <meta-data android:name="sender_ids" android:value="ipc.invalidation@gmail.com"/> - </service> - - <!-- Invalidation service multiplexed GCM receiver --> - <service android:exported="false" - android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageReceiverService" - android:enabled="true"/> - <receiver android:exported="false" - android:name="com.google.ipc.invalidation.ticl.android2.channel.AndroidMessageReceiverService$Receiver"> - <intent-filter> - <action android:name="com.google.ipc.invalidation.gcmmplex.EVENT" /> - </intent-filter> - </receiver> - </application> -</manifest> diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerManifest.xml b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerManifest.xml deleted file mode 100644 index 06084f6701492d1424698645b63c8c29c62b6970..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/external/client/contrib/AndroidListenerManifest.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> - <!-- Copyright 2011 Google Inc. All Rights Reserved. --> - <!-- Manifest for AndroidListener. Must be merged with - j/c/g/ipc/invalidation/external/client2/android2/AndroidManifest.xml. --> -<manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.google.ipc.invalidation.external.client2.contrib"> - <application> - <!-- Receiver for scheduler alarms. --> - <receiver android:exported="false" - android:name="com.google.ipc.invalidation.external.client2.contrib.AndroidListener$AlarmReceiver"/> - </application> -</manifest> diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTest.aidl b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTest.aidl deleted file mode 100644 index fb5ab2915a5976f79c95e8f9a3e353076650727b..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/testing/android/InvalidationTest.aidl +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.ipc.invalidation.testing.android; - -import android.os.Bundle; - -interface InvalidationTest { - - /** - * Used to set whether the invalidation test service should store incoming - * actions and outgoing events respectively by {@link getActionEvents()} - * and {@link getEventIntents()}. If {@code false}, they will be processed - * and forgotten. - */ - void setCapture(boolean captureActions, boolean captureEvents); - - /** - * Returns an array of bundle containing the set of invalidation requests - * received by the test service since the last call to this method. - */ - Bundle [] getRequests(); - - /** - * Returns an array of intents containing the set of invalidation event - * bundles sent by the test service since the last call to this method. - */ - Bundle [] getEvents(); - - /** - * Instructs the test service to send an event back to the client to support - * testing of listener functionality. - */ - void sendEvent(in Bundle eventBundle); - - /** - * Reset all state for the invalidation test service. This will clear all - * current clients and drop and disable any captured action or event bundles. - */ - void reset(); -} diff --git a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidManifest.xml b/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidManifest.xml deleted file mode 100644 index 4d665386ee78ae31b42090e83577699d8f4cf2ce..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/java/com/google/ipc/invalidation/ticl/android2/AndroidManifest.xml +++ /dev/null @@ -1,15 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> - <!-- Copyright 2011 Google Inc. All Rights Reserved. --> - <!-- Test application for Android Client API and implementation. --> - <manifest xmlns:android="http://schemas.android.com/apk/res/android" - package="com.google.ipc.invalidation.ticl.android2.tests" - android:versionName="2.3.0"> - <!--Unit test runner application --> - <application> - <uses-library android:name="android.test.runner"/> - </application> - - <instrumentation - android:name="android.test.InstrumentationTestRunner" - android:targetPackage="com.google.ipc.invalidation.ticl.android2"/> - </manifest> diff --git a/chromium/third_party/cacheinvalidation/src/proto/android_channel.proto b/chromium/third_party/cacheinvalidation/src/proto/android_channel.proto deleted file mode 100644 index e5d47323930b04c0a06670ff7453abcfb4f88c3a..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/android_channel.proto +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// The Android delivery service's network endpoint id descriptor. -// This proto is internal to the Android channel. - -syntax = "proto2"; - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -option java_outer_classname = "AndroidChannel"; - - - - - -import "client_protocol.proto"; - -// Defines the valid major versions of the android channel protocol. The -// channel version controls the expected envelope syntax and semantics of -// http and c2dm messages sent between the client and server. -enum MajorVersion { - - // The initial version of the android channel protocol. Inbound and - // outbound channel packets contained a single binary protocol message only. - INITIAL = 0; - - // Adds batching (multiple protocol messages in a single channel message) - BATCH = 1; - - // The default channel version used by Android clients. Lower major numbers - // will represent earlier versions and higher numbers will represent - // experimental versions that are not yet released. - DEFAULT = 0; - - // The minimum and maximum supported channel major versions. Used to validate - // incoming requests, so update as new versions are added or old versions are - // no longer supported. - MIN_SUPPORTED = 0; - MAX_SUPPORTED = 1; -} - -// An id that specifies how to route a message to a Ticl on an Android device -// via C2DM. -message EndpointId { - // Field 1 was once the ProtocolVersion of this message. - - // The "registration_id" returned when the client registers with c2dm. This - // id is required by c2dm in order to send a message to the device. - optional string c2dm_registration_id = 2; - - // A key identifying a specific client on a device. - optional string client_key = 3; - - // The C2DM sender ID to use to deliver messages to the endpoint. - optional string sender_id = 4 [deprecated = true]; - - // Defines the expected channel version generated by the network endpoint or - // expected in messages sent from the server. - optional Version channel_version = 5; - - // The package name of the Android application that will receive the messages. - // Replaces sender_id. Must be set (unless sender_id is set; in which case it - // must not be set). - optional string package_name = 6; -} - -// A message addressed to a particular Ticl on an Android device. -message AddressedAndroidMessage { - // Client on the device to which the message is destined. - optional string client_key = 1; - - // Message contents (serialized ServerToClientMessage). - optional bytes message = 2; -} - -// A batch of messages addressed to potentially-different Ticls on the same -// Android device. -message AddressedAndroidMessageBatch { - repeated AddressedAndroidMessage addressed_message = 1; -} diff --git a/chromium/third_party/cacheinvalidation/src/proto/android_listener.proto b/chromium/third_party/cacheinvalidation/src/proto/android_listener.proto deleted file mode 100644 index 6a81e06202a090b9f96acf44401835c457a71382..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/android_listener.proto +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// Specification of protocols used by the AndroidListener abstraction. -// -// Note: unless otherwise specified in a comment, all fields in all messages -// are required, even though they are listed as optional. - -syntax = "proto2"; - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -option java_outer_classname = "AndroidListenerProtocol"; - - - - - -import "client.proto"; -import "client_protocol.proto"; - -// Used to persist internal state between instantiations of Android listener -// objects. -message AndroidListenerState { - // When a registration request has failed, we track state for that object that - // allows retries to be delayed using exponential backoff. - message RetryRegistrationState { - // Identifier of the object for which there has been a failure. - optional ObjectIdP object_id = 1; - - // State of exponential backoff delay generator that is used to delay any - // registration retries for the object. - optional ExponentialBackoffState exponential_backoff_state = 2; - } - - // Set of object ids tracking the application's desired registrations. - repeated ObjectIdP registration = 1; - - // Set of states for registrations retries. When there is a transient - // registration failure relative to an object, an entry is added. If - // registration is successful or the user gives up on the request, the entry - // is removed. - repeated RetryRegistrationState retry_registration_state = 2; - - // Identifier of client with which this listener is associated. This client ID - // is randomly generated by the Android listener whenever a new client is - // started and has no relationship to 's application client ID. - optional bytes client_id = 3; - - // Sequence number for alarm manager request codes. Sequence numbers are - // assigned serially for each distinct client_id. This value indicates - // the request code used for the last request. - optional int32 request_code_seq_num = 4; -} - -// Represents a command that registers or unregisters a set of objects. The -// command may be initiated by the application or by the Android listener when -// there is a registration failure. -message RegistrationCommand { - // Indicates whether this is a register command (when true) or unregister - // (when false) request. - optional bool is_register = 1; - - // Identifies the objects to register or unregister. - repeated ObjectIdP object_id = 2; - - // Identifier of client with which this listener is associated. - optional bytes client_id = 3; - - // Indicates whether this is a delayed registration command. When a - // registration command intent is handled by the Android listener, this field - // is used to determine whether the command has been delayed yet or not. If it - // has not already been delayed, the listener may choose to defer the command - // until later. - optional bool is_delayed = 4; -} - -// Represents a command that starts an Android invalidation client. -message StartCommand { - // Type of client to start. - optional int32 client_type = 1; - - // Name of client to start. - optional bytes client_name = 2; - - // Whether suppression is permitted for this client. - optional bool allow_suppression = 3; -} - diff --git a/chromium/third_party/cacheinvalidation/src/proto/android_service.proto b/chromium/third_party/cacheinvalidation/src/proto/android_service.proto deleted file mode 100644 index cd3287e27448af90eec2ef4269723f62c9a03650..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/android_service.proto +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// Specification of protocol buffers that are used with the Android -// service. -// -// Note: unless otherwise specified in a comment, all fields in all messages -// are required, even though they are listed as optional. - -syntax = "proto2"; - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -option java_outer_classname = "AndroidService"; - - -import "client_protocol.proto"; -import "java_client.proto"; - -// Call from application to Ticl. - -message ClientDowncall { - message StartDowncall {} - message StopDowncall {} - message AckDowncall { - optional bytes ack_handle = 1; - } - message RegistrationDowncall { - repeated ObjectIdP registrations = 1; - repeated ObjectIdP unregistrations = 2; - } - - // Serial number to prevent intent reordering. - // TODO: use. - optional int64 serial = 1; - optional Version version = 2; - - // Exactly one of the following fields must be set. - optional StartDowncall start = 3; - optional StopDowncall stop = 4; - optional AckDowncall ack = 5; - optional RegistrationDowncall registrations = 6; -} - -// Internal (non-public) call from application to Ticl. -message InternalDowncall { - message ServerMessage { - optional bytes data = 1; - } - message NetworkStatus { - optional bool is_online = 1; - } - message CreateClient { - optional int32 client_type = 1; // client type code. - optional bytes client_name = 2; // application client id. - optional ClientConfigP client_config = 3; // Client config. - - // Whether the client should not be started on creation. Must always be - // false for production use. - optional bool skip_start_for_test = 4; - } - optional Version version = 1; - - // Exactly one must be set. - optional ServerMessage server_message = 2; - optional NetworkStatus network_status = 3; - optional bool network_addr_change = 4; - optional CreateClient create_client = 5; -} - -// Upcall from Ticl to application listener. - -message ListenerUpcall { - message ReadyUpcall {} - - message InvalidateUpcall { - // Required. - optional bytes ack_handle = 1; - - // Exactly one must be set. - optional InvalidationP invalidation = 2; - optional ObjectIdP invalidate_unknown = 3; - optional bool invalidate_all = 4; - } - - message RegistrationStatusUpcall { - optional ObjectIdP object_id = 1; - optional bool is_registered = 2; - } - - message RegistrationFailureUpcall { - optional ObjectIdP object_id = 1; - optional bool transient = 2; - optional string message = 3; - } - - message ReissueRegistrationsUpcall { - optional bytes prefix = 1; - optional int32 length = 2; - } - - message ErrorUpcall { - optional int32 error_code = 1; - optional string error_message = 2; - optional bool is_transient = 3; - } - - // Serial number to prevent intent reordering. Not currently used. - // TODO: use - optional int64 serial = 1; - optional Version version = 2; - - // Exactly one must be sent. - optional ReadyUpcall ready = 3; - optional InvalidateUpcall invalidate = 4; - optional RegistrationStatusUpcall registration_status = 5; - optional RegistrationFailureUpcall registration_failure = 6; - optional ReissueRegistrationsUpcall reissue_registrations = 7; - optional ErrorUpcall error = 8; -} - -// Internal proto used by the Android scheduler to represent an event to run. -message AndroidSchedulerEvent { - optional Version version = 1; - - // Name of the recurring task to execute. - optional string event_name = 2; - - // Generation number of the Ticl with which this event is associated. Used to - // prevent old events from accidentally firing on new Ticls. - optional int64 ticl_id = 3; -} - -// Internal proto used by the Android network to represent a message to send -// to the data center from the client. -message AndroidNetworkSendRequest { - optional Version version = 1; // Required - optional bytes message = 2; // Required -} - -// Protocol buffer used to store state for a persisted Ticl. -message AndroidTiclState { - message Metadata { - // All fields are required. - optional int32 client_type = 1; // client type code. - optional bytes client_name = 2; // application client id. - optional int64 ticl_id = 3; // Ticl uniquifier. - optional ClientConfigP client_config = 4; // client config. - } - optional Version version = 1; - optional InvalidationClientState ticl_state = 2; // Marshalled Ticl. - optional Metadata metadata = 3; // Extra state needed to construct a Ticl. -} - -// An AndroidTiclState state plus a digest; this is the protocol buffer actually -// stored persistently by the service. -message AndroidTiclStateWithDigest { - optional AndroidTiclState state = 1; - optional bytes digest = 2; // Digest of "state." -} diff --git a/chromium/third_party/cacheinvalidation/src/proto/android_state.proto b/chromium/third_party/cacheinvalidation/src/proto/android_state.proto deleted file mode 100644 index fc444e2f1d0a0d50d56aa4c0ed58e425e3466831..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/android_state.proto +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// The Android internal storage format for per-client state. - -syntax = "proto2"; - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -option java_outer_classname = "AndroidState"; - - - - -import "client_protocol.proto"; - -// Base metadata for an Android client instance. All of these values -// are required and invariant for the life of the client. -message ClientMetadata { - - // The version of this state. - optional Version version = 1; - - // A key identifying a specific client on a device. - optional string client_key = 2; - - // The client type for this client. - optional int32 client_type = 3; - - // The user account name for this client. - optional string account_name = 4; - - // The user account type for this client. - optional string account_type = 5; - - // The authentication token type that is used for requests from this client. - optional string auth_type = 6; - - // The application package name for the client's event listener. - optional string listener_pkg = 7; - - // The class name for the client's event listener. - optional string listener_class = 8; - -} - -// Internal properties associated with the client by the client library. These -// properties may change or grow over time. -message ClientProperty { - - // The key of the stored property - optional string key = 1; - - // The value of the stored property - optional bytes value = 2; -} - -// The stored state of the client combining base metadata and internal properties. -message StoredState { - optional ClientMetadata metadata = 1; - - // TICL properties stored for this client. - repeated ClientProperty property = 9; -} diff --git a/chromium/third_party/cacheinvalidation/src/proto/channel_common.proto b/chromium/third_party/cacheinvalidation/src/proto/channel_common.proto deleted file mode 100644 index 4623bc0859ee99dd93e2c450c78988577e7803ac..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/channel_common.proto +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// Common utilities used by all channel related protos. -// This is also publicly visible to all channel implementors. - -syntax = "proto2"; - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -option java_outer_classname = "ChannelCommon"; - - - - -message ChannelMessageEncoding { - // What kind of encoding is used for network_message - enum MessageEncoding { - // Raw proto encoding - PROTOBUF_BINARY_FORMAT = 1; - - } -} - -message NetworkEndpointId { - enum NetworkAddress { - TEST = 1; // A delivery service for testing - - // Low numbers reserved. - ANDROID = 113; // Android delivery service using c2dm / http. - LCS = 114; // Lightweight connection service () channel. - } - optional NetworkAddress network_address = 1; - optional bytes client_address = 2; - - // Optional. When true, the client is considered offline but the - // client_address is maintained so that the client can potentially be reached. - // When false or undefined, the client is considered online. - optional bool is_offline = 3; -} diff --git a/chromium/third_party/cacheinvalidation/src/proto/client.proto b/chromium/third_party/cacheinvalidation/src/proto/client.proto deleted file mode 100644 index a9018c76204b9db17ddbaf916d9fa08538d07eb9..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/client.proto +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// Specification of protocol buffers that are used only on the client -// side. -// -// Note: unless otherwise specified in a comment, all fields in all messages -// are required, even though they are listed as optional. - -syntax = "proto2"; - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -option java_outer_classname = "Client"; - - - - - -import "client_protocol.proto"; - -// An object that is serialized and given to clients for acknowledgement -// purposes. -message AckHandleP { - optional InvalidationP invalidation = 1; -} - -// The state persisted at a client so that it can be used after a reboot. -message PersistentTiclState { - // Last token received from the server (required). - optional bytes client_token = 1; - - // Last time a message was sent to the server (optional). Must be a value - // returned by the clock in the Ticl system resources. - optional int64 last_message_send_time_ms = 2 [default = 0]; -} - -// An envelope containing a Ticl's internal state, along with a digest of the -// serialized representation of this state, to ensure its integrity across -// reads and writes to persistent storage. -message PersistentStateBlob { - // The (important parts of the) Ticl's internal state. - optional PersistentTiclState ticl_state = 1; - - // Implementation-specific message authentication code for the Ticl state. - optional bytes authentication_code = 2; -} - -// State of a Ticl RunState. -message RunStateP { - enum State { - NOT_STARTED = 1; - STARTED = 2; - STOPPED = 3; - } - optional State state = 1; -} - -// Fields in this message correspond directly to fields in -// ExponentialBackoffDelayGenerator. -message ExponentialBackoffState { - optional int32 current_max_delay = 1; - optional bool in_retry_mode = 2; -} diff --git a/chromium/third_party/cacheinvalidation/src/proto/client_protocol.proto b/chromium/third_party/cacheinvalidation/src/proto/client_protocol.proto deleted file mode 100644 index 5713e87529e4f2e26c7a0b52447c9fa61c963cb7..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/client_protocol.proto +++ /dev/null @@ -1,610 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// Specification of protocol buffers and the client-server protocol that -// are used by the clients of the system. -// -// Note: unless otherwise specified in a comment, all fields in all messages -// are required, even though they are listed as optional. - -syntax = "proto2"; - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -option java_outer_classname = "ClientProtocol"; - - - - - -// Here is a high-level overview of the protocol. The protocol is designed in a -// "message-passing" style, i.e., the client (C) or the server (S) can send any -// message SPONTANEOUSLY at any time and both sides have to be prepared for any -// message from the other side. However, even with this style, there are some -// "flows" which are somewhat like requests and replies. - -// 1. Initialization: When a client starts up, it needs a token to alow it to -// perform any other operation with the server. -// C -> S: InitializeMessage -// S -> C: TokenControlMessage -// -// 2. Registration: When a client has to register or unregister for a set of -// objects, the following flow occurs: -// C -> S: RegistrationMessage -// S -> C: RegistrationStatusMessage -// -// 3. Invalidation: The server sends an invalidation and the client sends back -// an ack. -// S -> C InvalidationMessage -// C -> S InvalidationMessage -// -// 4. Registration sync: Once in a while the server may detect that the client -// and server's registration state is out of sync (the server can detect this -// since it gets the client's registration summary in the client's message -// header). In that case, it asks the client some registration information -// and the client sends it to the server. -// S -> C: RegistrationSyncRequestMessage -// C -> S: RegistrationSyncMessage -// -// 5. Information messages: The server can occasionally for client-side -// information such as statistics, etc. The client responds with the -// requested information -// S -> C: InfoRequestMessage -// C -> S: InfoMessage -// -// ------------------------------------------------------------------------ - -// A basic message type used for versioning public proto messages and/or -// types. The two fields are supposed to be used as follows: -// -// * The major version number is changed whenever an incompatible protocol -// change or type has been made. When a message/object with a particular -// major version is received, the receiver needs to either know how to handle -// this version or it needs to drop the message -// -// * The minor version can be changed (say) to document some internal change -// for debugging purposes. When a message is received by a receiver, it MUST -// ignore the minor version number for making any protocol/type -// decisions. I.e., the minor version number is for debugging purposes only. -// -// Versioning is used in various places - for entities that are part of a -// protocol (e.g., message requests), for various client implementations, and -// for other data types that change independently of the protocol (e.g., -// session tokens). For each versioned entity, we define a specific message -// type to encapsulate the version of that entity (e.g., ProtocolVersion, -// ClientVersion, etc.). -message Version { - optional int32 major_version = 1; - optional int32 minor_version = 2; -} - -// Message included in all client <-> server messages to indicate the version -// of the protocol in use by the sender. -message ProtocolVersion { - optional Version version = 1; -} - -// Defines a specific version of the client library (for information purposes -// only) May not be used to make decisions at the server (use ProtocolVersion -// instead). -message ClientVersion { - - // A client-specific version number. - optional Version version = 1; - - // All fields below are for informational/debugging/monitoring purposes only. - // No critical code decision is supposed to be made using them. - - // Information about the client operating system/platform, e.g., Windows, - // ChromeOS. - optional string platform = 2; - - // Language used for the library. - optional string language = 3; - - // Extra information about the client (e.g., application name). - optional string application_info = 4; -} - -// Message indicating the result of an operation. -message StatusP { - - // Whether operation is successful or not - enum Code { - SUCCESS = 1; - TRANSIENT_FAILURE = 2; - PERMANENT_FAILURE = 3; - } - - optional Code code = 1; - - // Textual description of the status or additional context about any - // error. (Optional - Can be set for success also.) - optional string description = 2; -} - -// Identifies an object that a client can register for. -message ObjectIdP { - - // The source of the data. - optional int32 source = 1; - - // The id of the object relative to the source. Must be <= 64 bytes. - optional bytes name = 2; -} - -// A message containing the part of the client's id that the application -// controls. This id is used for squelching invalidations on the server side. -// For example, if a client C1 modifies object x and informs the backend about -// C1's application client id as part of the invalidation. The backend can then -// avoid sending the invalidation unnecessarily to that client. -// -// If the application wishes to use this squelching feature, it must assign a -// globally unique client_name for a given client_type so that the particular -// instantation of the application can be identified. -message ApplicationClientIdP { - // The type of the client. - optional int32 client_type = 1; - - // A client name or unique id assigned by the application. Application should - // choose a unique name for different client instances if it wants to squelch - // invalidations by name (as discussed above). - optional bytes client_name = 2; -} - -// Invalidation for a given object/version. -message InvalidationP { - // The id of the object being invalidated. - optional ObjectIdP object_id = 1; - - // Whether the invalidation is for a known version of the object as assigned - // by an application backend (is_known_version == true) or an unknown system - // version synthesized by the invalidation service. (Note that if - // is_known_version is false then is_trickle_restart be true or missing - // because an unknown version implies that invalidation versions prior to the - // current backend version may have been dropped.) - optional bool is_known_version = 2; - - // Version being invalidated (see comment on is_known_version). If the - // is_known_version is false, the version corresponds to an internal "system - // version" for *that* object. An object's system version has no meaning to - // the application other than the fact that these system versions are also - // monotonically increasing and the client must ack such an invalidation with - // this system version (and an ack for a later system version acknowledges an - // invalidation for all earlier system version for *that* object. - optional int64 version = 3; - - // Whether the object's Trickle is restarting at this version. - // sets this value to true to inform Trickle API clients that it may - // have dropped invalidations prior to "version", or, if is_known_version is - // false, prior to the current backend version. This field is logically - // required and is always set by current code. The default is true because - // old Android invalidation clients strip this field when acking - // invalidations due to ProtoLite limitations; true is the correct default - // because invalidation clients logically ack all current versions and - // because old persisted invalidations are all restarted. - optional bool is_trickle_restart = 6 [default = true]; - - // Optional payload associated with this invalidation. - optional bytes payload = 4; - - // DEPRECATED: bridge arrival time is now maintained by - // InvalidationMetadataP in the SourcedInvalidation, InvalidationContents and - // ClientInvalidation containers. - optional int64 bridge_arrival_time_ms_deprecated = 5 [deprecated=true]; -} - -// Specifies the intention to change a registration on a specific object. To -// update registrations, a client sends a message containing repeated -// RegistrationP messages. -message RegistrationP { - enum OpType { - REGISTER = 1; - UNREGISTER = 2; - } - - // The object for which to (un)register. - optional ObjectIdP object_id = 1; - - // Whether to register or unregister. - optional OpType op_type = 2; -} - -// Summary of the registration state associated with a particular client, sent -// in the header of client<->server messages. This summary has two different -// (but related) meanings depending on where it is used: -// -// 1) In a client->server message, it describes the DESIRED client state. -// 2) In a server->client message, it describes the ACTUAL state at the server -// for that client. -message RegistrationSummary { - // Number of registrations desired (client) or held (server). - optional int32 num_registrations = 1; - - // Top-level digest over the registrations. - // - // The digest for an object id is computed as following (the digest chosen for - // this method is SHA-1): - // - // digest = new Digest(); - // digest.update(Little endian encoding of object source type) - // digest.update(object name) - // digest.getDigestSummary() - // - // For a set of objects, digest is computing by sorting lexicographically - // based on their digests and then performing the update process given above - // (i.e., calling digest.update on each object's digest and then calling - // getDigestSummary at the end). - optional bytes registration_digest = 2; -} - -// Header included on every client -> server message. -message ClientHeader { - - // Protocol version of this message. - optional ProtocolVersion protocol_version = 1; - - // Token identifying the client. Tokens are issued by the server in response - // to client requests (see InitializeMessage, below). In order to perform any - // operation other than initialization, the client must supply a token. When - // performing initialization, this field must be left unset. - optional bytes client_token = 2; - - // Optional summary of the client's desired registration state. The client is - // encouraged to provide this summary in every message once a "steady" state - // of registrations/unregistrations has been reached. For example, it may not - // want to send this summary during initialization (but after the initial set - // has been registered, it should try to send it). - optional RegistrationSummary registration_summary = 3; - - // Timestamp from the client's clock, expressed as ms since 00:00:00 UTC, 1 - // January 1970 (i.e., the UNIX epoch) - for debugging/monitoring purposes. - optional int64 client_time_ms = 4; - - // Highest server timestamp observed by the client (the server includes its - // time on every message to the client). Note: this time is NOT necessarily - // expressed as relative to the UNIX epoch - for debugging/monitoring - // purposes. - optional int64 max_known_server_time_ms = 5; - - // Message id to identify the message -for debugging/monitoring purposes. - optional string message_id = 6; - - // Client typecode (as in the InitializeMessage, below). This field may or - // may not be set. - optional int32 client_type = 7; -} - -// A message from the client to the server. -message ClientToServerMessage { - // Header. - optional ClientHeader header = 1; - - // Any or all of the follow messages may be present. - - // Optional initialization message, used to obtain a new token. Note that, if - // present, this message is always processed before the messages below, and - // those messages will be interpreted relative to the new token assigned here. - optional InitializeMessage initialize_message = 2; - - // Optional request to perform registrations. - optional RegistrationMessage registration_message = 3; - - // Optional data for registration sync. - optional RegistrationSyncMessage registration_sync_message = 4; - - // Optional invalidation acks. - optional InvalidationMessage invalidation_ack_message = 5; - - // Optional information about the client. - optional InfoMessage info_message = 6; -} - -// Used to obtain a new token when the client does not have one. -message InitializeMessage { - - // Defines how clients serialize object ids when computing digests for - // registrations. - enum DigestSerializationType { - - // The digest for an object id is computed by serializing the object id into - // bytes. - BYTE_BASED = 1; - - // The digest for an object id is computed by serializing the object id into - // an array of numbers. TODO: Determine and specify this - // more precisely. - NUMBER_BASED = 2; - } - - // Type of the client. This value is assigned by the backend notification - // system (out-of-band) and the client must use the correct value. - optional int32 client_type = 1; - - // Nonce. This value will be echoed as the existing token in the header of - // the server message that supplies the new token (the new token itself will - // be provided in a TokenControlMessage; see below). - optional bytes nonce = 2; - - // Id of the client as assigned by the application. - optional ApplicationClientIdP application_client_id = 3; - - // Type of registration digest used by this client. - optional DigestSerializationType digest_serialization_type = 4; -} - -// Registration operations to perform. -message RegistrationMessage { - repeated RegistrationP registration = 1; -} - -// Message from the client to the server. -message RegistrationSyncMessage { - - // Objects for which the client is registered. - repeated RegistrationSubtree subtree = 1; -} - -// Message sent from the client to the server about registered objects -// (typically) in response to a registration sync request. -// -// The name of the message implies a "tree" for future expansion where the -// intention is to not necessarily send the complete set of objects but to -// partition the object space into multiple ranges and then exchange Merkle-tree -// like data structures to determine which ranges are out-of-sync. -message RegistrationSubtree { - // Registered objects - repeated ObjectIdP registered_object = 1; -} - -// A message from the client to the server with info such as performance -// counters, client os info, etc. -message InfoMessage { - optional ClientVersion client_version = 1; - - // Config parameters used by the client. - // Deprecated and removed - the client_config parameter is what is used now. - repeated PropertyRecord config_parameter = 2; - - // Performance counters from the client. - repeated PropertyRecord performance_counter = 3; - - // If 'true', indicates that the client does not know the server's - // registration summary, so the server should respond with it even if the - // client's summary matches the server's. - optional bool server_registration_summary_requested = 4; - - // Configuration parameters for this client. - optional ClientConfigP client_config = 5; -} - -// Information about a single config/performance counter value in the -// InfoMessage. -message PropertyRecord { - - // Name of the performance counter/config parameter. - optional string name = 1; - - // Value of the performance counter/config parameter. - optional int32 value = 2; -} - -message ServerHeader { - // Protocol version of this message. - optional ProtocolVersion protocol_version = 1; - - // Current token that the server expects the client to have. Clients must - // ignore messages where this token field does not match their current token. - // During initialization, the client's "token" is the nonce that it generates - // and sends in the InitializeMessage. - optional bytes client_token = 2; - - // Summary of registration state held by the server for the client. - optional RegistrationSummary registration_summary = 3; - - // Timestamp from the server's clock. No guarantee on when this time is - // relative to. - optional int64 server_time_ms = 4; - - // Message id to identify the message (for debug purposes only). - optional string message_id = 5; -} - -// If ServerToClientMessage is modified, you need to change the type -// TestServerToClientMessageWithExtraFields in the same way to match. -message ServerToClientMessage { - optional ServerHeader header = 1; - - // Message to assign a new client token or invalidate an existing one. Note - // that, if present, this message is always processed before the messages - // below, and those messages will be interpreted relative to the new token - // assigned here. - optional TokenControlMessage token_control_message = 2; - - // Invalidations. - optional InvalidationMessage invalidation_message = 3; - - // Registration operation replies. - optional RegistrationStatusMessage registration_status_message = 4; - - // Request for client registration state. - optional RegistrationSyncRequestMessage registration_sync_request_message = 5; - - // Request to change config from the server. - optional ConfigChangeMessage config_change_message = 6; - - // Request for client information. - optional InfoRequestMessage info_request_message = 7; - - // Asynchronous error information that the server sends to the client. - optional ErrorMessage error_message = 8; -} - -// Message used to supply a new client token or invalidate an existing one. -message TokenControlMessage { - // If status is failure, new_token cannot be set. - optional bytes new_token = 1; // If missing, means destroy_token -} - -// Status of a particular registration (could be sent spontaneously by the -// server or in response to a registration request). -message RegistrationStatus { - optional RegistrationP registration = 1; - optional StatusP status = 2; -} - -// Registration status of several messages from the server to the client. -message RegistrationStatusMessage { - repeated RegistrationStatus registration_status = 1; -} - -// Request from the server to get the registration info from the client for -// sync purposes. -message RegistrationSyncRequestMessage { -} - -// A set of invalidations from the client to the server or vice-versa -message InvalidationMessage { - repeated InvalidationP invalidation = 1; -} - -// A request from the server to the client for information such as -// performance counters, client os, etc -message InfoRequestMessage { - enum InfoType { - GET_PERFORMANCE_COUNTERS = 1; - } - repeated InfoType info_type = 1; -} - -// A rate limit: a count of events and a window duration in which the events -// may occur. -message RateLimitP { - - // The size of the window over which the rate limit applies. - optional int32 window_ms = 1; - - // The number of events allowed within a given window. - optional int32 count = 2; -} - -// Configuration parameters for the protocol handler in the Ticl. -message ProtocolHandlerConfigP { - // Batching delay - certain messages (e.g., registrations, invalidation acks) - // are sent to the server after this delay. - optional int32 batching_delay_ms = 1 [default = 500]; - - // Rate limits for sending messages. Only two levels allowed currently. - repeated RateLimitP rate_limit = 2; -} - -// Configuration parameters for the Ticl. -message ClientConfigP { - - optional Version version = 1; - - // The delay after which a network message sent to the server is considered - // timed out. - optional int32 network_timeout_delay_ms = 2 [default = 60000]; - - // Retry delay for a persistent write if it fails - optional int32 write_retry_delay_ms = 3 [default = 10000]; - - // Delay for sending heartbeats to the server. - optional int32 heartbeat_interval_ms = 4 [default = 1200000]; - - // Delay after which performance counters are sent to the server. - optional int32 perf_counter_delay_ms = 5 [default = 21600000]; // 6 hours. - - // The maximum exponential backoff factor used for network and persistence - /// timeouts. - optional int32 max_exponential_backoff_factor = 6 [default = 500]; - - // Smearing percent for randomizing delays. - optional int32 smear_percent = 7 [default = 20]; - - // Whether the client is transient, that is, does not write its session - // token to durable storage. - // TODO: need to expose to the clients. - optional bool is_transient = 8 [default = false]; - - // Initial delay for a heartbeat after restarting from persistent state. We - // use this so that the application has a chance to respond to the - // reissueRegistrations call. - optional int32 initial_persistent_heartbeat_delay_ms = 9 [default = 2000]; - - // Configuration for the protocol client to control batching etc. - optional ProtocolHandlerConfigP protocol_handler_config = 10; - - // Whether the channel supports delivery while the client is offline. If - // true, then the servers' use of the channel is such that the - // following holds: if any number of messages are sent to the client while - // the client is unreachable, then the channel will eventually deliver at - // least one message to the client such that, on receiving the message, the - // client will send a message to the server. E.g., the channel could deliver - // a single invalidation or a single registration sync request. C2DM is - // an example of a suitable channel. - // - // When this is true, the Ticl will record in persistent storage the last - // time it sent a message to the server. On persistent restart, it will not - // send a message to the server unless the last one was sent more than a - // heartbeat-interval ago. This is designed to support efficient Android - // clients, which will destroy and recreate the Ticl when transitioning - // between foreground and background states. - optional bool channel_supports_offline_delivery = 11 [default = false]; - - // If the client loses network connectivity, it will send a heartbeat after it - // comes online, unless it had already sent a message more recently than this - // threshold. - optional int32 offline_heartbeat_threshold_ms = 12 [default = 60000]; - - // Whether the client allows suppression. If true (the default), then - // both continuous and restarted invalidations result in an invalidate() - // upcall, which is appropriate for invalidation clients. If false, - // then restarted invalidations result in an invalidateUnknownVersion() - // upcall, which provides correct semantics for Trickles clients. - optional bool allow_suppression = 13 [default = true]; -} - -// A message asking the client to change its configuration parameters -message ConfigChangeMessage { - - // On receipt of this value, do not send any new message to the server - // for the specified delay (this message needs to be accepted without - // any token check). A zero value is ignored by the client. So the lowest - // value for this field is 1. This concept exists to allow the server - // to tell the clients that they should not come back to the server - // for some period of time. - optional int64 next_message_delay_ms = 1; -} - -// An error message that contains an enum for different types of failures with a -// textual description of the failure (as the need arises new error codes will -// be added to this message). -message ErrorMessage { - - enum Code { - AUTH_FAILURE = 1; // Authorization or authentication failure. - UNKNOWN_FAILURE = 10000; // Some failure which is not described above. - }; - - optional Code code = 1; - - // Textual description of the error - optional string description = 2; -} diff --git a/chromium/third_party/cacheinvalidation/src/proto/java_client.proto b/chromium/third_party/cacheinvalidation/src/proto/java_client.proto deleted file mode 100644 index 7e8fcf027e46a49e8e45effdcbf9baa531a1a9a3..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/java_client.proto +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// -// Specification of protocol buffers that are used to marshall the -// in-memory state of an invalidation client. -// -// Note: unless otherwise specified in a comment, all fields in all messages -// are required, even though they are listed as optional. - -syntax = "proto2"; - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -option java_outer_classname = "JavaClient"; - - -import 'client.proto'; -import 'client_protocol.proto'; - -// State of the batched messages in the ProtocolHandler. Corresponds to -// ProtocolHandler.Batcher. -message BatcherState { - repeated ObjectIdP registration = 1; - repeated ObjectIdP unregistration = 2; - repeated InvalidationP acknowledgement = 3; - repeated RegistrationSubtree registration_subtree = 4; - optional InitializeMessage initialize_message = 5; - optional InfoMessage info_message = 6; -} - -// State of the protocol handler. Fields correspond directly to fields in -// ProtocolHandler.java. -message ProtocolHandlerState { - optional int32 message_id = 1; - optional int64 last_known_server_time_ms = 2; - optional int64 next_message_send_time_ms = 3; - optional BatcherState batcher_state = 4; -} - -// State of the registration manager. -message RegistrationManagerStateP { - repeated ObjectIdP registrations = 1; - optional RegistrationSummary last_known_server_summary = 2; - repeated RegistrationP pending_operations = 3; -} - -// State of a recurring task. Fields correspond directly to fields in -// RecurringTask.java. -message RecurringTaskState { - optional int32 initial_delay_ms = 1; - optional int32 timeout_delay_ms = 2; - optional bool scheduled = 3; - optional ExponentialBackoffState backoff_state = 4; -} - -// State of the statistics object. Marshalling is done by marshalling the -// SimplePairs returned by Statistics.fillWithNonZeroStatistics into -// PropertyRecords. -message StatisticsState { - repeated PropertyRecord counter = 1; -} - -// State of the invalidation client. Fields correspond directly to fields in -// InvalidationClientImpl.java. -message InvalidationClientState { - optional RunStateP run_state = 1; - optional bytes client_token = 2; - optional bytes nonce = 3; - optional bool should_send_registrations = 4; - optional int64 last_message_send_time_ms = 5; - optional bool is_online = 6; - optional ProtocolHandlerState protocol_handler_state = 7; - optional RegistrationManagerStateP registration_manager_state = 8; - optional RecurringTaskState acquire_token_task_state = 9; - optional RecurringTaskState reg_sync_heartbeat_task_state = 10; - optional RecurringTaskState persistent_write_task_state = 11; - optional RecurringTaskState heartbeat_task_state = 12; - optional RecurringTaskState batching_task_state = 13; - optional PersistentTiclState last_written_state = 14; - optional StatisticsState statistics_state = 15; -} diff --git a/chromium/third_party/cacheinvalidation/src/proto/types.proto b/chromium/third_party/cacheinvalidation/src/proto/types.proto deleted file mode 100644 index 13b43aea8c025df98f34297b309bd18ef5d4d9e5..0000000000000000000000000000000000000000 --- a/chromium/third_party/cacheinvalidation/src/proto/types.proto +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Enums definitions for main types in the cache invalidation system. - -syntax = "proto2"; - - -package com.google.protos.ipc.invalidation; - -option optimize_for = LITE_RUNTIME; - -// The type of client / application. -message ClientType { - enum Type { - INTERNAL = 1; - TEST = 2; // Uncontrolled client space for use by anyone for testing. - DEMO = 4; // A demo client type that can be used for testing. - - // Numbers below 1000 are reserved for internal use. - CHROME_SYNC = 1004; - CHROME_SYNC_ANDROID = 1018; - CHROME_SYNC_IOS = 1038; - } - optional Type type = 1; -} - -// The property that hosts the object. -message ObjectSource { - // - // NOTE: This enum MUST be kept in sync with ObjectIdP.Source in - // internal.proto. - // - enum Type { - INTERNAL = 1; - TEST = 2; // Uncontrolled object space for use by anyone for testing. - DEMO = 4; // A demo object source that can be used for testing. - - // Numbers below 1000 are reserved for internal use. - CHROME_SYNC = 1004; - COSMO_CHANGELOG = 1014; - CHROME_COMPONENTS = 1025; - CHROME_PUSH_MESSAGING = 1030; - } - optional Type type = 1; -} - -// A dummy message to enclose various enum constant declarations. -message Constants { - // Constants related to object versions. - enum ObjectVersion { - // Version number used to indicate that an object's version is unknown. - UNKNOWN = 0; - } -}