File: Async.h

package info (click to toggle)
trafficserver 9.2.5%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 53,008 kB
  • sloc: cpp: 345,484; ansic: 31,134; python: 24,200; sh: 7,271; makefile: 3,045; perl: 2,261; java: 277; pascal: 119; sql: 94; xml: 2
file content (265 lines) | stat: -rw-r--r-- 8,481 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/**
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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.
 */

/**
 * @file Async.h
 * @brief Provides constructs to perform async operations.
 */

#pragma once

#include <memory>
#include <mutex>
#include <unordered_map>
#include <utility>

#include "tscpp/api/noncopyable.h"

namespace atscppapi
{
#if !defined(ATSCPPAPI_MUTEX_DEFINED_)
#define ATSCPPAPI_MUTEX_DEFINED_

using Mutex = std::recursive_mutex;

#endif

/**
 * @private
 *
 * @brief This class represents the interface of a dispatch controller. A dispatch controller
 * is used to dispatch an event to a receiver. This interface exists so that the types in this
 * header file can be defined.
 */
class AsyncDispatchControllerBase : noncopyable
{
public:
  /**
   * Dispatches an async event to a receiver.
   *
   * @return True if the receiver was still alive.
   */
  virtual bool dispatch() = 0;

  /** Renders dispatch unusable to communicate to receiver */
  virtual void disable() = 0;

  /** Returns true if receiver can be communicated with */
  virtual bool isEnabled() = 0;

  virtual ~AsyncDispatchControllerBase() {}
};

/**
 * @brief AsyncProvider is the interface that providers of async operations must implement.
 * The system allows decoupling of the lifetime/scope of provider and receiver objects. The
 * receiver object might have expired before the async operation is complete and the system
 * handles this case. Because of this decoupling, it is the responsibility of the provider
 * to manage it's expiration - self-destruct on completion is a good option.
 */
class AsyncProvider
{
public:
  /**
   * This method is invoked when the async operation is requested. This call should be used
   * to just start the async operation and *not* block this thread. On completion,
   * getDispatchController() can be used to invoke the receiver.
   */
  virtual void run() = 0;

  /** Base implementation just breaks communication channel with receiver. Implementations
   * should add business logic here. */
  virtual void
  cancel()
  {
    if (dispatch_controller_) {
      dispatch_controller_->disable();
    }
  }

  virtual ~AsyncProvider() { this->cancel(); }

protected:
  std::shared_ptr<AsyncDispatchControllerBase>
  getDispatchController()
  {
    return dispatch_controller_;
  }

private:
  std::shared_ptr<AsyncDispatchControllerBase> dispatch_controller_;
  void
  doRun(std::shared_ptr<AsyncDispatchControllerBase> dispatch_controller)
  {
    dispatch_controller_ = std::move(dispatch_controller);
    run();
  }
  friend class Async;
};

/**
 * @private
 *
 * @brief Dispatch controller implementation. When invoking the receiver, it verifies that the
 * receiver is still alive, locks the mutex and then invokes handleAsyncComplete().
 */
template <typename AsyncEventReceiverType, typename AsyncProviderType>
class AsyncDispatchController : public AsyncDispatchControllerBase
{
public:
  bool
  dispatch() override
  {
    bool ret = false;
    std::lock_guard<Mutex> scopedLock(*dispatch_mutex_);
    if (event_receiver_) {
      event_receiver_->handleAsyncComplete(static_cast<AsyncProviderType &>(*provider_));
      ret = true;
    }
    return ret;
  }

  void
  disable() override
  {
    std::lock_guard<Mutex> scopedLock(*dispatch_mutex_);
    if (event_receiver_ != nullptr) {
      event_receiver_->revokePromise(this);
      event_receiver_ = nullptr;
    }
  }

  bool
  isEnabled() override
  {
    return (event_receiver_ != nullptr);
  }

  /**
   * Constructor
   *
   * @param event_receiver The async complete event will be dispatched to this receiver.
   * @param provider Async operation provider that is passed to the receiver on dispatch.
   * @param mutex Mutex of the receiver that is locked during the dispatch
   */
  AsyncDispatchController(AsyncEventReceiverType *event_receiver, AsyncProviderType *provider, std::shared_ptr<Mutex> mutex)
    : event_receiver_(event_receiver), dispatch_mutex_(std::move(mutex)), provider_(provider)
  {
  }

  ~AsyncDispatchController() override {}

public:
  AsyncEventReceiverType *event_receiver_;
  std::shared_ptr<Mutex> dispatch_mutex_;

private:
  AsyncProviderType *provider_;
};

/**
 * @private
 *
 * @brief A promise is used to let the dispatch controller know if the receiver is still
 * alive to receive the async complete dispatch. When the receiver dies, this promise is
 * broken and it automatically updates the dispatch controller.
 */
template <typename AsyncEventReceiverType, typename AsyncProviderType> class AsyncReceiverPromise : noncopyable
{
public:
  AsyncReceiverPromise(std::shared_ptr<AsyncDispatchController<AsyncEventReceiverType, AsyncProviderType>> dispatch_controller)
    : dispatch_controller_(dispatch_controller)
  {
  }

  ~AsyncReceiverPromise()
  {
    std::lock_guard<Mutex> scopedLock(*(dispatch_controller_->dispatch_mutex_));
    dispatch_controller_->event_receiver_ = nullptr;
  }

protected:
  std::shared_ptr<AsyncDispatchController<AsyncEventReceiverType, AsyncProviderType>> dispatch_controller_;
};

/**
 * @brief AsyncReceiver is the interface that receivers of async operations must implement. It is
 * templated on the type of the async operation provider.
 */
template <typename AsyncProviderType> class AsyncReceiver : noncopyable
{
public:
  /**
   * This method is invoked when the async operation is completed. The
   * mutex provided during the creation of the async operation will be
   * automatically locked during the invocation of this method.
   *
   * @param provider A reference to the provider which completed the async operation.
   */
  virtual void handleAsyncComplete(AsyncProviderType &provider) = 0;
  virtual ~AsyncReceiver() {}
  void
  revokePromise(AsyncDispatchController<AsyncReceiver<AsyncProviderType>, AsyncProviderType> *dispatch_controller_ptr)
  {
    receiver_promises_.erase(dispatch_controller_ptr);
  }

protected:
  AsyncReceiver() {}
  friend class Async;

private:
  mutable std::unordered_map<AsyncDispatchController<AsyncReceiver<AsyncProviderType>, AsyncProviderType> *,
                             std::shared_ptr<AsyncReceiverPromise<AsyncReceiver<AsyncProviderType>, AsyncProviderType>>>
    receiver_promises_;
};

/**
 * @brief This class provides a method to create an async operation.
 */
class Async : noncopyable
{
public:
  /**
   * This method sets up the dispatch controller to link the async operation provider and
   * receiver and then initiates the operation by invoking the provider.
   *
   * @param event_receiver The receiver of the async complete dispatch.
   * @param provider The provider of the async operation.
   * @param mutex The mutex that is locked during the dispatch of the async event complete.
   *              One will be created if nothing is passed in. Transaction plugins should use
   *              TransactionPlugin::getMutex() here and global plugins can pass an appropriate
   *              or nullptr mutex.
   */
  template <typename AsyncProviderType>
  static void
  execute(AsyncReceiver<AsyncProviderType> *event_receiver, AsyncProviderType *provider, std::shared_ptr<Mutex> mutex)
  {
    if (!mutex.get()) {
      mutex.reset(new Mutex);
    }
    std::shared_ptr<AsyncDispatchController<AsyncReceiver<AsyncProviderType>, AsyncProviderType>> dispatcher(
      new AsyncDispatchController<AsyncReceiver<AsyncProviderType>, AsyncProviderType>(event_receiver, provider, mutex));
    std::shared_ptr<AsyncReceiverPromise<AsyncReceiver<AsyncProviderType>, AsyncProviderType>> receiver_promise(
      new AsyncReceiverPromise<AsyncReceiver<AsyncProviderType>, AsyncProviderType>(dispatcher));
    event_receiver->receiver_promises_[dispatcher.get()] = receiver_promise;
    provider->doRun(dispatcher);
  }
};

} // end namespace atscppapi