Repository navigation
Improve object safety - #500
Vladimir Morozov (vmoroz) wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
Refactors Node-API object lifetimes around environment-owned runtime contexts and explicit value-scope factories.
Changes:
- Reworks scope, reference, module-holder, and runtime-context ownership.
- Updates hosts, embedding adapters, source generation, and Hermes integration.
- Expands lifetime and worker-teardown testing; updates documentation and dependencies.
Reviewed changes
Copilot reviewed 30 out of 30 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
test/TestCases/napi-dotnet/worker_teardown_stress.js |
Adds repeated worker teardown coverage. |
test/TestBuilder.cs |
Hardens SDK selection for test builds. |
test/MockJSRuntime.cs |
Mocks escapable-handle behavior. |
test/JSValueScopeTests.cs |
Tests the new scope model. |
test/JSReferenceTests.cs |
Updates reference lifetime tests. |
test/GCTests.cs |
Uses runtime-scope factories. |
src/NodeApi/Runtime/TracingJSRuntime.cs |
Migrates traced callbacks to runtime scopes. |
src/NodeApi/Runtime/NodeEmbeddingNodeApiScope.cs |
Creates an embedding runtime context. |
src/NodeApi/Runtime/NodeEmbedding.cs |
Updates embedding callback scopes. |
src/NodeApi/NodeApi.csproj |
Grants internal access to host and tests. |
src/NodeApi/JSValueScope.cs |
Introduces factory-based scope construction. |
src/NodeApi/JSValue.cs |
Removes no-context callback paths. |
src/NodeApi/JSReference.cs |
Makes references context-owned. |
src/NodeApi/JSPropertyDescriptor.cs |
Captures module holders. |
src/NodeApi/JSError.cs |
Adapts error handling to new scopes. |
src/NodeApi/Interop/JSThreadSafeFunction.cs |
Uses context-resolving callback scopes. |
src/NodeApi/Interop/JSSynchronizationContext.cs |
Adds an inline host synchronization context. |
src/NodeApi/Interop/JSRuntimeContext.cs |
Adds environment registration and annotations. |
src/NodeApi/Interop/JSModuleContext.cs |
Removes the former module context. |
src/NodeApi/Interop/JSModuleBuilderOfT.cs |
Stores module instances in holders. |
src/NodeApi/Interop/JSCallbackDescriptor.cs |
Carries module holders through callbacks. |
src/NodeApi/DotNetHost/NativeHost.cs |
Adds managed-host teardown registration. |
src/NodeApi.Generator/ModuleGenerator.cs |
Generates separate AOT and hosted entry paths. |
src/NodeApi.DotNetHost/ManagedHostRegistration.cs |
Defines the host teardown handshake. |
src/NodeApi.DotNetHost/ManagedHost.cs |
Registers and disposes managed contexts. |
src/NodeApi.DotNetHost/JSMarshaller.cs |
Resolves module instances from scopes. |
examples/hermes-engine/HermesRuntime.cs |
Migrates Hermes to scope factories. |
docs/features/js-value-scopes.md |
Documents the new factory API. |
Directory.Packages.props |
Updates Nullability.Source. |
bench/Benchmarks.cs |
Updates benchmark scope creation. |
Suppressed comments (3)
src/NodeApi/Interop/JSRuntimeContext.cs:184
FromEnvuses the runtime from the most recently constructed context process-wide. BecauseCreatepublicly accepts a runtime per context, creating env A with runtime A and then env B with a stateful runtime B makesFromEnv(envA)callruntimeB.GetInstanceData(envA)and potentially return B's context. Store/resolve the runtime per environment, or require the caller's runtime explicitly instead of using this global.
public static unsafe JSRuntimeContext? FromEnv(napi_env env)
{
JSRuntime? runtime = s_instanceDataRuntime;
if (runtime is null)
{
return null;
}
runtime.GetInstanceData(env, out nint instanceData).ThrowIfFailed();
src/NodeApi/Interop/JSRuntimeContext.cs:221
- Lazy creation makes disposal unsafe for a context that never opened a scope.
Dispose()accesses this property, so it attemptsJSSynchronizationContext.Create()while noJSValueScopeis current (including instance-data finalization), throws, and skips the remaining context/annotation cleanup. Disposal should only dispose an already-created_synchronizationContext, without constructing one.
/// <summary>
/// Gets the synchronization context that marshals callbacks and continuations to the JS thread.
/// A default one is created on first access, which happens while a scope for this context is
/// current, because creating it requires the current scope's runtime and environment.
/// </summary>
public JSSynchronizationContext SynchronizationContext
=> _synchronizationContext ??= JSSynchronizationContext.Create();
src/NodeApi/Interop/JSRuntimeContext.cs:278
- This silently overwrites an occupied slot instead of enforcing the promised one-context-per-env invariant. The embedding adapters now construct contexts repeatedly for the same lifecycle/env, so earlier contexts remain rooted while
FromEnvsuddenly resolves the last one; separate AOT addons are worse because the overwritten slot may contain a GCHandle owned by another CLR heap. Reuse/reject an existing registration and provide storage that cannot cross-dereference another runtime's handle.
((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 30 out of 30 changed files in this pull request and generated 2 comments.
Suppressed comments (2)
src/NodeApi/Interop/JSRuntimeContext.cs:278
- This unconditionally replaces an existing context for the same runtime/environment. The five changed Node embedding callback adapters each construct a new context, so earlier contexts (including their synchronization contexts and references) remain live while the environment finalizer disposes only the last one. Reuse the context already registered for the environment, and reject duplicate registration in the factory as a safeguard.
((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;
src/NodeApi/Interop/JSRuntimeContext.cs:904
ContextHandleis intentionally never freed, so this dictionary otherwise keeps every disposedManagedHost/NativeHostannotation strongly reachable forever. Repeated worker creation therefore accumulates disposed hosts and their load-context object graphs. Clear the owning annotations after all values have been disposed.
if (_disposableAnnotations != null)
{
foreach (IDisposable annotation in _disposableAnnotations.Values)
{
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 30 out of 30 changed files in this pull request and generated 1 comment.
Suppressed comments (4)
src/NodeApi/Interop/JSRuntimeContext.cs:123
- The fixed two-slot layout is not actually “one slot per runtime.” Two NativeAOT modules loaded into the same
napi_envrun in separate managed runtimes, but both useModuleContextSlot; the later module overwrites the first module’s opaqueGCHandle, and the first module’s instance-data finalizer then attempts to interpret a handle owned by the other GC heap. This can leak or crash during teardown. The instance-data representation needs per-runtime ownership that does not place multiple runtimes’ handles in the same fixed slot.
// Env instance-data layout: one GCHandle slot per runtime sharing the napi_env. Slot 0 is the
// module context (managed host / AOT module / embedding); slot 1 is the native host context.
// A runtime reads and writes only its own slot, so it never dereferences the other runtime's
// GCHandle (which belongs to a separate GC heap).
private const int ModuleContextSlot = 0;
src/NodeApi/Interop/JSRuntimeContext.cs:136
- This strong
GCHandleis intentionally never freed, so every environment permanently roots itsJSRuntimeContextand everything it still references. The worker stress path creates both native- and managed-host contexts per iteration, making repeated worker teardown a guaranteed process-lifetime managed-memory leak. Keep only teardown-safe finalize-hint state alive as long as necessary, and free the context handle after the environment’s dependent finalizers can no longer use it.
// A GCHandle rooting this context, used both as its env instance-data slot value and as the
// finalize hint for pooled GC handles. It is intentionally never freed: pooled-handle
// finalizers dereference it during env teardown, after this context is already disposed.
src/NodeApi/Interop/JSRuntimeContext.cs:180
FromEnvuses whichever runtime was registered most recently process-wide. After creating contexts with differentJSRuntimeinstances, resolving the earlier environment callsGetInstanceDataon the later runtime; stateful implementations (including the per-instanceMockJSRuntime) therefore return the wrong context or fail. Track the runtime/context per environment instead of storing one global runtime.
public static unsafe JSRuntimeContext? FromEnv(napi_env env)
{
JSRuntime? runtime = s_instanceDataRuntime;
if (runtime is null)
{
src/NodeApi/Interop/JSRuntimeContext.cs:877
- Replacing an owning annotation of the same type drops the previous instance without disposing it or returning it to the caller. Because this API promises that the context owns these values, the previous resource is leaked permanently. Define replacement semantics and either dispose the replaced value or reject duplicate registration.
public void SetDisposableAnnotation<T>(T value) where T : class, IDisposable
{
if (value is null) throw new ArgumentNullException(nameof(value));
(_disposableAnnotations ??= new())[typeof(T)] = value;
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 30 out of 30 changed files in this pull request and generated 1 comment.
Suppressed comments (3)
Previously missed (1) — in code that hasn't changed since the last review.
src/NodeApi.DotNetHost/ManagedHost.cs:213
- In hosted mode this context does not own the instance-data finalizer, but the native host receives the managed teardown callback only after
ManagedHostconstruction succeeds and fillsregistration. If initialization throws before that point, the catch reports the JS error but leaves this context's rootingGCHandleand synchronization context registered forever because the native host has no callback with which to dispose it. Close the scope and dispose the context on the failed-initialization path.
bool hosted = registration != null;
JSRuntimeContext context = new(env, runtime);
using JSValueScope scope = JSValueScope.CreateRuntimeScope(env, context);
src/NodeApi/Interop/JSModuleBuilderOfT.cs:37
- This drops the previous ownership behavior of
JSModuleContext: whenmoduleimplementsIDisposable, it is no longer disposed at module/context teardown. Generated module classes such astest/TestCases/napi-dotnet/ModuleClass.cs:17rely on that contract. Register disposable module instances with the runtime context (without collapsing multiple modules onto one annotation key) so teardown still invokesDispose().
// Write through the holder the descriptors captured, so callbacks bound before the module
// instance existed observe it.
JSValueScope.Current.ModuleHolder!.Value = module;
exports.DefineProperties(Properties.ToArray());
src/NodeApi/Interop/JSRuntimeContext.cs:280
- This assignment silently replaces an existing context in the slot without disposing it or freeing its
ContextHandle, violating the one-context-per-env invariant. The default embedding path already triggers this:RuntimeLoadingCallbackAdapterregisters one context, thenNodeEmbeddingNodeApiScoperegisters another for the same environment, permanently rooting the first context and its GC handles. Resolve/reuse the registered context in embedding callbacks/scopes, and reject or safely handle duplicate registration.
((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 30 out of 30 changed files in this pull request and generated 1 comment.
Suppressed comments (6)
Previously missed (2) — in code that hasn't changed since the last review.
src/NodeApi/JSValueScope.cs:175
- With no parent and the default null
env, this callsFromEnv(default). Once any context has initialized the static runtime, that invokesnapi_get_instance_datawith a null environment instead of rejecting the invalid factory call. Validate that an env was supplied before attempting environment lookup.
// Inherit the parent scope's context, else recover it from the env instance data.
context ??= _parentScope?.RuntimeContext
?? JSRuntimeContext.FromEnv(env)
?? throw new InvalidOperationException(
"A runtime context could not be resolved for the scope.");
src/NodeApi.DotNetHost/ManagedHost.cs:213
- The context is registered and rooted before initialization enters the
try, but the native host receives the registration handle only near the end of the successful path. If initialization throws earlier, the catch returns with no handshake handle, so environment teardown cannot dispose this managed context; its instance-data GCHandle, synchronization context, and any installed resolve handlers remain rooted. Dispose the failed scope and context after reporting the JS error.
bool hosted = registration != null;
JSRuntimeContext context = new(env, runtime);
using JSValueScope scope = JSValueScope.CreateRuntimeScope(env, context);
src/NodeApi/JSReference.cs:365
- This concurrent-disposal assumption is unsafe.
JSTsfnSynchronizationContext.PostchecksIsDisposedand then calls_tsfn.NonBlockingCall, whileDisposecan release the TSFN between those operations. Since reference finalizers now always post here during environment teardown, that race can call a released native TSFN. Gate in-flight calls and close the gate before releasing the TSFN.
// The guard above handles an already-disposed context; if it is disposed concurrently after
// that check, the posted delete is still a safe no-op (the napi_ref went with the env).
src/NodeApi/DotNetHost/NativeHost.cs:501
- On .NET Framework, the managed teardown notification uses
_runtimeHost->ExecuteInDefaultAppDomain. This callback closes and nulls_runtimeHostwithout notifying the managed host, so the later environment finalizer skips its notification and leaks_addonGCHandleplus the managed context. Run the full idempotentDispose()path so notification occurs before the CLR host is closed.
exports.DefineProperties(new JSPropertyDescriptor(
"dispose", (_) => { CloseRuntimeHost(); return default; }));
src/NodeApi.Generator/ModuleGenerator.cs:309
- This hosted-module scope inherits the
ModuleHolderfrom the currentManagedHost.LoadModulecallback. Consequently all dynamically loaded generated modules share oneStrongBox; loading a second module overwrites the instance observed by callbacks from the first module. Create a fresh module holder at each module-initialization boundary while continuing to share the runtime context.
s += "using var moduleScope = JSValueScope.CreateRuntimeScope(env);";
s += $"return {ModuleExportsMethodName}(moduleScope, exports);";
src/NodeApi/Interop/JSRuntimeContext.cs:880
- Replacing an owning annotation of the same type drops the previous
IDisposablewithout disposing it, even though this API transfers disposal responsibility to the context. Either reject duplicate keys or dispose the previous value when replacing it so owned resources are not leaked.
public void SetDisposableAnnotation<T>(T value) where T : class, IDisposable
{
if (value is null) throw new ArgumentNullException(nameof(value));
(_disposableAnnotations ??= new())[typeof(T)] = value;
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 35 out of 35 changed files in this pull request and generated 4 comments.
Suppressed comments (3)
Previously missed (1) — in code that hasn't changed since the last review.
src/NodeApi/DotNetHost/NativeHost.cs:501
- On .NET Framework this releases
_runtimeHost, but environment teardown later requires that same pointer to callOnEnvironmentFinalize. After an explicit JSdispose(), the condition inNotifyManagedHostEnvironmentFinalizeis false, so the managed registration GCHandle and context are never released. Use the full disposal path so the managed host is notified before the runtime-host pointer is cleared.
// Define a dispose method implemented by the native host that closes the CLR context.
// The managed host proxy will pass through dispose calls to this callback.
exports.DefineProperties(new JSPropertyDescriptor(
"dispose", (_) => { CloseRuntimeHost(); return default; }));
src/NodeApi/Interop/JSRuntimeContext.cs:291
- This unconditionally overwrites an occupied slot. A second
JSRuntimeContext.Createfor the same environment leaves the first context rooted by a GCHandle that is no longer reachable through instance data, so it is never disposed. Reject an already-populated slot (and free the newly allocated handle on registration failure) to enforce the stated one-context-per-env invariant.
((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;
src/NodeApi/JSReference.cs:374
- The context can be disposed after the
IsDisposedcheck but before this post.JSTsfnSynchronizationContext.Postitself also checks then callsNonBlockingCall, whileDisposecan concurrently release the TSFN, producing a native use-after-release. A try/catch cannot protect that race; gate in-flight TSFN calls against release before using this path for cross-thread reference cleanup.
if (disposing)
{
// Delete the reference on the JS thread (inline if already there).
_context.SynchronizationContext.Post(
() => runtime.DeleteReference(env, handle).ThrowIfFailed(), allowSync: true);
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 35 out of 35 changed files in this pull request and generated 2 comments.
Suppressed comments (2)
Previously missed (1) — in code that hasn't changed since the last review.
test/TestCases/napi-dotnet/worker_teardown_stress.js:35
- This one-shot error listener is tied to the readiness promise. After
'ready'resolves that promise, a worker error emitted duringterminate()callsrejecton an already-settled promise and is silently consumed, allowing this teardown regression test to pass. Keep an error handler that fails the test for the worker's full lifetime, asworker_teardown.jsdoes.
src/NodeApi.DotNetHost/ManagedHost.cs:240
- The host becomes an owned annotation only after its constructor returns, but that constructor subscribes process-wide resolving handlers before several Node-API operations that can throw (
ManagedHost.cs:85-135). If construction fails, the catch disposes a context that does not know about the partially constructed host, leaving those handlers subscribed and rooting the failed worker host. Make construction transactional by unsubscribing on constructor failure, or defer the subscriptions until all fallible initialization is complete.
// Dispose the host with its environment: as a disposable annotation on the context, the
// host's full Dispose (which unsubscribes the process-wide resolve handlers) runs when
// the context is disposed at environment teardown. Mirrors the native host.
context.SetDisposableAnnotation(host);
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 35 out of 35 changed files in this pull request and generated no new comments.
Suppressed comments (1)
src/NodeApi/DotNetHost/NativeHost.cs:501
- The JS
disposehook now closes_runtimeHostwithout notifying the managed host. On .NET Framework,_onEnvFinalizeis intentionally unset and teardown can notify managed code only through_runtimeHost; after this callback nulls that pointer,NotifyManagedHostEnvironmentFinalize()skips the notification, so the registrationGCHandle, managedJSRuntimeContext, and resolve handlers remain rooted. Run the full idempotent host disposal here so the managed registration is released before the runtime-host channel is closed.
"dispose", (_) => { CloseRuntimeHost(); return default; }));
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved registration rollback, unmanaged-boundary, and scope-disposal issues can break context resolution or leak native runtimes.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (1)
Previously missed (1) — in code that hasn't changed since the last review.
docs/concepts/runtime-model.md:117
- This says the native reference is released when its context is disposed, but the implementation intentionally marks the context disposed before visiting references, causing
JSReference.Dispose()to skipnapi_delete_reference; on explicit context disposal, Node retains the reference until later environment teardown. Document that context disposal invalidates the managed reference and that the nativenapi_refis reclaimed by environment teardown.
- Files reviewed: 35/35 changed files
- Comments generated: 4
- Review effort level: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
Deferred teardown can dispose a context while an earlier scope for that context remains open under alternating context nesting.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
- Files reviewed: 35/35 changed files
- Comments generated: 1
- Review effort level: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Context lookup can use the wrong runtime, and reference cleanup retains a TSFN post/release race.
Review details
Suppressed comments (2)
src/NodeApi/Interop/JSRuntimeContext.cs:194
FromEnvuses whichever runtime registered most recently for every environment.JSRuntimeis a swappable, potentially instance-backed abstraction (for example,MockJSRuntimestores instance data on the runtime instance), so after contexts A and B are created with different runtimes,FromEnv(envA)calls B'sGetInstanceData; this can return no context or even dispatch the env to the wrong engine. Keep the runtime association per environment, or require the owning runtime when resolving a context.
JSRuntime? runtime = s_instanceDataRuntime;
src/NodeApi/JSReference.cs:388
- Posting here still has the TSFN post/release race:
JSTsfnSynchronizationContext.Postcan observeIsDisposed == false, then the environment cleanup path can release_tsfnbeforeNonBlockingCallexecutes. That produces a native use-after-release, and thiscatchcannot contain it. SynchronizePost/SendwithDisposeusing an in-flight call gate that closes and drains before releasing the TSFN (as described in the #495 follow-up).
_context.SynchronizationContext.Post(
- Files reviewed: 35/35 changed files
- Comments generated: 0 new
- Review effort level: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
Failed native scope closes can poison the scope stack, and rejected TSFN sends can wait indefinitely.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (1)
src/NodeApi/JSValueScope.cs:364
CloseHandleScope/CloseEscapableHandleScopecan fail, but the scope is marked disposed before those fallible calls. On failure,CurrentOrNullstill points at this now-disposed scope and a retry immediately returns, permanently poisoning the thread's scope stack. Mark the scope disposed only after the native close succeeds.
IsDisposed = true;
- Files reviewed: 37/37 changed files
- Comments generated: 1
- Review effort level: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
Queued synchronous TSFN calls can still deadlock during teardown, and context disposal can invalidate open scope stacks.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (2)
Previously missed (1) — in code that hasn't changed since the last review.
src/NodeApi/JSValueScope.cs:341
- This ignores the
runtimeContextargument whenever any scope is current. If that scope belongs to another context, closing it will dispose its ownRuntimeContextat line 393 while the requested context remains live. Only defer onto a scope that belongs to the supplied context; otherwise dispose the supplied context directly (and let its thread-affinity check apply).
src/NodeApi/Interop/JSRuntimeContext.cs:1013
Dispose()can still be called while this context has an open handle scope. It marks the context disposed immediately, so that scope's later close readsRuntimeContext.EnvironmentHandle, throwsObjectDisposedException, and remains on the thread-static stack; the outer scope then cannot close either. Route same-context disposal through the idle deferral before mutatingIsDisposed(or reject it while scopes are open).
// Disposal calls thread-affine napi (the sync context's RemoveEnvCleanupHook), so it must
// run on the thread that created the context -- where the instance-data finalizer and the
// JS dispose functions, the only expected callers, both run.
if (OwningThreadId != Environment.CurrentManagedThreadId)
- Files reviewed: 37/37 changed files
- Comments generated: 1
- Review effort level: Balanced
A napi_value is valid exactly while its JSValueScope is open, and a JSReference is owned by the JSRuntimeContext of its napi_env. - Each napi_env has exactly one JSRuntimeContext, stored in the env instance data and disposed at env teardown by the hosting infrastructure only. - The no-context scope and reference paths are removed, and with them the no-context deletion queue from microsoft#495. - The native and managed hosts, embedding adapters, and generated module entry points create or resolve the context explicitly. Breaking API change: JSValueScope is created through static factory methods, JSValueScopeType is internal, JSModuleContext is replaced by JSValueScope.Module, and JSRuntimeContext is no longer IDisposable.
c53b95a to
590a9a0
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Context lookup can use the wrong runtime or freed instance data, risking crashes, while teardown can leak references or let exceptions cross unmanaged callbacks.
6 open issues
Format instance-data pointers as opaque addresses in tracing · New Retain context lookup storage until all dependent finalizers finish · New Handle queued calls and callback errors while a JS scope is live · New Queue off-thread reference deletions for the next JS-thread entry · New Check disposed references before dispatching Run calls · New Run managed finalizer cleanup when the context is unavailable · New
1 resolved since last review
Review effort: Balanced
- Format instance data as a raw address in TracingJSRuntime; it is a native block, not a GCHandle. - Check for a disposed reference or context in JSReference.Run before dispatching, so a torn-down reference cannot appear to succeed. - Run an AddFinalizer action even when no live context can be entered, so its managed cleanup still happens.
There was a problem hiding this comment.
🔵 Needs a closer look
Queued callbacks can crash after disposal, finalizers can access freed instance data, and reference cleanup can leak objects.
No open issues 🎉
6 resolved since last review
Handle queued calls and callback errors while a JS scope is live Retain context lookup storage until all dependent finalizers finish Format instance-data pointers as opaque addresses in tracing Run managed finalizer cleanup when the context is unavailable Check disposed references before dispatching Run calls Queue off-thread reference deletions for the next JS-thread entry
Review effort: Balanced
The JSValueScope API change is breaking, and .NET modules built with an earlier version must be rebuilt.


Type of change
Why
Node-API values (
napi_value) and references (napi_ref) have strict, environment-scopedlifetimes, but the previous design spread responsibility for them across five
JSValueScopetypes, a separate
JSModuleContext, and a "no-context"JSReferencepath. That made two simpleinvariants hard to guarantee:
napi_valueis valid exactly while itsJSValueScopeis open, andJSReferenceis owned by the oneJSRuntimeContextbound to itsnapi_env.This change makes both invariants structural. It builds on #487, #492, and #495. Because
no-context references no longer exist, the deferred-deletion queue that #495 added for them is
removed; #495's TSFN call gate is unchanged.
What
Values live exactly as long as their scope. Value validity flows only through the owning
JSValueScope, so using a value after its scope closes fails predictably. A scope must be closedon its own thread and in reverse order of creation; a wrong close throws instead of corrupting the
scope stack, and a failed native close can be retried.
One runtime context per
napi_env, disposed at env teardown. The context is stored in theenv's instance data and resolved from it (
JSRuntimeContext.FromEnv), and it is bound to the env'sJS thread. The env's instance-data finalizer disposes it, and a native-to-managed host handshake
does the same for the managed host, without calling into JavaScript. Only the hosting
infrastructure disposes a context.
References belong to that context. Every
JSReferencehas a context. Deletes are posted tothe JS thread, and once the context is disposed a reference never touches the dead env. This
removes the no-context path and the teardown edge cases that came with it.
Simpler
JSValueScopeAPI. Three internal scope types (RuntimeContext,Handle,Escapable) sit behind static factories:CreateRuntimeScope,CreateHandleScope,CreateEscapableScope, andCreateModuleScope, plusJSRuntimeContext.Create. A small moduleholder replaces
JSModuleContext, so each loaded module resolves its own instance, and anIDisposablemodule is disposed once at env teardown.Hosts, embedding, and generated code updated. The native and managed hosts, the embedding
adapters, and the generated module entry points create or resolve the context explicitly, and
their callbacks no longer let exceptions cross the native boundary.
Tests and docs. The scope and reference unit tests are rewritten for the new model, a
worker-teardown stress test repeatedly loads and tears down the host, and the value-scope docs use
the new factories.
Breaking changes
.NET modules built with an earlier version of
Microsoft.JavaScript.NodeApi.Generatormust berebuilt, because their generated code calls the removed
JSValueScopeconstructor. Source changes:new JSValueScope()→JSValueScope.CreateHandleScope()new JSValueScope(JSValueScopeType.Escapable)→JSValueScope.CreateEscapableScope()new JSValueScope(JSValueScopeType.Callback)→JSValueScope.CreateRuntimeScope()new JSValueScope(JSValueScopeType.Root, env, runtime)→ create the env's context once withJSRuntimeContext.Create(env, runtime), then open scopes withJSValueScope.CreateRuntimeScope(env, context)JSModuleContext.Current.Module→JSValueScope.Current.Module, andscope.ModuleContext.Module→
scope.Module(JSRuntimeContext)env→JSRuntimeContext.FromEnv(env), which returnsnullwhen the env has nocontext
JSRuntimeContext.Dispose()is removed; the context is disposed when its env is torn down.JSValueScopeTypeandJSValueScope.ScopeTypeare internal, and theNoContextscope type is gone.Testing
Built and packed in Release; the full test suite passes on net10.0, net9.0, net8.0, and net472.
Release notes
Should this change be included in the release notes: yes — Object-lifetime safety: a
napi_valueis valid exactly while itsJSValueScopeis open, and aJSReferenceis owned by theJSRuntimeContextof itsnapi_env. Breaking (version 0.10):JSValueScopeis created throughstatic factory methods,
JSValueScopeTypeis internal,JSModuleContextis replaced byJSValueScope.Module,JSRuntimeContextis no longer publicly disposable, and .NET modules builtwith an earlier version must be rebuilt.