Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor JSClosure to leverage FinalizationRegistry #128

Merged
merged 7 commits into from
Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,5 @@ class Benchmark {
return .undefined
}
runner("\(title)/\(name)", jsBody)
jsBody.release()
}
}
49 changes: 21 additions & 28 deletions IntegrationTests/TestSuites/Sources/PrimaryTests/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -191,36 +191,36 @@ try test("Closure Lifetime") {
return arguments[0]
}
try expectEqual(evalClosure(c1, JSValue.number(1.0)), .number(1.0))
c1.release()
}

do {
let c1 = JSClosure { arguments in
return arguments[0]
}
let c1 = JSClosure { _ in .undefined }
c1.release()
c1.release()
// Call a released closure
_ = try expectThrow(try evalClosure.throws(c1))
}

do {
let c1 = JSClosure { _ in
// JSClosure will be deallocated before `release()`
_ = JSClosure { _ in .undefined }
return .undefined
}
_ = try expectThrow(try evalClosure.throws(c1))
c1.release()
let array = JSObject.global.Array.function!.new()
_ = array.push!(JSClosure { _ in .number(3) })
try expectEqual(array[0].function!().number, 3.0)
}

// do {
// let weakRef = { () -> JSObject in
// let c1 = JSClosure { _ in .undefined }
// return JSObject.global.WeakRef.function!.new(c1)
// }()
//
// // unsure if this will actually work since GC may not run immediately
// try expectEqual(weakRef.deref!(), .undefined)
// }

do {
let c1 = JSOneshotClosure { _ in
return .boolean(true)
}
try expectEqual(evalClosure(c1), .boolean(true))
// second call will cause `fatalError` that can be caught as a JavaScript exception
_ = try expectThrow(try evalClosure.throws(c1))
// OneshotClosure won't call fatalError even if it's deallocated before `release`
try expectEqual(evalClosure(c1), .boolean(true))
}
}

Expand Down Expand Up @@ -253,8 +253,6 @@ try test("Host Function Registration") {
try expectEqual(call_host_1Func(), .number(1))
try expectEqual(isHostFunc1Called, true)

hostFunc1.release()

let hostFunc2 = JSClosure { (arguments) -> JSValue in
do {
let input = try expectNumber(arguments[0])
Expand All @@ -266,7 +264,6 @@ try test("Host Function Registration") {

try expectEqual(evalClosure(hostFunc2, 3), .number(6))
_ = try expectString(evalClosure(hostFunc2, true))
hostFunc2.release()
}

try test("New Object Construction") {
Expand Down Expand Up @@ -375,19 +372,14 @@ try test("ObjectRef Lifetime") {
// }
// ```

let identity = JSClosure { $0[0] }
let ref1 = getJSValue(this: .global, name: "globalObject1").object!
let ref2 = evalClosure(identity, ref1).object!
let ref2 = evalClosure(JSClosure { $0[0] }, ref1).object!
try expectEqual(ref1.prop_2, .number(2))
try expectEqual(ref2.prop_2, .number(2))
identity.release()
}

func closureScope() -> ObjectIdentifier {
let closure = JSClosure { _ in .undefined }
let result = ObjectIdentifier(closure)
closure.release()
return result
ObjectIdentifier(JSClosure { _ in .undefined })
}

try test("Closure Identifiers") {
Expand Down Expand Up @@ -513,7 +505,7 @@ try test("Timer") {
interval = JSTimer(millisecondsDelay: 5, isRepeating: true) {
// ensure that JSTimer is living
try! expectNotNil(interval)
// verify that at least `timeoutMilliseconds * count` passed since the `timeout`
// verify that at least `timeoutMilliseconds * count` passed since the `timeout`
// timer started
try! expectEqual(start + timeoutMilliseconds * count <= JSDate().valueOf(), true)

Expand Down Expand Up @@ -549,7 +541,8 @@ try test("Promise") {
exp1.fulfill()
return JSValue.undefined
}
.catch { _ -> JSValue in
.catch { err -> JSValue in
print(err.object!.stack.string!)
fatalError("Not fired due to no throw")
}
.finally { exp1.fulfill() }
Expand Down
19 changes: 17 additions & 2 deletions Runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ interface SwiftRuntimeExportedFunctions {
argc: number,
callback_func_ref: ref
): void;

swjs_free_host_function(host_func_id: number): void;
}

enum JavaScriptValueKind {
Expand Down Expand Up @@ -118,11 +120,22 @@ class SwiftRuntimeHeap {
export class SwiftRuntime {
private instance: WebAssembly.Instance | null;
private heap: SwiftRuntimeHeap;
private functionRegistry: FinalizationRegistry;
private version: number = 701;

constructor() {
this.instance = null;
this.heap = new SwiftRuntimeHeap();
this.functionRegistry = new FinalizationRegistry(
this.handleFree.bind(this)
);
}

handleFree(id: unknown) {
if (!this.instance || typeof id !== "number") return;
const exports = (this.instance
.exports as any) as SwiftRuntimeExportedFunctions;
exports.swjs_free_host_function(id);
}

setInstance(instance: WebAssembly.Instance) {
Expand Down Expand Up @@ -452,12 +465,14 @@ export class SwiftRuntime {
host_func_id: number,
func_ref_ptr: pointer
) => {
const func_ref = this.heap.retain(function () {
const func = function () {
return callHostFunction(
host_func_id,
Array.prototype.slice.call(arguments)
);
});
};
const func_ref = this.heap.retain(func);
this.functionRegistry.register(func, func_ref);
writeUint32(func_ref_ptr, func_ref);
},
swjs_call_throwing_new: (
Expand Down
1 change: 1 addition & 0 deletions Runtime/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"rootDir": "src",
"strict": true,
"target": "es2017",
"lib": ["es2017", "DOM", "ESNext.WeakRef"],
"skipLibCheck": true
},
"include": ["src/**/*"],
Expand Down
3 changes: 3 additions & 0 deletions Sources/JavaScriptKit/Deprecated.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,6 @@ public typealias JSValueConstructible = ConstructibleFromJSValue

@available(*, deprecated, renamed: "JSValueCompatible")
public typealias JSValueCodable = JSValueCompatible

@available(*, deprecated, renamed: "JSClosure")
public typealias JSOneshotClosure = JSClosure
70 changes: 17 additions & 53 deletions Sources/JavaScriptKit/FundamentalObjects/JSClosure.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import _CJavaScriptKit

fileprivate var closureRef: JavaScriptHostFuncRef = 0
fileprivate var sharedClosures: [JavaScriptHostFuncRef: ([JSValue]) -> JSValue] = [:]

/// JSClosureProtocol abstracts closure object in JavaScript, whose lifetime is manualy managed
Expand All @@ -10,40 +11,9 @@ public protocol JSClosureProtocol: JSValueCompatible {
func release()
}

/// `JSOneshotClosure` is a JavaScript function that can be called only once.
public class JSOneshotClosure: JSObject, JSClosureProtocol {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you measure runtime performance between JSOneshotClosure and JSClosure for deallocation overhead?
I think deallocation that depends on GC cycle will increase memory usage while waiting until event loop frame.

(But I'm not sure how this overhead affects users experience 😅 )

private var hostFuncRef: JavaScriptHostFuncRef = 0

public init(_ body: @escaping ([JSValue]) -> JSValue) {
// 1. Fill `id` as zero at first to access `self` to get `ObjectIdentifier`.
super.init(id: 0)
let objectId = ObjectIdentifier(self)
let funcRef = JavaScriptHostFuncRef(bitPattern: Int32(objectId.hashValue))
// 2. Retain the given body in static storage by `funcRef`.
sharedClosures[funcRef] = {
defer { self.release() }
return body($0)
}
// 3. Create a new JavaScript function which calls the given Swift function.
var objectRef: JavaScriptObjectRef = 0
_create_function(funcRef, &objectRef)

hostFuncRef = funcRef
id = objectRef
}

/// Release this function resource.
/// After calling `release`, calling this function from JavaScript will fail.
public func release() {
sharedClosures[hostFuncRef] = nil
}
}

/// `JSClosure` represents a JavaScript function the body of which is written in Swift.
/// This type can be passed as a callback handler to JavaScript functions.
/// Note that the lifetime of `JSClosure` should be managed by users manually
/// due to GC boundary between Swift and JavaScript.
/// For further discussion, see also [swiftwasm/JavaScriptKit #33](https://github.com/swiftwasm/JavaScriptKit/pull/33)
///
/// e.g.
/// ```swift
Expand All @@ -55,12 +25,10 @@ public class JSOneshotClosure: JSObject, JSClosureProtocol {
/// button.addEventListener!("click", JSValue.function(eventListenter))
/// ...
/// button.removeEventListener!("click", JSValue.function(eventListenter))
/// eventListenter.release()
/// ```
///
public class JSClosure: JSObject, JSClosureProtocol {
private var hostFuncRef: JavaScriptHostFuncRef = 0
var isReleased: Bool = false

@available(*, deprecated, message: "This initializer will be removed in the next minor version update. Please use `init(_ body: @escaping ([JSValue]) -> JSValue)` and add `return .undefined` to the end of your closure")
@_disfavoredOverload
Expand All @@ -72,33 +40,29 @@ public class JSClosure: JSObject, JSClosureProtocol {
}

public init(_ body: @escaping ([JSValue]) -> JSValue) {
// 1. Fill `id` as zero at first to access `self` to get `ObjectIdentifier`.
super.init(id: 0)
let objectId = ObjectIdentifier(self)
let funcRef = JavaScriptHostFuncRef(bitPattern: Int32(objectId.hashValue))
// 2. Retain the given body in static storage by `funcRef`.
sharedClosures[funcRef] = body
// 3. Create a new JavaScript function which calls the given Swift function.
self.hostFuncRef = closureRef
closureRef += 1

// Retain the given body in static storage by `closureRef`.
sharedClosures[self.hostFuncRef] = body

// Create a new JavaScript function which calls the given Swift function.
var objectRef: JavaScriptObjectRef = 0
_create_function(funcRef, &objectRef)
_create_function(self.hostFuncRef, &objectRef)

hostFuncRef = funcRef
id = objectRef
super.init(id: objectRef)
}

public func release() {
isReleased = true
sharedClosures[hostFuncRef] = nil
}
@available(*, deprecated, message: "JSClosure.release() is no longer necessary")
public func release() {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So JSClosure in browsers without FinalizationRegistry support won't be deallocated, right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If FinalizationRegistry is not supported, the JS side will crash on startup when it attempts to call new FinalizationRegistry().

}

deinit {
guard isReleased else {
// Safari doesn't support `FinalizationRegistry`, so we cannot automatically manage the lifetime of Swift objects
fatalError("release() must be called on JSClosure objects manually before they are deallocated")
}
}
@_cdecl("_free_host_function_impl")
func _free_host_function_impl(_ hostFuncRef: JavaScriptHostFuncRef) {
sharedClosures[hostFuncRef] = nil
}


// MARK: - `JSClosure` mechanism note
//
// 1. Create a thunk in the JavaScript world, which has a reference
Expand Down
7 changes: 7 additions & 0 deletions Sources/_CJavaScriptKit/_CJavaScriptKit.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ void swjs_call_host_function(const JavaScriptHostFuncRef host_func_ref,
_call_host_function_impl(host_func_ref, argv, argc, callback_func);
}

void _free_host_function_impl(const JavaScriptHostFuncRef host_func_ref);

__attribute__((export_name("swjs_free_host_function")))
void swjs_free_host_function(const JavaScriptHostFuncRef host_func_ref) {
_free_host_function_impl(host_func_ref);
}

__attribute__((export_name("swjs_prepare_host_function_call")))
void *swjs_prepare_host_function_call(const int argc) {
return malloc(argc * sizeof(RawJSValue));
Expand Down
38 changes: 1 addition & 37 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@
"license": "MIT",
"devDependencies": {
"prettier": "2.1.2",
"typescript": "^4.0.2"
"typescript": "^4.2.4"
}
}