-
-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathJSRemote.swift
More file actions
394 lines (369 loc) · 14.8 KB
/
JSRemote.swift
File metadata and controls
394 lines (369 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import _Concurrency
@_spi(JSObject_id) import JavaScriptKit
import _CJavaScriptKit
/// A sendable handle for temporarily accessing a `JSObject` on its owning thread.
///
/// `JSRemote` lets you share a reference to a JavaScript object across Swift concurrency
/// domains without transferring or cloning the object itself. Instead, the object stays
/// owned by its original JavaScript thread, and `withJSObject(_:)` schedules a closure to
/// run on that owner when needed.
///
/// This is useful when you need occasional coordinated access to a JavaScript object from
/// another thread, but cannot or should not move the object with `JSSending`.
///
/// - Note: `JSRemote` does not make the underlying `JSObject` itself thread-safe. The object
/// may only be touched inside `withJSObject(_:)`.
///
/// ## Example
///
/// ```swift
/// let document = JSObject.global.document.object!
/// let remoteDocument = JSRemote(document)
///
/// let executor = try await WebWorkerTaskExecutor(numberOfThreads: 1)
/// let title = try await Task(executorPreference: executor) {
/// try await remoteDocument.withJSObject { document in
/// document.title.string ?? ""
/// }
/// }.value
/// ```
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public struct JSRemote<T>: @unchecked Sendable {
private final class Storage {
let sourceObject: JSObject
let sourceTid: Int32
init(sourceObject: JSObject, sourceTid: Int32) {
self.sourceObject = sourceObject
self.sourceTid = sourceTid
}
}
private let storage: Storage
fileprivate init(sourceObject: JSObject) {
let sourceTid: Int32
#if compiler(>=6.1) && _runtime(_multithreaded)
sourceTid = sourceObject.ownerTid
#else
sourceTid = -1
#endif
self.storage = Storage(sourceObject: sourceObject, sourceTid: sourceTid)
}
fileprivate func _withJSObject<R: Sendable, E: Error>(
_ body: @Sendable @escaping (JSObject) throws(E) -> R
) async throws(E) -> sending R {
#if compiler(>=6.1) && _runtime(_multithreaded)
if storage.sourceTid == swjs_get_worker_thread_id_cached() {
return try body(storage.sourceObject)
}
let result: Result<R, E> = await withCheckedContinuation { continuation in
let context = _JSRemoteSyncContext(
sourceObject: storage.sourceObject,
body: body,
continuation: continuation
)
swjs_request_remote_jsobject_body(
storage.sourceTid,
Unmanaged.passRetained(context).toOpaque()
)
}
return try result.get()
#else
return try body(storage.sourceObject)
#endif
}
#if compiler(>=6.1) && hasFeature(Embedded) && _runtime(_multithreaded)
#else
fileprivate func _withJSObject<R: Sendable, E: Error>(
_ body: @Sendable @escaping (JSObject) async throws(E) -> R
) async throws(E) -> sending R {
#if compiler(>=6.1) && _runtime(_multithreaded)
if storage.sourceTid == swjs_get_worker_thread_id_cached() {
return try await body(storage.sourceObject)
}
let result: Result<R, E> = await withCheckedContinuation { continuation in
let context = _JSRemoteAsyncContext(
sourceObject: storage.sourceObject,
body: body,
continuation: continuation
)
swjs_request_remote_jsobject_body(
storage.sourceTid,
Unmanaged.passRetained(context).toOpaque()
)
}
return try result.get()
#else
return try await body(storage.sourceObject)
#endif
}
#endif
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension JSRemote where T == JSObject {
/// Creates a remote handle for a `JSObject`.
///
/// The object remains owned by its current JavaScript thread. Access it later by calling
/// `withJSObject(_:)`, which executes the closure on the owning thread when necessary.
///
/// ## Example
///
/// ```swift
/// let remoteWindow = JSRemote(JSObject.global)
/// ```
///
/// - Parameter object: The JavaScript object to reference remotely.
public init(_ object: JSObject) {
self.init(sourceObject: object)
}
/// Performs an operation with the underlying `JSObject` on its owning thread.
///
/// If the caller is already running on the thread that owns the object, `body` executes
/// immediately. Otherwise, this method asynchronously requests execution on the owner and
/// resumes when the closure completes.
///
/// Use this API when the object must stay on its original thread but a result derived from
/// that object needs to be produced in another Swift concurrency context.
///
/// ## Example
///
/// ```swift
/// let location = try await remoteWindow.withJSObject { window in
/// window.location.href.string ?? ""
/// }
/// ```
///
/// - Parameter body: A sendable closure that receives the owned `JSObject`.
/// - Returns: The value produced by `body`.
/// - Throws: Any error thrown by `body`.
public func withJSObject<R: Sendable, E: Error>(
_ body: @Sendable @escaping (JSObject) throws(E) -> R
) async throws(E) -> sending R {
try await _withJSObject(body)
}
#if compiler(>=6.1) && hasFeature(Embedded) && _runtime(_multithreaded)
#else
/// Performs an asynchronous operation with the underlying `JSObject` on its owning thread.
///
/// If the caller is already running on the thread that owns the object, `body` executes
/// immediately. Otherwise, this method asynchronously requests execution on the owner and
/// resumes when the closure completes.
///
/// Use this API when the object must stay on its original thread but producing a result
/// requires suspending, such as awaiting a JavaScript promise.
///
/// ## Example
///
/// ```swift
/// let value = try await remoteWindow.withJSObject { window in
/// try await JSPromise(from: window.fetch!("/api").object!)!.value
/// }
/// ```
///
/// - Parameter body: A sendable asynchronous closure that receives the owned `JSObject`.
/// - Returns: The value produced by `body`.
/// - Throws: Any error thrown by `body`.
public func withJSObject<R: Sendable, E: Error>(
_ body: @Sendable @escaping (JSObject) async throws(E) -> R
) async throws(E) -> sending R {
try await _withJSObject(body)
}
#endif
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension JSRemote where T: _JSBridgedClass {
/// Creates a remote handle for a `@JSClass`-imported object.
///
/// The object remains owned by its current JavaScript thread. Access it later by calling
/// `withJSObject(_:)`, which executes the closure on the owning thread when necessary.
///
/// ## Example
///
/// ```swift
/// @JSClass struct Window {
/// @JSGetter var location: Location
/// }
/// let remoteWindow = JSRemote(Window(unsafelyWrapping: JSObject.global))
/// remoteWindow.withJSObject { window in
/// print(window.location.href.string ?? "")
/// }
/// ```
///
/// - Parameter object: The JavaScript object to reference remotely.
public init(_ object: T) {
self.init(sourceObject: object.jsObject)
}
/// Performs an operation with the underlying `T` object on its owning thread.
///
/// If the caller is already running on the thread that owns the object, `body` executes
/// immediately. Otherwise, this method asynchronously requests execution on the owner and
/// resumes when the closure completes.
///
/// Use this API when the object must stay on its original thread but a result derived from
/// that object needs to be produced in another Swift concurrency context.
///
/// ## Example
///
/// ```swift
/// let location = try await remoteWindow.withJSObject { window in
/// window.location.href.string ?? ""
/// }
/// ```
///
/// - Parameter body: A sendable closure that receives the owned `T` object.
/// - Returns: The value produced by `body`.
/// - Throws: Any error thrown by `body`.
#if compiler(>=6.2)
public func withJSObject<R: Sendable, E: Error>(
_ body: @Sendable @escaping (T) throws(E) -> R
) async throws(E) -> sending R where T: SendableMetatype {
try await _withJSObject { jsObject throws(E) -> R in
let object = T(unsafelyWrapping: jsObject)
return try body(object)
}
}
#else
public func withJSObject<R: Sendable, E: Error>(
_ body: @Sendable @escaping (T) throws(E) -> R
) async throws(E) -> sending R {
try await _withJSObject { jsObject throws(E) -> R in
let object = T(unsafelyWrapping: jsObject)
return try body(object)
}
}
#endif
#if compiler(>=6.1) && hasFeature(Embedded) && _runtime(_multithreaded)
#else
/// Performs an asynchronous operation with the underlying `T` object on its owning thread.
///
/// If the caller is already running on the thread that owns the object, `body` executes
/// immediately. Otherwise, this method asynchronously requests execution on the owner and
/// resumes when the closure completes.
///
/// Use this API when the object must stay on its original thread but producing a result
/// requires suspending, such as awaiting a JavaScript promise.
///
/// ## Example
///
/// ```swift
/// let response = try await remoteWindow.withJSObject { window in
/// try await window.fetch("/api").value
/// }
/// ```
///
/// - Parameter body: A sendable asynchronous closure that receives the owned `T` object.
/// - Returns: The value produced by `body`.
/// - Throws: Any error thrown by `body`.
#if compiler(>=6.2)
public func withJSObject<R: Sendable, E: Error>(
_ body: @Sendable @escaping (T) async throws(E) -> R
) async throws(E) -> sending R where T: SendableMetatype {
try await _withJSObject { jsObject async throws(E) -> R in
let object = T(unsafelyWrapping: jsObject)
return try await body(object)
}
}
#else
public func withJSObject<R: Sendable, E: Error>(
_ body: @Sendable @escaping (T) async throws(E) -> R
) async throws(E) -> sending R {
try await _withJSObject { jsObject async throws(E) -> R in
let object = T(unsafelyWrapping: jsObject)
return try await body(object)
}
}
#endif
#endif
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
private class _JSRemoteContext: @unchecked Sendable {
fileprivate func invoke() {
preconditionFailure("JSRemote context subclasses must override invoke()")
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
private final class _JSRemoteSyncContext<R: Sendable, E: Error>: _JSRemoteContext, @unchecked Sendable {
let sourceObject: JSObject
let body: @Sendable (JSObject) throws(E) -> R
let continuation: CheckedContinuation<Result<R, E>, Never>
init(
sourceObject: JSObject,
body: @escaping @Sendable (JSObject) throws(E) -> R,
continuation: CheckedContinuation<Result<R, E>, Never>
) {
self.sourceObject = sourceObject
self.body = body
self.continuation = continuation
}
override fileprivate func invoke() {
// NOTE: Sendability violation here for `sourceObject`.
// Even though `JSObject` is not Sendable, it is safe to access it here
// because this method will only be executed on the owning thread.
do throws(E) {
continuation.resume(returning: .success(try body(sourceObject)))
} catch {
continuation.resume(returning: .failure(error))
}
}
}
#if compiler(>=6.1) && hasFeature(Embedded) && _runtime(_multithreaded)
#else
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
private final class _JSRemoteAsyncContext<R: Sendable, E: Error>: _JSRemoteContext, @unchecked Sendable {
let sourceObject: JSObject
let body: @Sendable (JSObject) async throws(E) -> R
let continuation: CheckedContinuation<Result<R, E>, Never>
init(
sourceObject: JSObject,
body: @escaping @Sendable (JSObject) async throws(E) -> R,
continuation: CheckedContinuation<Result<R, E>, Never>
) {
self.sourceObject = sourceObject
self.body = body
self.continuation = continuation
}
override fileprivate func invoke() {
_runJSRemoteBody {
await self.invokeAsync()
}
}
private func invokeAsync() async {
// NOTE: Sendability violation here for `sourceObject`.
// Even though `JSObject` is not Sendable, it is safe to access it here
// because this method will only be executed on the owning thread.
do throws(E) {
continuation.resume(returning: .success(try await body(sourceObject)))
} catch {
continuation.resume(returning: .failure(error))
}
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
private func _runJSRemoteBody(_ body: @escaping @Sendable () async -> Void) {
#if compiler(>=6.0) && !hasFeature(Embedded)
if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {
Task(executorPreference: WebWorkerTaskExecutor.currentExecutorPreference) {
await body()
}
return
}
#endif
Task {
await body()
}
}
#endif
#if compiler(>=6.1)
@_expose(wasm, "swjs_invoke_remote_jsobject_body")
@_cdecl("swjs_invoke_remote_jsobject_body")
#endif
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
func _swjs_invoke_remote_jsobject_body(_ contextPtr: UnsafeRawPointer?) -> Bool {
#if compiler(>=6.1) && _runtime(_multithreaded)
guard let contextPtr else { return true }
let context = Unmanaged<_JSRemoteContext>.fromOpaque(contextPtr).takeRetainedValue()
context.invoke()
return false
#else
_ = contextPtr
return true
#endif
}