From c20db2bae6fe867db26ea6a4b350f13289d51bc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kasper=20Isager=20Dalsgar=C3=B0?= Date: Tue, 27 Oct 2026 21:50:18 +0100 Subject: [PATCH 1/4] Rework using Bare Kit v3 --- .github/workflows/publish.yml | 3 - .gitignore | 1 - CMakeLists.txt | 17 - README.md | 65 +- android/.npmignore | 1 - android/CMakeLists.txt | 11 +- android/build.gradle | 15 +- android/libs/.gitignore | 3 - android/libs/.npmignore | 1 - android/proguard-rules.pro | 3 + android/src/main/AndroidManifest.xml | 9 +- .../bare/kit/react/BareKitPackage.java | 5 - .../bare/kit/react/BareKitProvider.java | 56 ++ index.d.ts | 1 - index.js | 19 +- ios/.gitignore | 1 - ios/.npmignore | 1 - ios/BareKit.podspec | 19 - package.json | 1 - react-native-bare-kit.podspec | 2 +- shared/BareKitModule.cc | 565 +++++++----------- shared/BareKitModule.h | 4 +- shared/bare-kit.h | 250 ++++++++ specs/NativeBareKit.ts | 3 +- 24 files changed, 589 insertions(+), 467 deletions(-) delete mode 100644 CMakeLists.txt delete mode 100644 android/libs/.gitignore delete mode 100644 android/libs/.npmignore create mode 100644 android/proguard-rules.pro create mode 100644 android/src/main/java/to/holepunch/bare/kit/react/BareKitProvider.java delete mode 100644 ios/.gitignore delete mode 100644 ios/.npmignore delete mode 100644 ios/BareKit.podspec create mode 100644 shared/bare-kit.h diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b770958..75dd51d 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -14,7 +14,4 @@ jobs: name: Publish steps: - uses: holepunchto/actions/node-base@v1 - - run: npm install --global bare-make - - run: bare-make generate - - run: bare-make install --prefix . - uses: holepunchto/actions/publish@v1 diff --git a/.gitignore b/.gitignore index 900b9b3..009351a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -addons/ build/ node_modules/ package-lock.json diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 2762890..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -cmake_minimum_required(VERSION 4.0) - -find_package(cmake-fetch REQUIRED PATHS node_modules/cmake-fetch) - -project(react-native-bare-kit) - -fetch_package("https://github.com/holepunchto/bare-kit/releases/download/v2.5.4/prebuilds.zip" SOURCE_DIR bare-kit) - -install( - DIRECTORY "${bare-kit}/android/bare-kit" - DESTINATION android/libs -) - -install( - DIRECTORY "${bare-kit}/ios/BareKit.xcframework" - DESTINATION ios -) diff --git a/README.md b/README.md index c59d1e7..3f36699 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ npm i react-native-bare-kit ``` +Bare Kit isn't included. The application brings it along with the addons and assets of its worklets, so that other code, such as a notification service extension, can share them. See [Linking addons and assets](#linking-addons-and-assets). + ## Usage ```js @@ -15,10 +17,8 @@ import b4a from 'b4a' const worklet = new Worklet() const source = `\ -const { IPC } = BareKit - -IPC.on('data', (data) => console.log(data.toString())) -IPC.write(Buffer.from('Hello from Bare!')) +Bare.IPC.on('data', (data) => console.log(data.toString())) +Bare.IPC.write(Buffer.from('Hello from Bare!')) ` worklet.start('/app.js', source) @@ -29,56 +29,45 @@ IPC.on('data', (data) => console.log(b4a.toString(data))) IPC.write(b4a.from('Hello from React Native!')) ``` -Alternatively to load from a bundle: +Refer to for an example of using the library in an Expo application. -```js -import { Worklet } from 'react-native-bare-kit' +### Packing workers -// Bundle output by `bare-pack` -// Extension can be .bundle, .js, .cjs, .mjs -import bundle from './my.bundle.js' +Pack a worker and its dependencies into a package with and . The worker exports a `start()` function that receives the IPC stream: -const worklet = new Worklet() -// First arg (filename)'s extension *must* be .bundle -worklet.start('/app.bundle', source) +```js +module.exports = function start(ipc) { + ipc.on('data', (data) => ipc.write(data)) +} +``` -// [...] +```console +bare-stow pack --target react-native --out ./worker worker.js ``` -Refer to for an example of using the library in an Expo application. +Add the package as a dependency of the application and start the worker in a worklet: -### Linking native addons +```js +import worker from 'worker' -Native addons used by the worklet are not linked automatically. Applications must link them into their native projects themselves, such as by using . Given the entry point of the worklet, `bare-link` links the addons loaded by its module graph: +const { ipc } = await worker.start() -```console -bare-link --preset ios --out ios/addons worklet.js -bare-link --preset android --out android/app/src/main/jniLibs worklet.js +ipc.on('data', (data) => console.log(b4a.toString(data))) +ipc.write(b4a.from('Hello from React Native!')) ``` -On iOS, the resulting `.xcframework` bundles must be embedded in the application target. On Android, the resulting `.so` libraries must be included in the `jniLibs` of the application and the resulting `.jar` libraries, if any, added as dependencies. +The package leaves out the addons and assets of the worker, so link them as described below. + +### Linking addons and assets -As a convenience, the library includes designated directories that are already wired into its native projects. Any `.xcframework` bundle in `ios/addons` and any `.so` or `.jar` library in `android/src/main/addons` of the library will be included in the build without further configuration: +Link the addons and assets of all of the worklets of the application once with . It writes a Swift package and a Gradle module, which also bring along Bare Kit: ```console -bare-link --preset ios --out node_modules/react-native-bare-kit/ios/addons worklet.js -bare-link --preset android --out node_modules/react-native-bare-kit/android/src/main/addons worklet.js +bare-stow link --target bare-kit --language swift --out ios/BareKitResources worklet.js +bare-stow link --target bare-kit --language kotlin --language-option package=com.example.addons --out android/bare-kit-resources worklet.js ``` -As these directories live within `node_modules`, they are cleared whenever the library is reinstalled. Consider running the commands from a `postinstall` script of the application: - -```json -{ - "scripts": { - "postinstall": "npm run link:ios && npm run link:android", - "link:ios": "bare-link --preset ios --out node_modules/react-native-bare-kit/ios/addons worklet.js", - "link:android": "bare-link --preset android --out node_modules/react-native-bare-kit/android/src/main/addons worklet.js" - }, - "devDependencies": { - "bare-link": "^4.0.1" - } -} -``` +Add the Swift package and its `bare-stow` folder to the application target, and include the Gradle module in the application. In an Expo application, list the workers in the `workers` option of instead. ### Logging diff --git a/android/.npmignore b/android/.npmignore index 04e622d..173f0fa 100644 --- a/android/.npmignore +++ b/android/.npmignore @@ -1,4 +1,3 @@ .cxx/ build/ -addons/ libc++_shared.so diff --git a/android/CMakeLists.txt b/android/CMakeLists.txt index 79ad22a..e499cec 100644 --- a/android/CMakeLists.txt +++ b/android/CMakeLists.txt @@ -2,14 +2,6 @@ cmake_minimum_required(VERSION 3.22) project(react-native-bare-kit) -add_library(bare-kit SHARED IMPORTED) - -set_target_properties( - bare-kit - PROPERTIES - IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/libs/bare-kit/jni/${ANDROID_ABI}/libbare-kit.so" -) - add_library(react-native-bare-kit STATIC) set_target_properties( @@ -24,6 +16,7 @@ target_sources( PRIVATE ../shared/BareKitModule.cc ../shared/BareKitModule.h + ../shared/bare-kit.h ) target_include_directories( @@ -34,6 +27,6 @@ target_include_directories( target_link_libraries( react-native-bare-kit - bare-kit + fbjni::fbjni react_codegen_BareKitSpec ) diff --git a/android/build.gradle b/android/build.gradle index 50974b2..8656424 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -20,17 +20,12 @@ android { minSdk 29 targetSdk 34 - externalNativeBuild { - cmake { - arguments "-DANDROID_STL=c++_shared" - } - } + consumerProguardFiles "proguard-rules.pro" } sourceSets { main { manifest.srcFile "src/main/AndroidManifest.xml" - jniLibs.srcDirs "src/main/addons", "libs/bare-kit/jni" } } @@ -39,12 +34,6 @@ android { minifyEnabled false } } - - externalNativeBuild { - cmake { - path "CMakeLists.txt" - } - } } repositories { @@ -53,8 +42,6 @@ repositories { } dependencies { - api fileTree(dir: "libs", include: ["bare-kit/classes.jar"]) - api fileTree(dir: "src/main/addons", include: ["*.jar"]) implementation "com.facebook.react:react-native:+" } diff --git a/android/libs/.gitignore b/android/libs/.gitignore deleted file mode 100644 index 2f41fac..0000000 --- a/android/libs/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -* -!.gitignore -!.npmignore diff --git a/android/libs/.npmignore b/android/libs/.npmignore deleted file mode 100644 index 8b13789..0000000 --- a/android/libs/.npmignore +++ /dev/null @@ -1 +0,0 @@ - diff --git a/android/proguard-rules.pro b/android/proguard-rules.pro new file mode 100644 index 0000000..f71fd85 --- /dev/null +++ b/android/proguard-rules.pro @@ -0,0 +1,3 @@ +-keep class to.holepunch.bare.kit.react.BareKitProvider { + public static android.content.Context getApplicationContext(); +} diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml index 94cbbcf..186bc28 100644 --- a/android/src/main/AndroidManifest.xml +++ b/android/src/main/AndroidManifest.xml @@ -1 +1,8 @@ - + + + + + diff --git a/android/src/main/java/to/holepunch/bare/kit/react/BareKitPackage.java b/android/src/main/java/to/holepunch/bare/kit/react/BareKitPackage.java index e81af80..743c64e 100644 --- a/android/src/main/java/to/holepunch/bare/kit/react/BareKitPackage.java +++ b/android/src/main/java/to/holepunch/bare/kit/react/BareKitPackage.java @@ -11,11 +11,6 @@ public class BareKitPackage extends BaseReactPackage { public static String NAME = "BareKit"; - static { - // The library must be loaded from Java so JNI_OnLoad runs and captures the JVM. - System.loadLibrary("bare-kit"); - } - @Override public NativeModule getModule(String name, ReactApplicationContext context) { diff --git a/android/src/main/java/to/holepunch/bare/kit/react/BareKitProvider.java b/android/src/main/java/to/holepunch/bare/kit/react/BareKitProvider.java new file mode 100644 index 0000000..d7b1c6e --- /dev/null +++ b/android/src/main/java/to/holepunch/bare/kit/react/BareKitProvider.java @@ -0,0 +1,56 @@ +package to.holepunch.bare.kit.react; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; + +// Captures the application context at startup, as React Native never hands one +// to a C++ module, so that worklets can publish it to their native addons. +public class BareKitProvider extends ContentProvider { + private static Context applicationContext; + + public static Context + getApplicationContext() { + return applicationContext; + } + + @Override + public boolean + onCreate() { + applicationContext = getContext().getApplicationContext(); + + return false; + } + + @Override + public Cursor + query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { + return null; + } + + @Override + public String + getType(Uri uri) { + return null; + } + + @Override + public Uri + insert(Uri uri, ContentValues values) { + return null; + } + + @Override + public int + delete(Uri uri, String selection, String[] selectionArgs) { + return 0; + } + + @Override + public int + update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + return 0; + } +} diff --git a/index.d.ts b/index.d.ts index 6b8f56f..d17e64a 100644 --- a/index.d.ts +++ b/index.d.ts @@ -15,7 +15,6 @@ export interface WorkletEvents extends EventMap { export interface WorkletOptions { memoryLimit?: number - assets?: string } export class Worklet extends EventEmitter { diff --git a/index.js b/index.js index 7e7bd52..c8e55bd 100644 --- a/index.js +++ b/index.js @@ -54,7 +54,7 @@ class BareKitIPC extends Duplex { const data = NativeBareKit.read(this._worklet._handle) if (data) { - this.push(new Uint8Array(data)) + this.push(data.byteLength === 0 ? null : new Uint8Array(data)) cb(null) } else { this._pendingRead = cb @@ -71,12 +71,18 @@ class BareKitIPC extends Duplex { ) if (written === data.byteLength) cb(null) + else if (written < 0) cb(new Error('IPC has been closed')) else { this._pendingWrite = [data.subarray(written), cb] this._update() } } + _final(cb) { + NativeBareKit.end(this._worklet._handle) + cb(null) + } + _continueOpen(err) { if (this._pendingOpen === null) { if (err) this.destroy(err) @@ -117,7 +123,7 @@ class BareKitWorklet extends EventEmitter { throw new TypeError('ID must be a string. Received type ' + typeof id + ' (' + id + ')') } - const { memoryLimit = 0, assets = null } = opts + const { memoryLimit = 0 } = opts if (typeof memoryLimit !== 'number') { throw new TypeError( @@ -129,12 +135,6 @@ class BareKitWorklet extends EventEmitter { ) } - if (typeof assets !== 'string' && assets !== null) { - throw new TypeError( - 'Asset path must be a string. Received type ' + typeof assets + ' (' + assets + ')' - ) - } - super() this._state = 0 @@ -145,7 +145,6 @@ class BareKitWorklet extends EventEmitter { this._handle = NativeBareKit.init( id, memoryLimit, - assets, terminate, this._ipc._poll, this._onsuspend.bind(this), @@ -280,7 +279,7 @@ class BareKitWorklet extends EventEmitter { static wakeup(deadline) { for (const worklet of this._worklets) { - worklet.deadline(deadline) + worklet.wakeup(deadline) } } diff --git a/ios/.gitignore b/ios/.gitignore deleted file mode 100644 index 83d77ab..0000000 --- a/ios/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.xcframework diff --git a/ios/.npmignore b/ios/.npmignore deleted file mode 100644 index 61060c3..0000000 --- a/ios/.npmignore +++ /dev/null @@ -1 +0,0 @@ -addons/ diff --git a/ios/BareKit.podspec b/ios/BareKit.podspec deleted file mode 100644 index 7121b39..0000000 --- a/ios/BareKit.podspec +++ /dev/null @@ -1,19 +0,0 @@ -require "json" - -package = JSON.parse(File.read(File.join(__dir__, "../package.json"))) - -Pod::Spec.new do |s| - s.name = "BareKit" - s.version = package["version"] - s.summary = package["description"] - s.homepage = package["homepage"] - s.license = package["license"] - s.authors = package["author"] - - s.platforms = { :ios => min_ios_version_supported } - - s.source = { :git => package["repository"]["url"], :tag => "#{s.version}" } - - s.vendored_frameworks = "*.xcframework", "addons/*.xcframework" -end - diff --git a/package.json b/package.json index 63b6162..1bd6240 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,6 @@ "react-native": "*" }, "devDependencies": { - "cmake-fetch": "^1.4.9", "lunte": "^1.6.0", "prettier": "^3.3.3", "prettier-config-holepunch": "^2.0.0" diff --git a/react-native-bare-kit.podspec b/react-native-bare-kit.podspec index a4be2b0..6a0cbfd 100644 --- a/react-native-bare-kit.podspec +++ b/react-native-bare-kit.podspec @@ -16,7 +16,7 @@ Pod::Spec.new do |s| s.source_files = "ios/**/*.{h,mm}", "shared/**/*.{h,cc}" - s.vendored_frameworks = "ios/*.xcframework", "ios/addons/*.xcframework" + s.private_header_files = "shared/bare-kit.h" s.header_dir = "BareKit" diff --git a/shared/BareKitModule.cc b/shared/BareKitModule.cc index 0685f02..4e062df 100644 --- a/shared/BareKitModule.cc +++ b/shared/BareKitModule.cc @@ -6,165 +6,94 @@ #include #include -#include -#include +#include #include +#if defined(__ANDROID__) +#include +#endif + #include "BareKitModule.h" +#include "bare-kit.h" using namespace facebook::jsi; using namespace facebook::react; -extern "C" { -typedef struct uv_buf_t { - char *base; - size_t len; -} uv_buf_t; -} - namespace facebook::react { namespace { -static inline uv_buf_t -jsi_to_buffer(Runtime &rt, const ArrayBuffer &value) { - return {reinterpret_cast(value.data(rt)), value.size(rt)}; -} - -static inline uv_buf_t -jsi_to_buffer(Runtime &rt, const ArrayBuffer &value, size_t offset, size_t length) { - return {reinterpret_cast(value.data(rt)) + offset, length}; -} - -static inline uv_buf_t -jsi_to_buffer_owned(Runtime &rt, const String &value) { - auto utf8 = value.utf8(rt); - - return {strdup(utf8.c_str()), utf8.size()}; -} - -static inline char * -jsi_to_string_owned(Runtime &rt, const String &value) { - return strdup(value.utf8(rt).c_str()); -} - -} // namespace - -} // namespace facebook::react - -extern "C" { -typedef struct bare_s bare_t; -typedef struct bare_worklet_s bare_worklet_t; -typedef struct bare_worklet_options_s bare_worklet_options_t; -typedef struct bare_ipc_s bare_ipc_t; -typedef struct bare_ipc_poll_s bare_ipc_poll_t; - -typedef void (*bare_suspend_cb)(bare_t *, int linger, void *data); -typedef void (*bare_wakeup_cb)(bare_t *, int deadline, void *data); -typedef void (*bare_idle_cb)(bare_t *, void *data); -typedef void (*bare_resume_cb)(bare_t *, void *data); -typedef void (*bare_worklet_finalize_cb)(bare_worklet_t *, const uv_buf_t *source, void *finalize_hint); -typedef void (*bare_ipc_poll_cb)(bare_ipc_poll_t *, int events); - -struct bare_worklet_options_s { - size_t memory_limit; - const char *assets; -}; - -enum { - bare_ipc_readable = 0x1, - bare_ipc_writable = 0x2, -}; - -enum { - bare_ipc_would_block = -1, - bare_ipc_error = -2, -}; - -int -bare_worklet_alloc(bare_worklet_t **result); - -int -bare_worklet_init(bare_worklet_t *worklet, const bare_worklet_options_t *options); - -void -bare_worklet_destroy(bare_worklet_t *worklet); - -void * -bare_worklet_get_data(bare_worklet_t *worklet); - -void -bare_worklet_set_data(bare_worklet_t *worklet, void *data); - -int -bare_worklet_on_suspend(bare_worklet_t *worklet, bare_suspend_cb cb, void *data); - -int -bare_worklet_on_wakeup(bare_worklet_t *worklet, bare_wakeup_cb cb, void *data); - -int -bare_worklet_on_idle(bare_worklet_t *worklet, bare_idle_cb cb, void *data); - -int -bare_worklet_on_resume(bare_worklet_t *worklet, bare_resume_cb cb, void *data); - -int -bare_worklet_start(bare_worklet_t *worklet, const char *filename, const uv_buf_t *source, int argc, const char *argv[]); - -int -bare_worklet_suspend(bare_worklet_t *worklet, int linger); - -int -bare_worklet_resume(bare_worklet_t *worklet); - -int -bare_worklet_wakeup(bare_worklet_t *worklet, int deadline); - -int -bare_worklet_terminate(bare_worklet_t *worklet); - -int -bare_ipc_alloc(bare_ipc_t **result); - -int -bare_ipc_init(bare_ipc_t *ipc, bare_worklet_t *worklet); - -void -bare_ipc_destroy(bare_ipc_t *ipc); - -int -bare_ipc_read(bare_ipc_t *ipc, void **data, size_t *len); - -int -bare_ipc_write(bare_ipc_t *ipc, const void *data, size_t len); - -int -bare_ipc_poll_alloc(bare_ipc_poll_t **result); - -int -bare_ipc_poll_init(bare_ipc_poll_t *poll, bare_ipc_t *ipc); - -void -bare_ipc_poll_destroy(bare_ipc_poll_t *poll); - -void * -bare_ipc_poll_get_data(bare_ipc_poll_t *poll); - -void -bare_ipc_poll_set_data(bare_ipc_poll_t *poll, void *data); +// Bare Kit is brought along by the application, through bare-kit-swift or +// bare-kit-kotlin, so that the library is shared with any other code of the +// application that runs worklets. It is therefore resolved at runtime rather +// than linked. +#define BARE_KIT_FUNCTIONS(V) \ + V(bare_worklet_create) \ + V(bare_worklet_destroy) \ + V(bare_worklet_on_suspend) \ + V(bare_worklet_on_wakeup) \ + V(bare_worklet_on_idle) \ + V(bare_worklet_on_resume) \ + V(bare_worklet_on_exit) \ + V(bare_worklet_start) \ + V(bare_worklet_suspend) \ + V(bare_worklet_resume) \ + V(bare_worklet_wakeup) \ + V(bare_worklet_terminate) \ + V(bare_ipc_create) \ + V(bare_ipc_end) \ + V(bare_ipc_destroy) \ + V(bare_ipc_read) \ + V(bare_ipc_write) \ + V(bare_ipc_poll_create) \ + V(bare_ipc_poll_destroy) \ + V(bare_ipc_poll_get_data) \ + V(bare_ipc_poll_set_data) \ + V(bare_ipc_poll_start) \ + V(bare_ipc_poll_stop) + +static struct { +#define V(name) decltype(&::name) name; + BARE_KIT_FUNCTIONS(V) +#undef V +} kit; + +#if defined(__APPLE__) +static const char *bare_kit_library = "@rpath/BareKit.framework/BareKit"; +#else +static const char *bare_kit_library = "libbare-kit.so"; +#endif + +static void +load(Runtime &rt) { + static std::string error; + static std::once_flag loaded; + + std::call_once(loaded, [] { + void *handle = dlopen(bare_kit_library, RTLD_NOW | RTLD_LOCAL); + + if (handle == nullptr) { + error = dlerror(); + + return; + } -int -bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb); +#define V(name) \ + kit.name = reinterpret_cast(dlsym(handle, #name)); \ + if (kit.name == nullptr) { \ + error = "Missing symbol '" #name "'"; \ + return; \ + } + BARE_KIT_FUNCTIONS(V) +#undef V + }); -int -bare_ipc_poll_stop(bare_ipc_poll_t *poll); + if (!error.empty()) { + throw JSError(rt, "Bare Kit is not available, so make sure the application includes bare-kit-swift or bare-kit-kotlin (" + error + ")"); + } } -namespace facebook::react { - -namespace { - struct BareKitBuffer : MutableBuffer { BareKitBuffer(size_t len) : data_(len) {} @@ -178,10 +107,25 @@ struct BareKitBuffer : MutableBuffer { return data_.data(); } + void + resize(size_t len) { + data_.resize(len); + } + private: std::vector data_; }; +// The lifecycle callbacks of a worklet run on its thread and may still fire +// while it tears down after being destroyed, so they hold on to their own +// state until the worklet exits. +struct BareKitEvents { + AsyncCallback on_suspend; + AsyncCallback on_wakeup; + AsyncCallback<> on_idle; + AsyncCallback<> on_resume; +}; + struct BareKitWorklet : HostObject { bare_worklet_t *worklet = nullptr; bare_ipc_t *ipc = nullptr; @@ -189,10 +133,8 @@ struct BareKitWorklet : HostObject { AsyncCallback<> on_terminate; AsyncCallback on_poll; - AsyncCallback on_suspend; - AsyncCallback on_wakeup; - AsyncCallback<> on_idle; - AsyncCallback<> on_resume; + + std::shared_ptr events; bool started = false; bool terminated = false; @@ -205,8 +147,7 @@ struct BareKitWorklet : HostObject { BareKitWorklet( Runtime &rt, std::optional id, - int memoryLimit, - std::optional assets, + size_t memoryLimit, Function &&on_terminate, Function &&on_poll, Function &&on_suspend, @@ -217,208 +158,167 @@ struct BareKitWorklet : HostObject { ) : on_terminate(rt, std::move(on_terminate), jsInvoker), on_poll(rt, std::move(on_poll), jsInvoker), - on_suspend(rt, std::move(on_suspend), jsInvoker), - on_wakeup(rt, std::move(on_wakeup), jsInvoker), - on_idle(rt, std::move(on_idle), jsInvoker), - on_resume(rt, std::move(on_resume), jsInvoker) { + events(std::make_shared(BareKitEvents{ + AsyncCallback(rt, std::move(on_suspend), jsInvoker), + AsyncCallback(rt, std::move(on_wakeup), jsInvoker), + AsyncCallback<>(rt, std::move(on_idle), jsInvoker), + AsyncCallback<>(rt, std::move(on_resume), jsInvoker), + })) { int err; + load(rt); + if (id) this->id = id->utf8(rt); - err = bare_worklet_alloc(&worklet); - assert(err == 0); + bare_worklet_options_t options = {.version = 0, .memory_limit = memoryLimit}; - err = bare_ipc_alloc(&ipc); - assert(err == 0); +#if defined(__ANDROID__) + JNIEnv *env = facebook::jni::Environment::current(); - err = bare_ipc_poll_alloc(&poll); + JavaVM *vm; + err = env->GetJavaVM(&vm); assert(err == 0); - bare_ipc_poll_set_data(poll, this); + jobject context = nullptr; - bare_worklet_options_t options; + jclass provider = env->FindClass("to/holepunch/bare/kit/react/BareKitProvider"); - options.memory_limit = static_cast(memoryLimit); + if (provider != nullptr) { + jmethodID get_application_context = env->GetStaticMethodID(provider, "getApplicationContext", "()Landroid/content/Context;"); - if (assets) { - options.assets = jsi_to_string_owned(rt, assets.value()); - } else { - options.assets = nullptr; - } - - err = bare_worklet_init(worklet, &options); - assert(err == 0); + if (get_application_context != nullptr) context = env->CallStaticObjectMethod(provider, get_application_context); - err = bare_worklet_on_suspend(worklet, on_suspend_, this); - assert(err == 0); + env->DeleteLocalRef(provider); + } - err = bare_worklet_on_wakeup(worklet, on_wakeup_, this); - assert(err == 0); + if (context == nullptr) { + env->ExceptionClear(); - err = bare_worklet_on_idle(worklet, on_idle_, this); - assert(err == 0); + throw JSError(rt, "The application context could not be found"); + } - err = bare_worklet_on_resume(worklet, on_resume_, this); - assert(err == 0); + options.android.jvm = vm; + options.android.context = context; +#endif - free(const_cast(options.assets)); - } + err = kit.bare_worklet_create(&options, &worklet); - ~BareKitWorklet() { - terminate(); - } +#if defined(__ANDROID__) + env->DeleteLocalRef(context); +#endif - void - start() { - int err; + if (err < 0) throw JSError(rt, "Worklet could not be created"); - err = bare_ipc_init(ipc, worklet); + err = kit.bare_ipc_create(worklet, &ipc); assert(err == 0); - err = bare_ipc_poll_init(poll, ipc); + err = kit.bare_ipc_poll_create(ipc, &poll); assert(err == 0); - if (id) { - std::unique_lock guard(lock); - - auto previous = worklets[id.value()]; - - worklets[id.value()] = this; + kit.bare_ipc_poll_set_data(poll, this); + } - if (previous) { - previous->on_terminate.call([=](Runtime &rt, Function &function) { - function.call(rt); - }); - } - } + ~BareKitWorklet() { + terminate(); } void - start(Runtime &rt, Object handle, String filename, Array args) { + start(Runtime &rt, String filename, const void *source, size_t len, Array args) { int err; if (started || terminated) return; - started = true; + // Released once the worklet exits, which it only does once started. + auto data = new std::shared_ptr(events); - auto string = jsi_to_string_owned(rt, filename); - - auto argv = std::vector(args.size(rt)); - - for (size_t i = 0, n = argv.size(); i < n; i++) { - argv[i] = jsi_to_string_owned(rt, args.getValueAtIndex(rt, i).getString(rt)); - } - - err = bare_worklet_start(worklet, string, nullptr, argv.size(), argv.data()); + err = kit.bare_worklet_on_suspend(worklet, on_suspend_, data); assert(err == 0); - free(string); - - for (size_t i = 0, n = argv.size(); i < n; i++) { - free(const_cast(argv[i])); - } - - start(); - } - - void - start(Runtime &rt, Object handle, String filename, Object source, size_t offset, size_t length, Array args) { - int err; + err = kit.bare_worklet_on_wakeup(worklet, on_wakeup_, data); + assert(err == 0); - if (started || terminated) return; + err = kit.bare_worklet_on_idle(worklet, on_idle_, data); + assert(err == 0); - started = true; + err = kit.bare_worklet_on_resume(worklet, on_resume_, data); + assert(err == 0); - auto string = jsi_to_string_owned(rt, filename); + err = kit.bare_worklet_on_exit(worklet, on_exit_, data); + assert(err == 0); - auto buffer = jsi_to_buffer(rt, source.getArrayBuffer(rt), offset, length); + auto string = filename.utf8(rt); - auto argv = std::vector(args.size(rt)); + auto argv = std::vector(args.size(rt)); for (size_t i = 0, n = argv.size(); i < n; i++) { - argv[i] = jsi_to_string_owned(rt, args.getValueAtIndex(rt, i).getString(rt)); + argv[i] = args.getValueAtIndex(rt, i).getString(rt).utf8(rt); } - err = bare_worklet_start(worklet, string, &buffer, argv.size(), argv.data()); - assert(err == 0); - - free(string); + auto pointers = std::vector(argv.size()); - for (size_t i = 0, n = argv.size(); i < n; i++) { - free(const_cast(argv[i])); - } + std::transform(argv.begin(), argv.end(), pointers.begin(), [](const std::string &arg) { return arg.c_str(); }); - start(); - } + err = kit.bare_worklet_start(worklet, string.c_str(), source, len, int(pointers.size()), pointers.data()); - void - start(Runtime &rt, Object handle, String filename, String source, Array args) { - int err; + if (err < 0) { + delete data; - if (started || terminated) return; + throw JSError(rt, "Worklet could not be started"); + } started = true; - auto string = jsi_to_string_owned(rt, filename); - - auto buffer = jsi_to_buffer_owned(rt, source); - - auto argv = std::vector(args.size(rt)); - - for (size_t i = 0, n = argv.size(); i < n; i++) { - argv[i] = jsi_to_string_owned(rt, args.getValueAtIndex(rt, i).getString(rt)); - } - - err = bare_worklet_start(worklet, string, &buffer, argv.size(), argv.data()); - assert(err == 0); + if (id) { + std::unique_lock guard(lock); - free(buffer.base); + auto previous = worklets[id.value()]; - free(string); + worklets[id.value()] = this; - for (size_t i = 0, n = argv.size(); i < n; i++) { - free(const_cast(argv[i])); + if (previous) { + previous->on_terminate.call([=](Runtime &rt, Function &function) { + function.call(rt); + }); + } } - - start(); } std::optional - read(Runtime &rt, Object handle) { - int err; + read(Runtime &rt) { + if (terminated) return std::nullopt; - if (!started || terminated) return std::nullopt; + auto buffer = std::make_shared(BARE_IPC_READ_BUFFER_SIZE); - uint8_t *data; - size_t len; - err = bare_ipc_read(ipc, reinterpret_cast(&data), &len); - assert(err == 0 || err == bare_ipc_would_block); + int len = kit.bare_ipc_read(ipc, buffer->data(), buffer->size()); - if (err == bare_ipc_would_block) { - return std::nullopt; - } + if (len == bare_ipc_would_block) return std::nullopt; - auto buffer = std::make_shared(len); + assert(len >= 0); - std::copy(data, data + len, buffer->data()); + buffer->resize(size_t(len)); return ArrayBuffer(rt, buffer); } int - write(Runtime &rt, Object handle, Object data, size_t offset, size_t length) { - int err; + write(Runtime &rt, Object data, size_t offset, size_t length) { + if (terminated) return -1; - auto buffer = jsi_to_buffer(rt, data.getArrayBuffer(rt), offset, length); + auto base = data.getArrayBuffer(rt).data(rt) + offset; - err = bare_ipc_write(ipc, buffer.base, buffer.len); - assert(err >= 0 || err == bare_ipc_would_block); + int len = kit.bare_ipc_write(ipc, base, length); - if (err == bare_ipc_would_block) { - return 0; - } + if (len == bare_ipc_would_block) return 0; + if (len == bare_ipc_error) return -1; + + return len; + } + + void + end() { + if (terminated) return; - return err; + kit.bare_ipc_end(ipc); } void @@ -433,48 +333,37 @@ struct BareKitWorklet : HostObject { if (writable) events |= bare_ipc_writable; if (events) { - err = bare_ipc_poll_start(poll, events, on_poll_); + err = kit.bare_ipc_poll_start(poll, events, on_poll_); assert(err == 0); } else { - err = bare_ipc_poll_stop(poll); + err = kit.bare_ipc_poll_stop(poll); assert(err == 0); } } void suspend(int linger) { - int err; - - if (!started || terminated) return; + if (terminated) return; - err = bare_worklet_suspend(worklet, linger); - assert(err == 0); + kit.bare_worklet_suspend(worklet, linger); } void resume() { - int err; - - if (!started || terminated) return; + if (terminated) return; - err = bare_worklet_resume(worklet); - assert(err == 0); + kit.bare_worklet_resume(worklet); } void wakeup(int deadline) { - int err; - - if (!started || terminated) return; + if (terminated) return; - err = bare_worklet_wakeup(worklet, int(deadline)); - assert(err == 0); + kit.bare_worklet_wakeup(worklet, deadline); } void terminate() { - int err; - if (terminated) return; if (id) { @@ -487,20 +376,9 @@ struct BareKitWorklet : HostObject { terminated = true; - if (started) { - err = bare_worklet_terminate(worklet); - assert(err == 0); - - bare_ipc_poll_destroy(poll); - bare_ipc_destroy(ipc); - - free(ipc); - free(poll); - } - - bare_worklet_destroy(worklet); - - free(worklet); + kit.bare_ipc_poll_destroy(poll); + kit.bare_ipc_destroy(ipc); + kit.bare_worklet_destroy(worklet); worklet = nullptr; ipc = nullptr; @@ -510,48 +388,50 @@ struct BareKitWorklet : HostObject { private: static void on_poll_(bare_ipc_poll_t *poll, int events) { - auto worklet = static_cast(bare_ipc_poll_get_data(poll)); + auto worklet = static_cast(kit.bare_ipc_poll_get_data(poll)); worklet->on_poll.call([=](Runtime &rt, Function &function) { function.call(rt, (events & bare_ipc_readable) != 0, (events & bare_ipc_writable) != 0); }); } - static void - on_suspend_(bare_t *bare, int linger, void *data) { - auto worklet = static_cast(data); + static BareKitEvents & + events_from(void *data) { + return **static_cast *>(data); + } - worklet->on_suspend.call([=](Runtime &rt, Function &function) { + static void + on_suspend_(int linger, void *data) { + events_from(data).on_suspend.call([=](Runtime &rt, Function &function) { function.call(rt, linger); }); } static void - on_wakeup_(bare_t *bare, int deadline, void *data) { - auto worklet = static_cast(data); - - worklet->on_wakeup.call([=](Runtime &rt, Function &function) { + on_wakeup_(int deadline, void *data) { + events_from(data).on_wakeup.call([=](Runtime &rt, Function &function) { function.call(rt, deadline); }); } static void - on_idle_(bare_t *bare, void *data) { - auto worklet = static_cast(data); - - worklet->on_idle.call([=](Runtime &rt, Function &function) { + on_idle_(void *data) { + events_from(data).on_idle.call([=](Runtime &rt, Function &function) { function.call(rt); }); } static void - on_resume_(bare_t *bare, void *data) { - auto worklet = static_cast(data); - - worklet->on_resume.call([=](Runtime &rt, Function &function) { + on_resume_(void *data) { + events_from(data).on_resume.call([=](Runtime &rt, Function &function) { function.call(rt); }); } + + static void + on_exit_(int exit_code, void *data) { + delete static_cast *>(data); + } }; std::mutex BareKitWorklet::lock; @@ -567,7 +447,6 @@ BareKitModule::init( Runtime &rt, std::optional id, double memoryLimit, - std::optional assets, Function on_terminate, Function on_poll, Function on_suspend, @@ -578,8 +457,7 @@ BareKitModule::init( auto worklet = std::make_shared( rt, std::move(id), - int(memoryLimit), - std::move(assets), + size_t(memoryLimit), std::move(on_terminate), std::move(on_poll), std::move(on_suspend), @@ -603,35 +481,46 @@ void BareKitModule::startFile(Runtime &rt, Object handle, String filename, Array args) { auto worklet = handle.getHostObject(rt); - worklet->start(rt, std::move(handle), std::move(filename), std::move(args)); + worklet->start(rt, std::move(filename), nullptr, 0, std::move(args)); } void BareKitModule::startBytes(Runtime &rt, Object handle, String filename, Object source, double offset, double length, Array args) { auto worklet = handle.getHostObject(rt); - worklet->start(rt, std::move(handle), std::move(filename), std::move(source), size_t(offset), size_t(length), std::move(args)); + auto base = source.getArrayBuffer(rt).data(rt) + size_t(offset); + + worklet->start(rt, std::move(filename), base, size_t(length), std::move(args)); } void BareKitModule::startUTF8(Runtime &rt, Object handle, String filename, String source, Array args) { auto worklet = handle.getHostObject(rt); - worklet->start(rt, std::move(handle), std::move(filename), std::move(source), std::move(args)); + auto utf8 = source.utf8(rt); + + worklet->start(rt, std::move(filename), utf8.data(), utf8.size(), std::move(args)); } std::optional BareKitModule::read(Runtime &rt, Object handle) { auto worklet = handle.getHostObject(rt); - return worklet->read(rt, std::move(handle)); + return worklet->read(rt); } double BareKitModule::write(Runtime &rt, Object handle, Object data, double offset, double length) { auto worklet = handle.getHostObject(rt); - return double(worklet->write(rt, std::move(handle), std::move(data), size_t(offset), size_t(length))); + return double(worklet->write(rt, std::move(data), size_t(offset), size_t(length))); +} + +void +BareKitModule::end(Runtime &rt, Object handle) { + auto worklet = handle.getHostObject(rt); + + worklet->end(); } void diff --git a/shared/BareKitModule.h b/shared/BareKitModule.h index 65aa261..a48590c 100644 --- a/shared/BareKitModule.h +++ b/shared/BareKitModule.h @@ -16,7 +16,6 @@ class BareKitModule : public NativeBareKitCxxSpec { jsi::Runtime &rt, std::optional id, double memoryLimit, - std::optional assets, jsi::Function on_terminate, jsi::Function on_poll, jsi::Function on_suspend, @@ -43,6 +42,9 @@ class BareKitModule : public NativeBareKitCxxSpec { double write(jsi::Runtime &rt, jsi::Object handle, jsi::Object data, double offset, double length); + void + end(jsi::Runtime &rt, jsi::Object handle); + void suspend(jsi::Runtime &rt, jsi::Object handle, double linger); diff --git a/shared/bare-kit.h b/shared/bare-kit.h new file mode 100644 index 0000000..fe55221 --- /dev/null +++ b/shared/bare-kit.h @@ -0,0 +1,250 @@ +#ifndef BARE_KIT_H +#define BARE_KIT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +typedef struct bare_worklet_s bare_worklet_t; +typedef struct bare_worklet_options_s bare_worklet_options_t; +typedef struct bare_ipc_s bare_ipc_t; +typedef struct bare_ipc_poll_s bare_ipc_poll_t; + +typedef void (*bare_worklet_suspend_cb)(int linger, void *data); +typedef void (*bare_worklet_wakeup_cb)(int deadline, void *data); +typedef void (*bare_worklet_idle_cb)(void *data); +typedef void (*bare_worklet_resume_cb)(void *data); +typedef void (*bare_worklet_exit_cb)(int exit_code, void *data); +typedef void (*bare_ipc_poll_cb)(bare_ipc_poll_t *, int events); + +#define BARE_IPC_READ_BUFFER_SIZE (64 * 1024) + +enum { + bare_ipc_readable = 0x1, + bare_ipc_writable = 0x2, +}; + +enum { + bare_ipc_would_block = -1, + bare_ipc_error = -2, +}; + +/** @version 0 */ +struct bare_worklet_options_s { + int version; + + /** + * The memory limit of each JavaScript heap. By default, the limit will be + * inferred based on the amount of physical memory of the device. + * + * Note that the limit applies individually to each thread, including the + * main thread. + * + * @since 0 + */ + size_t memory_limit; + + /** + * Options that only apply on Android, and are ignored on other platforms. + * + * @since 0 + */ + struct { + /** + * The Java virtual machine, as a `JavaVM *`, which is published to the + * addons of the worklet under `bare.android.jvm.v1`. By default, the virtual + * machine that loaded Bare Kit through `JNI_OnLoad()` is used, so it must be + * given if Bare Kit is loaded by other means. There is only one per process. + */ + void *jvm; + + /** + * The application context, as a JNI reference to an `android.content.Context`, + * which is published to the addons of the worklet under + * `bare.android.context.v1`. The worklet takes a global reference of its + * own, so the reference need only be valid for the call. + */ + void *context; + } android; +}; + +/** + * Enable trade-off of performance for memory. Must be configured before + * starting the first worklet. + */ +int +bare_worklet_optimize_for_memory(bool enabled); + +/** + * Tear down the state shared by the worklets of the process. Every worklet must + * have been terminated or destroyed first, and those still tearing down are + * waited for. Must be called at most once, after which starting a worklet + * fails. A host that runs worklets for as long as it lives need not call it. + */ +int +bare_worklet_teardown(void); + +/** + * Create a worklet. The options are copied and may be `NULL`. On Android, the + * calling thread must be attached to the JVM if an application context is + * given. + */ +int +bare_worklet_create(const bare_worklet_options_t *options, bare_worklet_t **result); + +/** + * Terminate the worklet if it is still running and hand it over to tear itself + * down, without blocking. The worklet must not be used afterwards, but its ipc + * may be destroyed before or after it. + */ +void +bare_worklet_destroy(bare_worklet_t *worklet); + +/** + * Lifecycle callbacks, called on the worklet thread. They must be configured + * before starting the worklet. + */ +int +bare_worklet_on_suspend(bare_worklet_t *worklet, bare_worklet_suspend_cb cb, void *data); + +int +bare_worklet_on_wakeup(bare_worklet_t *worklet, bare_worklet_wakeup_cb cb, void *data); + +int +bare_worklet_on_idle(bare_worklet_t *worklet, bare_worklet_idle_cb cb, void *data); + +int +bare_worklet_on_resume(bare_worklet_t *worklet, bare_worklet_resume_cb cb, void *data); + +/** + * Called exactly once on the worklet thread with the exit code of the worklet + * once it has torn down, whether it exited on its own, was terminated, or was + * destroyed, so `data` must be kept until then. An ipc of the worklet has + * reached end-of-stream by then. + */ +int +bare_worklet_on_exit(bare_worklet_t *worklet, bare_worklet_exit_cb cb, void *data); + +void * +bare_worklet_get_data(bare_worklet_t *worklet); + +void +bare_worklet_set_data(bare_worklet_t *worklet, void *data); + +/** + * Start the worklet on a thread of its own, running `filename` with `argv` as + * `Bare.argv`. If `source` is `NULL`, the contents of `filename` will instead + * be read at runtime. The arguments need only remain valid until this function + * returns. + * + * In an application, a relative `filename` names a resource of the application. + * On Apple platforms, it resolves against the resources of the application + * bundle, which for an application extension is the bundle that contains it. + * On Android, where resources live in the APK, it resolves against the code + * cache directory of the application context, which must then be given. The + * resources listed in `.assets`, one `/` per line, are extracted to + * `/` before `.bundle` first runs, and the bundle itself is + * read from the APK if `source` is `NULL`. + */ +int +bare_worklet_start(bare_worklet_t *worklet, const char *filename, const void *source, size_t len, int argc, const char *argv[]); + +/** + * Suspending, resuming, waking up, or terminating a worklet that has not + * started or has torn down is a no-op. + */ +int +bare_worklet_suspend(bare_worklet_t *worklet, int linger); + +int +bare_worklet_resume(bare_worklet_t *worklet); + +int +bare_worklet_wakeup(bare_worklet_t *worklet, int deadline); + +int +bare_worklet_terminate(bare_worklet_t *worklet); + +/** + * Create the host end of the ipc of a worklet, which is exposed as `Bare.IPC` + * in the worklet. Fails if the worklet already has an ipc or has been + * terminated. + */ +int +bare_ipc_create(bare_worklet_t *worklet, bare_ipc_t **result); + +/** + * Close the host end, after which reads return end-of-stream and writes fail. + * Closing twice is a no-op. + */ +void +bare_ipc_close(bare_ipc_t *ipc); + +/** + * End the host end, a half-close after which `Bare.IPC` in the worklet reads + * end-of-stream once drained, while the host keeps reading. Writes fail + * afterwards. Ending twice, or after closing, is a no-op. + */ +void +bare_ipc_end(bare_ipc_t *ipc); + +/** + * Close and free the ipc. May be called before or after `bare_worklet_destroy()`, + * and from a poll callback of the ipc itself. + */ +void +bare_ipc_destroy(bare_ipc_t *ipc); + +/** + * Read up to `len` bytes, which must not be 0, into `data`. Returns the number + * of bytes read, 0 at end-of-stream, or `bare_ipc_would_block`. + */ +int +bare_ipc_read(bare_ipc_t *ipc, void *data, size_t len); + +/** + * Write `len` bytes from `data`. Returns the number of bytes written, + * `bare_ipc_would_block` if there is no room, or `bare_ipc_error` once the ipc + * is closed. + */ +int +bare_ipc_write(bare_ipc_t *ipc, const void *data, size_t len); + +/** + * Create a poll of the ipc, which calls back when it becomes readable or + * writable. Callbacks run on a thread owned by the ipc, which on Android is + * attached to the JVM, and may stop or destroy the poll or its ipc. + */ +int +bare_ipc_poll_create(bare_ipc_t *ipc, bare_ipc_poll_t **result); + +void +bare_ipc_poll_destroy(bare_ipc_poll_t *poll); + +void * +bare_ipc_poll_get_data(bare_ipc_poll_t *poll); + +void +bare_ipc_poll_set_data(bare_ipc_poll_t *poll, void *data); + +bare_ipc_t * +bare_ipc_poll_get_ipc(bare_ipc_poll_t *poll); + +/** + * Start polling for `events`. Polls are level-triggered, so the callback is + * called again for as long as the events remain ready. + */ +int +bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb); + +int +bare_ipc_poll_stop(bare_ipc_poll_t *poll); + +#ifdef __cplusplus +} +#endif + +#endif // BARE_KIT_H diff --git a/specs/NativeBareKit.ts b/specs/NativeBareKit.ts index 41e72f0..b85778a 100644 --- a/specs/NativeBareKit.ts +++ b/specs/NativeBareKit.ts @@ -5,7 +5,6 @@ export interface Spec extends TurboModule { init( id: string | null, memoryLimit: number, - assets: string | null, onterminate: () => void, onpoll: (readable: boolean, writable: boolean) => void, onsuspend: (linger: number) => void, @@ -33,6 +32,8 @@ export interface Spec extends TurboModule { write(handle: Object, data: Object, offset: number, length: number): number + end(handle: Object): void + suspend(handle: Object, linger: number): void resume(handle: Object): void From bd3d0a82943247b2f028adffb1df4ac566de125a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kasper=20Isager=20Dalsgar=C3=B0?= Date: Thu, 29 Oct 2026 12:10:07 +0100 Subject: [PATCH 2/4] Update headers --- shared/BareKitModule.cc | 4 +-- shared/bare-kit.h | 58 ++++++++++++++++++++++++----------------- 2 files changed, 36 insertions(+), 26 deletions(-) diff --git a/shared/BareKitModule.cc b/shared/BareKitModule.cc index 4e062df..dee7751 100644 --- a/shared/BareKitModule.cc +++ b/shared/BareKitModule.cc @@ -197,8 +197,8 @@ struct BareKitWorklet : HostObject { throw JSError(rt, "The application context could not be found"); } - options.android.jvm = vm; - options.android.context = context; + options.platform.android.jvm = vm; + options.platform.android.context = context; #endif err = kit.bare_worklet_create(&options, &worklet); diff --git a/shared/bare-kit.h b/shared/bare-kit.h index fe55221..2fb826e 100644 --- a/shared/bare-kit.h +++ b/shared/bare-kit.h @@ -48,27 +48,38 @@ struct bare_worklet_options_s { size_t memory_limit; /** - * Options that only apply on Android, and are ignored on other platforms. + * Options that are specific to a platform. Only the member of the platform + * that the worklet runs on is read. The size of the union is fixed by + * `reserved`, so that fields added to the end of the options keep their + * offsets as the members of the union grow. * * @since 0 */ - struct { + union { /** - * The Java virtual machine, as a `JavaVM *`, which is published to the - * addons of the worklet under `bare.android.jvm.v1`. By default, the virtual - * machine that loaded Bare Kit through `JNI_OnLoad()` is used, so it must be - * given if Bare Kit is loaded by other means. There is only one per process. + * Options that apply on Android. */ - void *jvm; - - /** - * The application context, as a JNI reference to an `android.content.Context`, - * which is published to the addons of the worklet under - * `bare.android.context.v1`. The worklet takes a global reference of its - * own, so the reference need only be valid for the call. - */ - void *context; - } android; + struct { + /** + * The Java virtual machine, as a `JavaVM *`, which is published to the + * addons of the worklet under `bare.android.jvm.v1`. By default, the + * virtual machine that loaded Bare Kit through `JNI_OnLoad()` is used, so + * it must be given if Bare Kit is loaded by other means. There is only one + * per process. + */ + void *jvm; + + /** + * The application context, as a JNI reference to an + * `android.content.Context`, which is published to the addons of the + * worklet under `bare.android.context.v1`. The worklet takes a global + * reference of its own, so the reference need only be valid for the call. + */ + void *context; + } android; + + void *reserved[8]; + } platform; }; /** @@ -140,14 +151,13 @@ bare_worklet_set_data(bare_worklet_t *worklet, void *data); * be read at runtime. The arguments need only remain valid until this function * returns. * - * In an application, a relative `filename` names a resource of the application. - * On Apple platforms, it resolves against the resources of the application - * bundle, which for an application extension is the bundle that contains it. - * On Android, where resources live in the APK, it resolves against the code - * cache directory of the application context, which must then be given. The - * resources listed in `.assets`, one `/` per line, are extracted to - * `/` before `.bundle` first runs, and the bundle itself is - * read from the APK if `source` is `NULL`. + * A relative `filename` names a resource of the application. On Apple + * platforms, it resolves against the resources of the application bundle, + * which extensions share with their application. On Android, it resolves + * against the code cache directory of the application context, which must then + * be given. The resources listed in `.assets`, one `/` per line, + * are extracted there from `/` in the APK before `.bundle` + * first runs, and a `NULL` source is read from the APK. */ int bare_worklet_start(bare_worklet_t *worklet, const char *filename, const void *source, size_t len, int argc, const char *argv[]); From 9add5f10977083dc1d7a929ae9e884e70ea6b31d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kasper=20Isager=20Dalsgar=C3=B0?= Date: Thu, 29 Oct 2026 13:02:34 +0100 Subject: [PATCH 3/4] Update header --- shared/bare-kit.h | 77 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 69 insertions(+), 8 deletions(-) diff --git a/shared/bare-kit.h b/shared/bare-kit.h index 2fb826e..33b9ec4 100644 --- a/shared/bare-kit.h +++ b/shared/bare-kit.h @@ -64,8 +64,8 @@ struct bare_worklet_options_s { * The Java virtual machine, as a `JavaVM *`, which is published to the * addons of the worklet under `bare.android.jvm.v1`. By default, the * virtual machine that loaded Bare Kit through `JNI_OnLoad()` is used, so - * it must be given if Bare Kit is loaded by other means. There is only one - * per process. + * it must be given if Bare Kit is loaded by other means. There is only + * one per process. */ void *jvm; @@ -114,19 +114,33 @@ bare_worklet_create(const bare_worklet_options_t *options, bare_worklet_t **resu void bare_worklet_destroy(bare_worklet_t *worklet); +// Lifecycle callbacks, called on the worklet thread. They must be configured +// before starting the worklet. + /** - * Lifecycle callbacks, called on the worklet thread. They must be configured - * before starting the worklet. + * Called when the worklet suspends, with the number of milliseconds that it + * lingers for before going idle. */ int bare_worklet_on_suspend(bare_worklet_t *worklet, bare_worklet_suspend_cb cb, void *data); +/** + * Called when a suspended worklet wakes up, with the number of milliseconds + * that it has to perform background work before going idle again. + */ int bare_worklet_on_wakeup(bare_worklet_t *worklet, bare_worklet_wakeup_cb cb, void *data); +/** + * Called when a suspended worklet goes idle, after which it does no work until + * it is resumed or woken up. + */ int bare_worklet_on_idle(bare_worklet_t *worklet, bare_worklet_idle_cb cb, void *data); +/** + * Called when a suspended worklet resumes. + */ int bare_worklet_on_resume(bare_worklet_t *worklet, bare_worklet_resume_cb cb, void *data); @@ -139,9 +153,17 @@ bare_worklet_on_resume(bare_worklet_t *worklet, bare_worklet_resume_cb cb, void int bare_worklet_on_exit(bare_worklet_t *worklet, bare_worklet_exit_cb cb, void *data); +/** + * Get the data that was associated with the worklet by + * `bare_worklet_set_data()`. + */ void * bare_worklet_get_data(bare_worklet_t *worklet); +/** + * Associate `data` with the worklet, for the host to retrieve with + * `bare_worklet_get_data()`. The worklet does not use it. + */ void bare_worklet_set_data(bare_worklet_t *worklet, void *data); @@ -162,19 +184,38 @@ bare_worklet_set_data(bare_worklet_t *worklet, void *data); int bare_worklet_start(bare_worklet_t *worklet, const char *filename, const void *source, size_t len, int argc, const char *argv[]); +// Suspending, resuming, waking up, or terminating a worklet is safe from any +// thread, and is a no-op if the worklet has not started or has torn down. + /** - * Suspending, resuming, waking up, or terminating a worklet that has not - * started or has torn down is a no-op. + * Suspend the worklet, which lingers for `linger` milliseconds before going + * idle. A negative `linger` lingers for 30 seconds. On iOS, the worklet holds a + * background task for as long as it lingers, so `linger` is capped by the + * background time remaining to the application, which a negative `linger` + * lingers for instead. */ int bare_worklet_suspend(bare_worklet_t *worklet, int linger); +/** + * Resume the worklet. If it has not yet gone idle, the suspension is + * cancelled. + */ int bare_worklet_resume(bare_worklet_t *worklet); +/** + * Wake up a suspended worklet and give it `deadline` milliseconds to perform + * background work before going idle again. A negative `deadline`, and the cap + * on iOS, are handled as for the `linger` of `bare_worklet_suspend()`. + */ int bare_worklet_wakeup(bare_worklet_t *worklet, int deadline); +/** + * Terminate the worklet as soon as possible. The exit callback is called once + * it has torn down. + */ int bare_worklet_terminate(bare_worklet_t *worklet); @@ -231,25 +272,45 @@ bare_ipc_write(bare_ipc_t *ipc, const void *data, size_t len); int bare_ipc_poll_create(bare_ipc_t *ipc, bare_ipc_poll_t **result); +/** + * Stop and free the poll. If its callback is running on another thread, this + * waits for the callback to return. May be called from the callback itself. + */ void bare_ipc_poll_destroy(bare_ipc_poll_t *poll); +/** + * Get the data that was associated with the poll by + * `bare_ipc_poll_set_data()`. + */ void * bare_ipc_poll_get_data(bare_ipc_poll_t *poll); +/** + * Associate `data` with the poll, for the host to retrieve with + * `bare_ipc_poll_get_data()`, such as from the callback. + */ void bare_ipc_poll_set_data(bare_ipc_poll_t *poll, void *data); +/** + * Get the ipc that the poll was created for. + */ bare_ipc_t * bare_ipc_poll_get_ipc(bare_ipc_poll_t *poll); /** - * Start polling for `events`. Polls are level-triggered, so the callback is - * called again for as long as the events remain ready. + * Start polling for `events`, replacing the events and callback of a poll that + * is already started. Polls are level-triggered, so the callback is called + * again for as long as the events remain ready. */ int bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb); +/** + * Stop polling, after which the callback is no longer called. Starting a poll + * with no `events` stops it too. + */ int bare_ipc_poll_stop(bare_ipc_poll_t *poll); From d5b1e068584f8202e2185f5ff11d024957fac81a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kasper=20Isager=20Dalsgar=C3=B0?= Date: Mon, 2 Nov 2026 10:01:35 +0100 Subject: [PATCH 4/4] Reset event reference on termination --- shared/BareKitModule.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/shared/BareKitModule.cc b/shared/BareKitModule.cc index dee7751..8a112d2 100644 --- a/shared/BareKitModule.cc +++ b/shared/BareKitModule.cc @@ -383,6 +383,8 @@ struct BareKitWorklet : HostObject { worklet = nullptr; ipc = nullptr; poll = nullptr; + + events.reset(); } private: