File
Blob: src/workerd/io/promise-wrapper.h
| 1 | // Copyright (c) 2017-2022 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | #include <workerd/io/io-context.h> |
| 8 | #include <workerd/jsg/jsg.h> |
| 9 | |
| 10 | namespace workerd { |
| 11 | |
| 12 | template <typename Self> |
| 13 | class PromiseWrapper { |
| 14 | public: |
| 15 | template <typename T> |
| 16 | static constexpr const char* getName(kj::Promise<T>*) { |
| 17 | return "Promise"; |
| 18 | } |
| 19 | |
| 20 | // Explicitly disallow V8 handles, which are not safe for the KJ event loop to own directly. |
| 21 | template <typename T> |
| 22 | static constexpr const char* getName(kj::Promise<v8::Global<T>>*) = delete; |
| 23 | template <typename T> |
| 24 | static constexpr const char* getName(kj::Promise<v8::Local<T>>*) = delete; |
| 25 | |
| 26 | template <typename T> |
| 27 | static constexpr const char* getName(kj::Promise<jsg::Ref<T>>*) { |
| 28 | return "Promise"; |
| 29 | } |
| 30 | // For some reason, this wasn't needed for jsg::V8Ref<T>... |
| 31 | |
| 32 | template <typename T> |
| 33 | v8::Local<v8::Promise> wrap(jsg::Lock& js, |
| 34 | v8::Local<v8::Context> context, |
| 35 | kj::Maybe<v8::Local<v8::Object>> creator, |
| 36 | kj::Promise<T> promise) { |
| 37 | auto jsPromise = IoContext::current().awaitIoLegacy(js, kj::mv(promise)); |
| 38 | return static_cast<Self&>(*this).wrap(js, context, kj::mv(creator), kj::mv(jsPromise)); |
| 39 | } |
| 40 | |
| 41 | template <typename T> |
| 42 | kj::Maybe<kj::Promise<T>> tryUnwrap(jsg::Lock& js, |
| 43 | v8::Local<v8::Context> context, |
| 44 | v8::Local<v8::Value> handle, |
| 45 | kj::Promise<T>*, |
| 46 | kj::Maybe<v8::Local<v8::Object>> parentObject) { |
| 47 | auto& wrapper = static_cast<Self&>(*this); |
| 48 | auto jsPromise = KJ_UNWRAP_OR_RETURN( |
| 49 | wrapper.tryUnwrap(js, context, handle, (jsg::Promise<T>*)nullptr, parentObject), kj::none); |
| 50 | return IoContext::current().awaitJs(js, kj::mv(jsPromise)); |
| 51 | } |
| 52 | |
| 53 | template <typename T> |
| 54 | v8::Local<v8::Context> newContext(v8::Isolate* isolate, kj::Promise<T> value) = delete; |
| 55 | template <bool isContext = false, typename T> |
| 56 | v8::Local<v8::FunctionTemplate> getTemplate(v8::Isolate* isolate, kj::Promise<T>*) = delete; |
| 57 | }; |
| 58 | |
| 59 | } // namespace workerd |