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 #ifndef CHROME_BROWSER_SEARCH_SUGGESTIONS_SUGGESTIONS_SERVICE_H_
6 #define CHROME_BROWSER_SEARCH_SUGGESTIONS_SUGGESTIONS_SERVICE_H_
10 #include "base/basictypes.h"
11 #include "base/callback.h"
12 #include "base/gtest_prod_util.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/time/time.h"
15 #include "chrome/browser/search/suggestions/proto/suggestions.pb.h"
16 #include "components/keyed_service/core/keyed_service.h"
17 #include "net/url_request/url_fetcher_delegate.h"
22 namespace suggestions
{
24 extern const char kSuggestionsFieldTrialName
[];
25 extern const char kSuggestionsFieldTrialURLParam
[];
26 extern const char kSuggestionsFieldTrialStateParam
[];
27 extern const char kSuggestionsFieldTrialStateEnabled
[];
29 // An interface to fetch server suggestions asynchronously.
30 class SuggestionsService
: public KeyedService
, public net::URLFetcherDelegate
{
32 typedef base::Callback
<void(const SuggestionsProfile
&)> ResponseCallback
;
34 explicit SuggestionsService(Profile
* profile
);
35 virtual ~SuggestionsService();
37 // Whether this service is enabled.
38 static bool IsEnabled();
40 // Request suggestions data, which will be passed to |callback|. Initiates a
41 // fetch request unless a pending one exists. To prevent multiple requests,
42 // we place all |callback|s in a queue and update them simultaneously when
43 // fetch request completes.
44 void FetchSuggestionsData(ResponseCallback callback
);
47 FRIEND_TEST_ALL_PREFIXES(SuggestionsServiceTest
, FetchSuggestionsData
);
49 // net::URLFetcherDelegate implementation.
50 // Called when fetch request completes. Parses the received suggestions data,
51 // and dispatches them to callbacks stored in queue.
52 virtual void OnURLFetchComplete(const net::URLFetcher
* source
) OVERRIDE
;
54 // KeyedService implementation.
55 virtual void Shutdown() OVERRIDE
;
57 // Contains the current suggestions fetch request. Will only have a value
58 // while a request is pending, and will be reset by |OnURLFetchComplete|.
59 scoped_ptr
<net::URLFetcher
> pending_request_
;
61 // The start time of the previous suggestions request. This is used to measure
62 // the latency of requests. Initially zero.
63 base::TimeTicks last_request_started_time_
;
65 // The URL to fetch suggestions data from.
66 GURL suggestions_url_
;
68 // Queue of callbacks. These are flushed when fetch request completes.
69 std::vector
<ResponseCallback
> waiting_requestors_
;
73 DISALLOW_COPY_AND_ASSIGN(SuggestionsService
);
76 } // namespace suggestions
78 #endif // CHROME_BROWSER_SEARCH_SUGGESTIONS_SUGGESTIONS_SERVICE_H_