1 // Copyright 2018 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.
4 
5 #ifndef SERVICES_NETWORK_PENDING_CALLBACK_CHAIN_H_
6 #define SERVICES_NETWORK_PENDING_CALLBACK_CHAIN_H_
7 
8 #include "base/component_export.h"
9 #include "base/memory/ref_counted.h"
10 #include "net/base/completion_once_callback.h"
11 #include "net/base/net_errors.h"
12 
13 namespace network {
14 
15 // Helper class to keep track of multiple functions which may return
16 // net::ERR_IO_PENDING and call a net::CompletionOnceCallback, or return another
17 // net error synchronously, and not call the completion callback. If there are
18 // one or more pending results added, the original completion callback will not
19 // be called until all those results have completed. If there are multiple error
20 // results that are different, net::ERR_FAILED will be used.
COMPONENT_EXPORT(NETWORK_SERVICE)21 class COMPONENT_EXPORT(NETWORK_SERVICE) PendingCallbackChain
22     : public base::RefCounted<PendingCallbackChain> {
23  public:
24   explicit PendingCallbackChain(net::CompletionOnceCallback complete);
25 
26   // Creates a callback that can be called to decrement the wait count if a
27   // net::ERR_IO_PENDING result is added with AddResult().
28   net::CompletionOnceCallback CreateCallback();
29 
30   // Adds a result to the chain. If the result is net::ERR_IO_PENDING,
31   // a corresponding callback will need to be called before the original
32   // completion callback is called.
33   void AddResult(int result);
34 
35   // Gets the current result of the chain. This will be net::ERR_IO_PENDING if
36   // there are any pending results.
37   int GetResult() const;
38 
39  private:
40   friend class base::RefCounted<PendingCallbackChain>;
41   ~PendingCallbackChain();
42 
43   void CallbackComplete(int result);
44   void SetResult(int result);
45 
46   int num_waiting_ = 0;
47   int final_result_ = net::OK;
48   net::CompletionOnceCallback complete_;
49 };
50 
51 }  // namespace network
52 
53 #endif  // SERVICES_NETWORK_PENDING_CALLBACK_CHAIN_H_
54