1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chromeos/file_system_provider/request_manager.h"
7 #include "base/files/file.h"
8 #include "base/stl_util.h"
11 namespace file_system_provider {
15 // Timeout in seconds, before a request is considered as stale and hence
17 const int kDefaultTimeout = 10;
21 RequestManager::RequestManager()
23 timeout_(base::TimeDelta::FromSeconds(kDefaultTimeout)),
24 weak_ptr_factory_(this) {}
26 RequestManager::~RequestManager() {
27 // Abort all of the active requests.
28 RequestMap::iterator it = requests_.begin();
29 while (it != requests_.end()) {
30 const int request_id = it->first;
32 RejectRequest(request_id, base::File::FILE_ERROR_ABORT);
35 DCHECK_EQ(0u, requests_.size());
36 STLDeleteValues(&requests_);
39 int RequestManager::CreateRequest(scoped_ptr<HandlerInterface> handler) {
40 // The request id is unique per request manager, so per service, thereof
42 int request_id = next_id_++;
44 // If cycled the int, then signal an error.
45 if (requests_.find(request_id) != requests_.end())
48 Request* request = new Request;
49 request->handler = handler.Pass();
50 request->timeout_timer.Start(FROM_HERE,
52 base::Bind(&RequestManager::OnRequestTimeout,
53 weak_ptr_factory_.GetWeakPtr(),
55 requests_[request_id] = request;
57 // Execute the request implementation. In case of an execution failure,
58 // unregister and return 0. This may often happen, eg. if the providing
59 // extension is not listening for the request event being sent.
60 // In such case, there is no reason we should abort as soon as possible.
61 if (!request->handler->Execute(request_id)) {
63 requests_.erase(request_id);
70 bool RequestManager::FulfillRequest(int request_id,
71 scoped_ptr<RequestValue> response,
73 RequestMap::iterator request_it = requests_.find(request_id);
75 if (request_it == requests_.end())
78 request_it->second->handler->OnSuccess(request_id, response.Pass(), has_next);
80 delete request_it->second;
81 requests_.erase(request_it);
83 request_it->second->timeout_timer.Reset();
89 bool RequestManager::RejectRequest(int request_id, base::File::Error error) {
90 RequestMap::iterator request_it = requests_.find(request_id);
92 if (request_it == requests_.end())
95 request_it->second->handler->OnError(request_id, error);
96 delete request_it->second;
97 requests_.erase(request_it);
102 void RequestManager::SetTimeoutForTests(const base::TimeDelta& timeout) {
106 void RequestManager::OnRequestTimeout(int request_id) {
107 RejectRequest(request_id, base::File::FILE_ERROR_ABORT);
110 RequestManager::Request::Request() {}
112 RequestManager::Request::~Request() {}
114 } // namespace file_system_provider
115 } // namespace chromeos