Files
nitro/packages/react-native-nitro-modules/cpp/jsi/JSICache.hpp
T
2024-07-30 13:31:22 +02:00

151 lines
4.4 KiB
C++

//
// JSICache.hpp
// NitroModules
//
// Created by Marc Rousavy on 20.06.24.
//
#pragma once
#include <jsi/jsi.h>
#include <memory>
#include <vector>
#include <unordered_map>
#include <mutex>
#include "OwningReference.hpp"
#include "BorrowingReference.hpp"
#include "NitroLogger.hpp"
#include "GetRuntimeID.hpp"
namespace margelo::nitro {
using namespace facebook;
static constexpr auto CACHE_PROP_NAME = "__nitroModulesJSICache";
template<typename T>
class JSICache;
template<typename T>
class JSICacheReference final {
public:
JSICacheReference() = delete;
JSICacheReference(const JSICacheReference&) = delete;
JSICacheReference(JSICacheReference&&) = delete;
~JSICacheReference() {
_strongCache->_mutex.unlock();
}
public:
/**
Creates a reference to a `jsi::Value` that can be stored in memory and accessed later.
The `jsi::Value` will be managed by the `jsi::Runtime`, if the `jsi::Runtime` gets the destroyed,
so will the `jsi::Value`.
To access the `jsi::Value`, try to `.lock()` the `weak_ptr`.
If it can be locked, it is still valid, otherwise the Runtime has already been deleted.
Do not hold the returned `shared_ptr` in memory, only use it in the calling function's scope.
Note: By design, this is not thread-safe, the returned `weak_ptr` must only be locked on the same thread as it was created on.
*/
OwningReference<T> makeGlobal(T&& value) {
auto owning = OwningReference<T>(new T(std::move(value)));
_strongCache->_cache.push_back(owning.weak());
return owning;
}
private:
explicit JSICacheReference(const std::shared_ptr<JSICache<T>>& cache): _strongCache(cache) {
_strongCache->_mutex.lock();
}
private:
std::shared_ptr<JSICache<T>> _strongCache;
friend class JSICache<T>;
};
/**
* A `JSICache` can safely store `jsi::Pointer` instances (e.g. `jsi::Object` or
* `jsi::Function`) inside `OwningReference<T>`.
*
* `jsi::Pointer`s are managed by a `jsi::Runtime`, and will be deleted if the `jsi::Runtime`
* is deleted - even if there are still strong references to the `jsi::Pointer`.
*/
template<typename T = jsi::Pointer>
class JSICache final: public jsi::NativeState {
public:
explicit JSICache(jsi::Runtime* runtime) : _runtime(runtime) {}
~JSICache() {
std::unique_lock lock(_mutex);
for (auto& func : _cache) {
OwningReference<T> owning = func.lock();
if (owning) {
// Destroy all functions that we might still have in cache, some callbacks and Promises may now become invalid.
owning.destroy();
}
}
}
public:
JSICache() = delete;
JSICache(const JSICache&) = delete;
JSICache(JSICache&&) = delete;
public:
/**
Gets or creates a `JSICache` for the given `jsi::Runtime`.
The returned `shared_ptr` should not be stored in
If it can be locked, you can access data in the cache. Otherwise the Runtime has already been deleted.
Do not hold the returned `shared_ptr` in memory, only use it in the calling function's scope.
*/
[[nodiscard]]
static JSICacheReference<T> getOrCreateCache(jsi::Runtime& runtime) {
auto found = _globalCache.find(&runtime);
if (found != _globalCache.end()) {
// Fast path: get weak_ptr to JSICache from our global list.
std::weak_ptr<JSICache<T>> weak = found->second;
std::shared_ptr<JSICache<T>> strong = weak.lock();
if (strong) {
// It's still alive! Return it
return JSICacheReference<T>(strong);
}
}
// Cache doesn't exist yet.
Logger::log(TAG, "Creating new JSICache<T> for runtime %s..", getRuntimeId(runtime));
// Create new cache
auto nativeState = std::make_shared<JSICache<T>>(&runtime);
// Wrap it in a jsi::Value using NativeState
jsi::Object cache(runtime);
cache.setNativeState(runtime, nativeState);
// Inject it into the jsi::Runtime's global so it's memory is managed by it
runtime.global().setProperty(runtime, CACHE_PROP_NAME, std::move(cache));
// Add it to our map of caches
_globalCache[&runtime] = nativeState;
// Return it
return JSICacheReference<T>(nativeState);
}
public:
private:
friend class JSICacheReference<T>;
private:
jsi::Runtime* _runtime;
std::mutex _mutex;
std::vector<BorrowingReference<T>> _cache;
private:
static inline std::unordered_map<jsi::Runtime*, std::weak_ptr<JSICache<T>>> _globalCache;
private:
static constexpr auto TAG = "JSICache";
};
} // namespace margelo::nitro