proxygen
futures.h
Go to the documentation of this file.
1 /*
2  * Copyright 2016-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 /*
17  * This file serves as a helper for bridging folly::future and python
18  * asyncio.future.
19  */
20 
21 #pragma once
22 
23 #include <Python.h>
24 #include <folly/Executor.h>
25 #include <folly/futures/Future.h>
27 #include <folly/python/executor_api.h>
28 
29 namespace folly {
30 namespace python {
31 
33  import_folly__executor();
34  return get_executor();
35 }
36 
37 template <typename T>
40  folly::Future<T>&& futureFrom,
41  folly::Function<void(folly::Try<T>&&, PyObject*)> callback,
42  PyObject* userData) {
43  // We are handing over a pointer to a python object to c++ and need
44  // to make sure it isn't removed by python in that time.
45  Py_INCREF(userData);
46  auto guard = folly::makeGuard([=] { Py_DECREF(userData); });
47  // Handle the lambdas for cython
48  // run callback from our Q
49  futureFrom.via(executor).then(
50  [callback = std::move(callback), userData, guard = std::move(guard)](
51  folly::Try<T>&& res) mutable {
52  // This will run from inside the gil, called by the asyncio add_reader
53  callback(std::move(res), userData);
54  // guard goes out of scope here, and its stored function is called
55  });
56 }
57 
58 template <typename T>
60  folly::Future<T>&& futureFrom,
61  folly::Function<void(folly::Try<T>&&, PyObject*)> callback,
62  PyObject* userData) {
64  getExecutor(), std::move(futureFrom), std::move(callback), userData);
65 }
66 
67 } // namespace python
68 } // namespace folly
folly::Executor * getExecutor()
Definition: futures.h:32
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
GuardImpl guard(ErrorHandler &&handler)
Definition: Base.h:840
Definition: Try.h:51
void bridgeFuture(folly::Executor *executor, folly::Future< T > &&futureFrom, folly::Function< void(folly::Try< T > &&, PyObject *)> callback, PyObject *userData)
Definition: futures.h:38
FOLLY_NODISCARD detail::ScopeGuardImplDecay< F, true > makeGuard(F &&f) noexcept(noexcept(detail::ScopeGuardImplDecay< F, true >(static_cast< F && >(f))))
Definition: ScopeGuard.h:184