forked from mirrors/gecko-dev
Started callback interface functionality to UniFFI. Currently this only
supports the async fire-and-forget use case, where Rust queues a JS
function to run, but doesn't wait (or `await`) for the response.
The basic system is:
- The JS code registers a callback interface handler with the C++
code. This handler is responsible for the specifics of invoking the
callback.
- The C++ code defines a function to call a JS handler. Once the JS
handler registers itself with C++, the C++ registers it's function
with Rust.
- The C++ code queues the call to the JS main thread.
- Because of how UniFFI handles callback interfaces, the C++ code can
be "dumb". UniFFI sends a object id, method id, and RustBuffer
encoding all arguments. This means C++ doesn't need to care about
the specific arguments, they get unpacked by JS.
I tried to keep the generated code as simple as possible by moving the
complexity to static code. For JS this meant writing a generic
`UniFFICallbackHandler` class in the static code that the generated code
constructs. For C++ this meant the generated code defines a
`UniFFIGetCallbackInterfaceInfo` function that returns a struct with all
the data specific to a callback interface (it's name, the UniFFI
scaffolding init function, etc). The static code can then define a
generic `QueueCallback` function that looks up the callback interface
info using the interface ID and then makes the call.
Allow UniFFI functions to run on the main thread rather than always
being dispatched to a worker thread. This allows us to test invoking
callback interfaces from the main thread thread. I don't think we will
use this much currently, since we don't want to block the main thread
for any significant amount of time. However, this will pair well with
the next step in the project which is async -- allowing async Rust
functions to call async JS functions. In that scenario, dispatching to
the worker thread is unnecessary.
Callback interface objects present a potential memory leak, since you
can easily create a cycle between a JS Callback object and a UniFFIed
Rust object, and the GC has no way of detecting it. To try to detect
these there's some shutdown code that checks that there are no callbacks
registered during shutdown and prevents any future callbacks from being
registered.
Added a `config.toml` file and code to parse it. This is needed to
specify which functions should run on the main thread.
Updated the git commits for the several UniFFI examples/fixtures.
Differential Revision: https://phabricator.services.mozilla.com/D156116
137 lines
4.7 KiB
C++
137 lines
4.7 KiB
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
|
|
/* vim:set ts=2 sw=2 sts=2 et cindent: */
|
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
|
|
|
#include "nsPrintfCString.h"
|
|
#include "nsString.h"
|
|
#include "nsThreadUtils.h"
|
|
#include "mozilla/dom/OwnedRustBuffer.h"
|
|
#include "mozilla/dom/RootedDictionary.h"
|
|
#include "mozilla/dom/UniFFIBinding.h"
|
|
#include "mozilla/dom/UniFFICallbacks.h"
|
|
#include "mozilla/Maybe.h"
|
|
#include "mozilla/Logging.h"
|
|
#include "mozilla/RefPtr.h"
|
|
|
|
static mozilla::LazyLogModule UNIFFI_INVOKE_CALLBACK_LOGGER("uniffi");
|
|
|
|
namespace mozilla::uniffi {
|
|
|
|
using dom::ArrayBuffer;
|
|
using dom::RootedDictionary;
|
|
using dom::UniFFICallbackHandler;
|
|
using dom::UniFFIScaffoldingCallCode;
|
|
|
|
static Maybe<CallbackInterfaceInfo> GetCallbackInterfaceInfo(
|
|
uint64_t aInterfaceId) {
|
|
const Maybe<CallbackInterfaceInfo> cbiInfo =
|
|
UniFFIGetCallbackInterfaceInfo(aInterfaceId);
|
|
#ifdef MOZ_UNIFFI_FIXTURES
|
|
if (!cbiInfo) {
|
|
return UniFFIFixturesGetCallbackInterfaceInfo(aInterfaceId);
|
|
}
|
|
#endif
|
|
return cbiInfo;
|
|
}
|
|
|
|
void RegisterCallbackHandler(uint64_t aInterfaceId,
|
|
UniFFICallbackHandler& aCallbackHandler,
|
|
ErrorResult& aError) {
|
|
// We should only be mutating mHandler on the main thread
|
|
MOZ_ASSERT(NS_IsMainThread());
|
|
|
|
Maybe<CallbackInterfaceInfo> cbiInfo = GetCallbackInterfaceInfo(aInterfaceId);
|
|
if (!cbiInfo.isSome()) {
|
|
aError.ThrowUnknownError(
|
|
nsPrintfCString("Unknown interface id: %" PRIu64, aInterfaceId));
|
|
return;
|
|
}
|
|
|
|
if (*cbiInfo->mHandler) {
|
|
MOZ_LOG(UNIFFI_INVOKE_CALLBACK_LOGGER, LogLevel::Error,
|
|
("[UniFFI] Callback handler already registered for %s",
|
|
cbiInfo->mName));
|
|
return;
|
|
}
|
|
*cbiInfo->mHandler = &aCallbackHandler;
|
|
RustCallStatus status = {0};
|
|
cbiInfo->mInitForeignCallback(cbiInfo->mForeignCallback, &status);
|
|
// Just use MOZ_DIAGNOSTIC_ASSERT to check the status, since the call should
|
|
// always succeed. The RustCallStatus out param only exists because UniFFI
|
|
// adds it to all FFI calls.
|
|
MOZ_DIAGNOSTIC_ASSERT(status.code == RUST_CALL_SUCCESS);
|
|
}
|
|
|
|
void DeregisterCallbackHandler(uint64_t aInterfaceId, ErrorResult& aError) {
|
|
// We should only be mutating mHandler on the main thread
|
|
MOZ_ASSERT(NS_IsMainThread());
|
|
|
|
Maybe<CallbackInterfaceInfo> cbiInfo = GetCallbackInterfaceInfo(aInterfaceId);
|
|
if (!cbiInfo.isSome()) {
|
|
aError.ThrowUnknownError(
|
|
nsPrintfCString("Unknown interface id: %" PRIu64, aInterfaceId));
|
|
return;
|
|
}
|
|
*cbiInfo->mHandler = nullptr;
|
|
}
|
|
|
|
MOZ_CAN_RUN_SCRIPT
|
|
static void QueueCallbackInner(uint64_t aInterfaceId, uint64_t aHandle,
|
|
uint32_t aMethod, OwnedRustBuffer aArgs) {
|
|
MOZ_ASSERT(NS_IsMainThread());
|
|
|
|
Maybe<CallbackInterfaceInfo> cbiInfo = GetCallbackInterfaceInfo(aInterfaceId);
|
|
if (!cbiInfo.isSome()) {
|
|
MOZ_LOG(UNIFFI_INVOKE_CALLBACK_LOGGER, LogLevel::Error,
|
|
("[UniFFI] Unknown inferface id: %" PRIu64, aInterfaceId));
|
|
return;
|
|
}
|
|
|
|
// Take our own reference to the callback handler to ensure that it stays
|
|
// alive for the duration of this call
|
|
RefPtr<UniFFICallbackHandler> ihandler = *cbiInfo->mHandler;
|
|
|
|
if (!ihandler) {
|
|
MOZ_LOG(UNIFFI_INVOKE_CALLBACK_LOGGER, LogLevel::Error,
|
|
("[UniFFI] JS handler for %s not registered", cbiInfo->mName));
|
|
return;
|
|
}
|
|
|
|
JSObject* global = ihandler->CallbackGlobalOrNull();
|
|
if (!global) {
|
|
MOZ_LOG(UNIFFI_INVOKE_CALLBACK_LOGGER, LogLevel::Error,
|
|
("[UniFFI] JS handler for %s has null global", cbiInfo->mName));
|
|
return;
|
|
}
|
|
|
|
dom::AutoEntryScript aes(global, cbiInfo->mName);
|
|
IgnoredErrorResult error;
|
|
JS::Rooted<JSObject*> args(aes.cx(), aArgs.IntoArrayBuffer(aes.cx()));
|
|
|
|
ihandler->Call(aHandle, aMethod, args, error);
|
|
|
|
if (error.Failed()) {
|
|
MOZ_LOG(UNIFFI_INVOKE_CALLBACK_LOGGER, LogLevel::Error,
|
|
("[UniFFI] Error invoking JS handler for %s", cbiInfo->mName));
|
|
return;
|
|
}
|
|
}
|
|
|
|
void QueueCallback(uint64_t aInterfaceId, uint64_t aHandle, uint32_t aMethod,
|
|
RustBuffer aArgs) {
|
|
nsresult dispatchResult =
|
|
GetMainThreadSerialEventTarget()->Dispatch(NS_NewRunnableFunction(
|
|
"UniFFI callback", [=]() MOZ_CAN_RUN_SCRIPT_BOUNDARY {
|
|
QueueCallbackInner(aInterfaceId, aHandle, aMethod,
|
|
OwnedRustBuffer(aArgs));
|
|
}));
|
|
|
|
if (NS_FAILED(dispatchResult)) {
|
|
MOZ_LOG(UNIFFI_INVOKE_CALLBACK_LOGGER, LogLevel::Error,
|
|
("[UniFFI] Error dispatching UniFFI callback task"));
|
|
}
|
|
}
|
|
|
|
} // namespace mozilla::uniffi
|