Repository navigation
Expand file tree
/
Copy pathJSThreadSafeFunction.cs
More file actions
323 lines (278 loc) · 11.5 KB
/
Copy pathJSThreadSafeFunction.cs
File metadata and controls
323 lines (278 loc) · 11.5 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.JavaScript.NodeApi.Runtime;
using static Microsoft.JavaScript.NodeApi.Runtime.JSRuntime;
using static Microsoft.JavaScript.NodeApi.Runtime.NodejsRuntime;
namespace Microsoft.JavaScript.NodeApi.Interop;
public delegate void JSThreadSafeCallback(JSValue jsFunction, object? functionContext, object? callbackData);
public delegate void JSThreadSafeFinalizeCallback(object? functionContext);
public class JSThreadSafeFunction
{
private readonly JSRuntime _runtime;
private readonly napi_threadsafe_function _tsfn;
private int _refCount = 1;
public static explicit operator napi_threadsafe_function(JSThreadSafeFunction function) => function._tsfn;
public static implicit operator JSThreadSafeFunction(napi_threadsafe_function tsfn) => new(tsfn);
private JSThreadSafeFunction(napi_threadsafe_function tsfn)
{
_runtime = JSValueScope.Current.Runtime;
_tsfn = tsfn;
}
public static bool IsAvailable
=> JSValueScope.Current.Runtime.IsAvailable("napi_create_threadsafe_function");
// This API may only be called from the main thread.
public unsafe JSThreadSafeFunction(int maxQueueSize,
int initialThreadCount,
in JSValue asyncResourceName,
in JSValue? jsFunction = null,
in JSObject? asyncResource = null,
JSThreadSafeFinalizeCallback? finalize = null,
object? functionContext = null,
JSThreadSafeCallback? jsCaller = null)
{
_runtime = JSValueScope.Current.Runtime;
FunctionData functionData = new(functionContext, finalize, jsCaller);
// Do not use AllocGCHandle() because we're calling from another thread.
GCHandle functionDataHandle = GCHandle.Alloc(functionData);
napi_status status = _runtime.CreateThreadSafeFunction(
(napi_env)JSValueScope.Current,
(napi_value)jsFunction,
(napi_value)(JSValue?)asyncResource,
(napi_value)asyncResourceName,
maxQueueSize,
initialThreadCount,
threadFinalizeData: default,
new napi_finalize(s_finalizeFunctionData),
(nint)functionDataHandle,
(jsCaller != null)
? new napi_threadsafe_function_call_js(s_customCallJS)
: new napi_threadsafe_function_call_js(s_defaultCallJS),
out _tsfn);
if (status != napi_status.napi_ok)
{
functionDataHandle.Free();
status.ThrowIfFailed();
}
}
// This API may be called from any thread.
public object? GetFunctionContext()
{
_runtime.GetThreadSafeFunctionContext(_tsfn, out nint handle).ThrowIfFailed();
FunctionData functionData = (FunctionData)GCHandle.FromIntPtr(handle).Target!;
return functionData.FunctionContext;
}
// This API may be called from any thread.
public void BlockingCall()
{
CallInternal(null, napi_threadsafe_function_call_mode.napi_tsfn_blocking);
}
// This API may be called from any thread.
public void BlockingCall(object? data)
{
CallInternal(data, napi_threadsafe_function_call_mode.napi_tsfn_blocking);
}
// This API may be called from any thread.
public void BlockingCall(Action callback)
{
CallInternal(callback, napi_threadsafe_function_call_mode.napi_tsfn_blocking);
}
// This API may be called from any thread.
public void BlockingCall(Action<JSValue?, object?> callback)
{
CallInternal(callback, napi_threadsafe_function_call_mode.napi_tsfn_blocking);
}
// This API may be called from any thread.
public bool NonBlockingCall()
{
return CallInternal(null, napi_threadsafe_function_call_mode.napi_tsfn_nonblocking);
}
// This API may be called from any thread.
public bool NonBlockingCall(object? data)
{
return CallInternal(data, napi_threadsafe_function_call_mode.napi_tsfn_nonblocking);
}
// This API may be called from any thread.
public bool NonBlockingCall(Action callback)
{
return CallInternal(callback, napi_threadsafe_function_call_mode.napi_tsfn_nonblocking);
}
// This API may be called from any thread.
public bool NonBlockingCall(Action<JSValue?, object?> callback)
{
return CallInternal(callback, napi_threadsafe_function_call_mode.napi_tsfn_nonblocking);
}
// This API may only be called from the main thread.
public void Ref()
{
if (_tsfn.Handle != default)
{
if (++_refCount == 1)
{
_runtime.RefThreadSafeFunction((napi_env)JSValueScope.Current, _tsfn).ThrowIfFailed();
}
}
}
// This API may only be called from the main thread.
public void Unref()
{
if (_tsfn.Handle != default)
{
if (--_refCount == 0)
{
_runtime.UnrefThreadSafeFunction((napi_env)JSValueScope.Current, _tsfn); //TODO: .ThrowIfFailed();
}
}
}
// This API may be called from any thread.
public napi_status Acquire()
{
return _runtime.AcquireThreadSafeFunction(_tsfn);
}
// This API may be called from any thread.
public napi_status Release()
{
return _runtime.ReleaseThreadSafeFunction(
_tsfn, napi_threadsafe_function_release_mode.napi_tsfn_release);
}
// This API may be called from any thread.
public napi_status Abort()
{
return _runtime.ReleaseThreadSafeFunction(
_tsfn, napi_threadsafe_function_release_mode.napi_tsfn_abort);
}
private bool CallInternal(object? callbackOrData, napi_threadsafe_function_call_mode mode)
{
// Do not use AllocGCHandle() because we're calling from another thread.
GCHandle callbackOrDataHandle = GCHandle.Alloc(callbackOrData);
napi_status status = _runtime.CallThreadSafeFunction(
_tsfn, (nint)callbackOrDataHandle, mode);
if (status != napi_status.napi_ok)
{
// Do not use FreeGCHandle() - the handle was allocated on a different thread.
callbackOrDataHandle.Free();
}
// TODO: Consider throwing exceptions for status codes other than napi_ok.
// Note some error statuses are expected:
// - napi_queue_full: The queue is full, the nonblocking call should be retried later.
// - napi_closing: The thread-safe function is closing (typically due to env shutdown).
// - napi_invalid_arg: The TSFN is invalid or disposed (can also occur during shutdown).
return status == napi_status.napi_ok;
}
#if !UNMANAGED_DELEGATES
private static readonly napi_finalize.Delegate s_finalizeFunctionData = FinalizeFunctionData;
private static readonly napi_threadsafe_function_call_js.Delegate s_customCallJS = CustomCallJS;
private static readonly napi_threadsafe_function_call_js.Delegate s_defaultCallJS = DefaultCallJS;
#else
private static readonly unsafe delegate* unmanaged[Cdecl]
<napi_env, nint, nint, void> s_finalizeFunctionData = &FinalizeFunctionData;
private static readonly unsafe delegate* unmanaged[Cdecl]
<napi_env, napi_value, nint, nint, void> s_customCallJS = &CustomCallJS;
private static readonly unsafe delegate* unmanaged[Cdecl]
<napi_env, napi_value, nint, nint, void> s_defaultCallJS = &DefaultCallJS;
#endif
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
private static unsafe void FinalizeFunctionData(napi_env env, nint _, nint hint)
{
GCHandle functionDataHandle = GCHandle.FromIntPtr(hint);
if (functionDataHandle.Target is FunctionData functionData && functionData.Finalize is not null)
{
functionData.Finalize(functionData.FunctionContext);
}
functionDataHandle.Free();
}
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
private static unsafe void CustomCallJS(napi_env env, napi_value jsCallback, nint context, nint data)
{
if (env.IsNull && jsCallback.IsNull)
{
return;
}
try
{
using JSValueScope scope = new(JSValueScopeType.Callback, env, runtime: null);
object? callbackData = null;
if (data != default)
{
GCHandle dataHandle = GCHandle.FromIntPtr(data);
callbackData = dataHandle.Target!;
// Do not use FreeGCHandle() - the handle was allocated on a different thread.
dataHandle.Free();
}
GCHandle contextHandle = GCHandle.FromIntPtr(context);
FunctionData functionData = (FunctionData)contextHandle.Target!;
functionData.JSCaller!((JSValue)jsCallback, functionData.FunctionContext, callbackData);
}
catch (Exception ex)
{
JSError.Fatal(ex.Message);
}
}
#if UNMANAGED_DELEGATES
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
#endif
private static unsafe void DefaultCallJS(napi_env env, napi_value jsCallback, nint context, nint data)
{
if (env.IsNull && jsCallback.IsNull)
{
return;
}
try
{
using JSValueScope scope = new(JSValueScopeType.Callback, env, runtime: null);
if (data != default)
{
GCHandle dataHandle = GCHandle.FromIntPtr(data);
object dataObject = dataHandle.Target!;
// Do not use FreeGCHandle() - the handle was allocated on a different thread.
dataHandle.Free();
if (dataObject is Action action)
{
action();
}
else if (dataObject is Action<JSValue?, object?> callback)
{
GCHandle contextHandle = GCHandle.FromIntPtr(context);
FunctionData functionData = (FunctionData)contextHandle.Target!;
callback((JSValue?)jsCallback, functionData.FunctionContext);
}
else
{
throw new ArgumentException("Unexpected data parameter");
}
}
else if (jsCallback.Handle != default)
{
((JSValue)jsCallback).Call();
}
}
catch (Exception ex)
{
#if DEBUG
Console.Error.WriteLine(ex);
#endif
JSError.Fatal(ex.Message);
}
}
private class FunctionData
{
public FunctionData(
object? functionContext,
JSThreadSafeFinalizeCallback? finalize,
JSThreadSafeCallback? jsCaller)
{
FunctionContext = functionContext;
Finalize = finalize;
JSCaller = jsCaller;
}
public object? FunctionContext { get; }
public JSThreadSafeFinalizeCallback? Finalize { get; }
public JSThreadSafeCallback? JSCaller { get; }
}
}