From 6807c5d0c2361d0636f5826c7e0abac0a2898c5c Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Sat, 28 Nov 2026 15:12:12 +0000 Subject: [PATCH 1/8] [refactor] Align observable subscriptions with node entity lifecycle --- lib/node.js | 33 +++++- lib/observable_subscription.js | 63 ++++++++---- lib/subscription.js | 2 +- test/test-observable-subscription.js | 144 +++++++++++++++++++++++++-- types/node.d.ts | 2 + types/observable_subscription.d.ts | 12 ++- 6 files changed, 218 insertions(+), 38 deletions(-) diff --git a/lib/node.js b/lib/node.js index 00115c0ab..dfa720527 100644 --- a/lib/node.js +++ b/lib/node.js @@ -42,7 +42,9 @@ import QoS from './qos.js'; import * as Rates from './rate.js'; import Service from './service.js'; import Subscription from './subscription.js'; -import ObservableSubscription from './observable_subscription.js'; +import ObservableSubscription, { + ObservableSubscriptionEntity, +} from './observable_subscription.js'; import MessageInfo from './message_info.js'; import ActionEndpointInfo from './action/endpoint_info.js'; import { declareQosParameters, _resolveQoS } from './qos_overriding_options.js'; @@ -910,6 +912,25 @@ class Node extends rclnodejs.ShadowNode { * @see {@link https://www.omg.org/spec/DDS/1.4/PDF|Content-filter details at DDS 1.4 specification, Annex B} */ createSubscription(typeClass, topic, options, callback, eventCallbacks) { + const subscription = this._createSubscription( + Subscription, + typeClass, + topic, + options, + callback, + eventCallbacks + ); + return this._registerEntity('subscriptions', subscription); + } + + _createSubscription( + SubscriptionClass, + typeClass, + topic, + options, + callback, + eventCallbacks + ) { if (typeof typeClass === 'string' || typeof typeClass === 'object') { typeClass = loader.loadInterface(typeClass); } @@ -970,7 +991,7 @@ class Node extends rclnodejs.ShadowNode { ); } - let subscription = Subscription.createSubscription( + let subscription = SubscriptionClass.createSubscription( this, typeClass, topic, @@ -979,12 +1000,14 @@ class Node extends rclnodejs.ShadowNode { eventCallbacks ); debug('Finish creating subscription, topic = %s.', topic); - return this._registerEntity('subscriptions', subscription); + return subscription; } /** * Create a Subscription that returns an RxJS Observable. * This allows using reactive programming patterns with ROS 2 messages. + * The node owns the underlying subscription and completes the observable + * when that subscription or the node is destroyed. * * @param {function|string|object} typeClass - The ROS message class, * OR a string representing the message class, e.g. 'std_msgs/msg/String', @@ -1002,7 +1025,8 @@ class Node extends rclnodejs.ShadowNode { createObservableSubscription(typeClass, topic, options, eventCallbacks) { let observableSubscription = null; - const subscription = this.createSubscription( + const subscription = this._createSubscription( + ObservableSubscriptionEntity, typeClass, topic, options, @@ -1015,6 +1039,7 @@ class Node extends rclnodejs.ShadowNode { ); observableSubscription = new ObservableSubscription(subscription, this); + this._registerEntity('subscriptions', subscription); return observableSubscription; } diff --git a/lib/observable_subscription.js b/lib/observable_subscription.js index 2dd4f1b81..b735e0548 100644 --- a/lib/observable_subscription.js +++ b/lib/observable_subscription.js @@ -13,29 +13,55 @@ // limitations under the License. import { Subject } from 'rxjs'; +import Subscription from './subscription.js'; + +/** + * Native-backed subscription that finalizes its observable with the entity. + * @ignore + */ +export class ObservableSubscriptionEntity extends Subscription { + #subject = new Subject(); + + get observable() { + return this.#subject.asObservable(); + } + + _emit(message) { + if (!this.isDestroyed()) { + this.#subject.next(message); + } + } + + finalizeDestruction() { + if (this.isDestroyed()) return; + + try { + super.finalizeDestruction(); + } finally { + this.#subject.complete(); + } + } +} /** * A wrapper that provides RxJS Observable support for ROS 2 subscriptions. - * This class wraps a standard Subscription and emits messages through an Observable. + * The node owns the underlying subscription and completes the observable when + * that subscription or the node is destroyed. * * @class ObservableSubscription * @hideconstructor */ class ObservableSubscription { #subscription; - #subject; - #destroyed; #node; /** * Create an ObservableSubscription wrapper. - * @param {Subscription} subscription - The underlying ROS 2 subscription + * @param {ObservableSubscriptionEntity} subscription - The underlying ROS 2 subscription * @param {Node} node - The node that owns the subscription, used to destroy it */ constructor(subscription, node) { this.#subscription = subscription; - this.#subject = new Subject(); - this.#destroyed = false; this.#node = node; } @@ -45,7 +71,7 @@ class ObservableSubscription { * @type {Observable} */ get observable() { - return this.#subject.asObservable(); + return this.#subscription.observable; } /** @@ -65,11 +91,12 @@ class ObservableSubscription { } /** - * Check if this observable subscription has been destroyed. + * Check if the underlying subscription has been destroyed, including by + * node teardown. * @type {boolean} */ get isDestroyed() { - return this.#destroyed; + return this.#subscription.isDestroyed(); } /** @@ -79,23 +106,17 @@ class ObservableSubscription { * @param {any} message - The message to emit */ _emit(message) { - if (!this.#destroyed) { - this.#subject.next(message); - } + this.#subscription._emit(message); } /** - * Complete the observable and clean up resources. - * After calling this, no more messages will be emitted, and the underlying - * ROS 2 subscription is destroyed so it stops receiving and deserializing - * messages. + * Destroy the underlying ROS 2 subscription through its node and complete + * the observable. Destruction is idempotent and can be retried if handle + * synchronization fails before native cleanup. + * Unsubscribing from the observable alone does not destroy the subscription. */ complete() { - if (!this.#destroyed) { - this.#destroyed = true; - this.#subject.complete(); - this.#node.destroySubscription(this.#subscription); - } + this.#node.destroySubscription(this.#subscription); } /** diff --git a/lib/subscription.js b/lib/subscription.js index ac7769602..324c2722d 100644 --- a/lib/subscription.js +++ b/lib/subscription.js @@ -111,7 +111,7 @@ class Subscription extends Entity { topic, options ); - return new Subscription( + return new this( handle, typeClass, topic, diff --git a/test/test-observable-subscription.js b/test/test-observable-subscription.js index ff38c36c1..96dca5aa8 100644 --- a/test/test-observable-subscription.js +++ b/test/test-observable-subscription.js @@ -15,8 +15,10 @@ import assert from 'assert'; import rclnodejs from '../index.js'; import rxjs from 'rxjs'; +import DistroUtils from '../lib/distro.js'; +import { SubscriptionEventCallbacks } from '../lib/event_handler.js'; -const { take, map, filter, toArray } = rxjs; +const { take, map, filter, toArray, finalize } = rxjs; describe('rclnodejs observable subscription test suite', function () { this.timeout(60 * 1000); @@ -32,6 +34,8 @@ describe('rclnodejs observable subscription test suite', function () { it('createObservableSubscription returns an ObservableSubscription', function () { const node = new rclnodejs.Node('test_node'); const String = 'std_msgs/msg/String'; + const subscriptions = node._subscriptions; + const subscriptionCount = subscriptions.length; const obsSub = node.createObservableSubscription(String, 'test_topic'); @@ -40,6 +44,8 @@ describe('rclnodejs observable subscription test suite', function () { assert.ok(obsSub.subscription, 'Should have a subscription property'); assert.ok(obsSub.topic.includes('test_topic')); assert.strictEqual(obsSub.isDestroyed, false); + assert.strictEqual(subscriptions.length, subscriptionCount + 1); + assert.ok(subscriptions.includes(obsSub.subscription)); node.destroy(); }); @@ -209,16 +215,138 @@ describe('rclnodejs observable subscription test suite', function () { it('underlying subscription can be destroyed via node', function () { const node = new rclnodejs.Node('test_node'); - const String = 'std_msgs/msg/String'; + try { + const obsSub = node.createObservableSubscription( + 'std_msgs/msg/String', + 'destroy_sub_test_topic' + ); + let completions = 0; + obsSub.observable.subscribe({ + complete: () => completions++, + }); - const obsSub = node.createObservableSubscription( - String, - 'destroy_sub_test_topic' - ); + node.destroySubscription(obsSub.subscription); + obsSub.destroy(); + obsSub.complete(); - node.destroySubscription(obsSub.subscription); + assert.strictEqual(obsSub.isDestroyed, true); + assert.strictEqual(completions, 1); + assert.ok(!node._subscriptions.includes(obsSub.subscription)); + } finally { + node.destroy(); + } + }); - node.destroy(); + it('node teardown completes observables after entity cleanup and runs finalizers once', function () { + const node = new rclnodejs.Node('test_node'); + const subscriptions = node._subscriptions; + try { + let eventCallbacks; + if (DistroUtils.getDistroId() >= DistroUtils.getDistroId('jazzy')) { + eventCallbacks = new SubscriptionEventCallbacks(); + eventCallbacks.deadline = () => {}; + } + const observables = ['first', 'second'].map((name) => + node.createObservableSubscription( + 'std_msgs/msg/String', + `node_teardown_${name}`, + undefined, + eventCallbacks + ) + ); + const events = observables.flatMap( + (obsSub) => obsSub.subscription.events || [] + ); + const completions = []; + let finalizations = 0; + for (const obsSub of observables) { + obsSub.observable + .pipe( + finalize(() => { + finalizations++; + obsSub.destroy(); + }) + ) + .subscribe({ + complete: () => { + completions.push({ + destroyed: obsSub.isDestroyed, + registered: subscriptions.includes(obsSub.subscription), + eventsDestroyed: events.every((event) => event.isDestroyed()), + }); + }, + }); + } + node.spin(-1); + node.destroy(); + for (const obsSub of observables) { + obsSub.destroy(); + obsSub.complete(); + } + + assert.strictEqual(node.spinning, false); + assert.strictEqual(subscriptions.length, 0); + assert.strictEqual(completions.length, observables.length); + assert.strictEqual(finalizations, observables.length); + for (const completion of completions) { + assert.deepStrictEqual(completion, { + destroyed: true, + registered: false, + eventsDestroyed: true, + }); + } + } finally { + node.destroy(); + } + }); + + it('retries destruction after handle synchronization fails', function () { + const node = new rclnodejs.Node('test_node'); + let obsSub; + try { + obsSub = node.createObservableSubscription( + 'std_msgs/msg/String', + 'retry_destruction_topic' + ); + let completions = 0; + obsSub.observable.subscribe({ + complete: () => completions++, + }); + node.spin(-1); + const nativeSync = node.syncHandles.bind(node); + let synchronizations = 0; + Object.defineProperty(node, 'syncHandles', { + configurable: true, + value: () => { + synchronizations++; + if (synchronizations === 1) { + throw new Error('Injected handle synchronization failure'); + } + nativeSync(); + }, + }); + + assert.throws( + () => obsSub.destroy(), + /Injected handle synchronization failure/ + ); + assert.strictEqual(obsSub.isDestroyed, false); + assert.strictEqual(obsSub.subscription.isDestroyed(), false); + assert.strictEqual(completions, 0); + + obsSub.destroy(); + obsSub.complete(); + + assert.strictEqual(obsSub.isDestroyed, true); + assert.strictEqual(obsSub.subscription.isDestroyed(), true); + assert.strictEqual(completions, 1); + assert.strictEqual(synchronizations, 2); + assert.ok(!node._subscriptions.includes(obsSub.subscription)); + } finally { + delete node.syncHandles; + if (obsSub) node.destroySubscription(obsSub.subscription); + node.destroy(); + } }); // Regression test: destroy()/complete() used to only complete the RxJS diff --git a/types/node.d.ts b/types/node.d.ts index 25b8f2124..330075a1f 100644 --- a/types/node.d.ts +++ b/types/node.d.ts @@ -432,6 +432,8 @@ declare module 'rclnodejs' { /** * Create a Subscription that returns an RxJS Observable. * This allows using reactive programming patterns with ROS 2 messages. + * The node owns the underlying subscription and completes the observable + * when that subscription or the node is destroyed. * * @param typeClass - Type of ROS messages the subscription will subscribe to. * @param topic - Name of the topic the subscription will subscribe to. diff --git a/types/observable_subscription.d.ts b/types/observable_subscription.d.ts index c02138650..31d20a65e 100644 --- a/types/observable_subscription.d.ts +++ b/types/observable_subscription.d.ts @@ -1,7 +1,8 @@ declare module 'rclnodejs' { /** * A wrapper that provides RxJS Observable support for ROS 2 subscriptions. - * This class wraps a standard Subscription and emits messages through an Observable. + * The node owns the underlying subscription and completes the observable + * when that subscription or the node is destroyed. */ class ObservableSubscription { /** @@ -21,13 +22,16 @@ declare module 'rclnodejs' { readonly topic: string; /** - * Check if this observable subscription has been destroyed. + * Check if the underlying subscription has been destroyed, including by + * node teardown. */ readonly isDestroyed: boolean; /** - * Complete the observable and clean up resources. - * After calling this, no more messages will be emitted. + * Destroy the underlying ROS 2 subscription through its node and complete + * the observable. Destruction is idempotent and can be retried if handle + * synchronization fails before native cleanup. + * Unsubscribing from the observable alone does not destroy the subscription. */ complete(): void; From 08b4002622bc38cb3464a187a63571e542ecc376 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Sat, 28 Nov 2026 14:57:30 +0000 Subject: [PATCH 2/8] Guard node and context teardown reentrancy Reject creation and dispatch during teardown, preserve cleanup retries, and cover generic finalizer reentrancy independently of observable subscriptions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lib/context.js | 63 ++++++++++-------- lib/node.js | 95 +++++++++++++++++++++------ test/test-context.js | 93 +++++++++++++++++++++++++++ test/test-destruction.js | 134 +++++++++++++++++++++++++++++++++++++++ types/context.d.ts | 2 + types/node.d.ts | 6 +- 6 files changed, 348 insertions(+), 45 deletions(-) diff --git a/lib/context.js b/lib/context.js index a6a308b1d..c2c969825 100644 --- a/lib/context.js +++ b/lib/context.js @@ -67,6 +67,7 @@ class Context { constructor(domainId) { this._handle = rclnodejs.createContext(); this._isShutdown = false; + this._isShuttingDown = false; this._nodes = []; this._domainId = domainId; Context._instances.push(this); @@ -142,31 +143,38 @@ class Context { /** * Shut down the context including destroying all nodes. + * Reentrant shutdown is ignored, and node creation is rejected while + * shutdown is in progress. * @returns {undefined} * @throws {Error} If there is a problem shutting down the context. */ shutdown() { - if (this.isShutdown()) return; + if (this.isShutdown() || this._isShuttingDown) return; - // shutdown and remove all nodes - for (const node of this.nodes) { - node.destroy(); - } + this._isShuttingDown = true; + try { + // shutdown and remove all nodes + for (const node of this.nodes) { + node.destroy(); + } - if (this.isInitialized()) { - rclnodejs.shutdown(this.handle); - } + if (this.isInitialized()) { + rclnodejs.shutdown(this.handle); + } - this._isShutdown = true; + this._isShutdown = true; - // remove context from _instances[] - const index = Context._instances.indexOf(this); - if (index > -1) { - Context._instances.splice(index, 1); - } + // remove context from _instances[] + const index = Context._instances.indexOf(this); + if (index > -1) { + Context._instances.splice(index, 1); + } - if (this.isDefaultContext()) { - defaultContext = null; + if (this.isDefaultContext()) { + defaultContext = null; + } + } finally { + this._isShuttingDown = false; } } @@ -181,6 +189,19 @@ class Context { } } + _assertNodeCreationAllowed() { + if (this.isShutdown() || this._isShuttingDown) { + const state = this._isShuttingDown ? 'shutting down' : 'shutdown'; + throw new OperationError( + `Can not add a Node to a Context that is ${state}`, + { + code: 'CONTEXT_SHUTDOWN', + entityType: 'context', + } + ); + } + } + onNodeCreated(node) { if (!node) { throw new OperationError('Node must be defined to add to Context', { @@ -189,15 +210,7 @@ class Context { }); } - if (this.isShutdown()) { - throw new OperationError( - 'Can not add a Node to a Context that is shutdown', - { - code: 'CONTEXT_SHUTDOWN', - entityType: 'context', - } - ); - } + this._assertNodeCreationAllowed(); if (this._nodes.includes(node)) { // do nothing diff --git a/lib/node.js b/lib/node.js index dfa720527..254104bf6 100644 --- a/lib/node.js +++ b/lib/node.js @@ -73,7 +73,7 @@ class Node extends rclnodejs.ShadowNode { * @param {string} [namespace=''] - The namespace used in ROS. * @param {Context} [context=Context.defaultContext()] - The context to create the node in. * @param {NodeOptions} [options=NodeOptions.defaultOptions] - The options to configure the new node behavior. - * @throws {Error} If the given context is not registered. + * @throws {Error} If the context is not initialized, shut down, or shutting down. */ constructor( nodeName, @@ -125,6 +125,7 @@ class Node extends rclnodejs.ShadowNode { _init(name, namespace, options, context, args, useGlobalArguments) { options = Node._normalizeOptions(options); + context._assertNodeCreationAllowed(); this.handle = rclnodejs.createNode( name, @@ -163,6 +164,8 @@ class Node extends rclnodejs.ShadowNode { this._postSetParametersCallbacks = []; this._logger = new Logging(rclnodejs.getNodeLoggerName(this.handle)); this._spinning = false; + this._destroying = false; + this._destroyed = false; // Detects stop/destroy during a ready batch, even if spinning restarts. this._dispatchGeneration = 0; this._enableRosout = options.enableRosout; @@ -547,10 +550,20 @@ class Node extends rclnodejs.ShadowNode { * reported through Node.js uncaught exception handling. * @param {Node} node - The node to be spun up. * @param {number} [timeout=10] - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0. - * @throws {Error} If the node is already spinning or native executor cleanup is still in progress. + * @throws {Error} If the node or context is being destroyed or already destroyed, the node is already spinning, or native executor cleanup is still in progress. * @return {undefined} */ spin(timeout = 10) { + if (this._destroying || this._destroyed) { + throw new Error( + 'Cannot spin a node while it is being destroyed or has been destroyed.' + ); + } + if (this.context._isShuttingDown || this.context.isShutdown()) { + throw new Error( + 'Cannot spin a node while its context is shutting down or shut down.' + ); + } if (this.spinning) { throw new Error('The node is already spinning.'); } @@ -604,10 +617,20 @@ class Node extends rclnodejs.ShadowNode { * A synchronous callback exception stops the current ready batch and is thrown to the caller. * @param {Node} node - The node to be spun. * @param {number} [timeout=10] - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0. - * @throws {Error} If the node is already spinning or native executor cleanup is still in progress. + * @throws {Error} If the node or context is being destroyed or already destroyed, the node is already spinning, or native executor cleanup is still in progress. * @return {undefined} */ spinOnce(timeout = 10) { + if (this._destroying || this._destroyed) { + throw new Error( + 'Cannot spin a node while it is being destroyed or has been destroyed.' + ); + } + if (this.context._isShuttingDown || this.context.isShutdown()) { + throw new Error( + 'Cannot spin a node while its context is shutting down or shut down.' + ); + } if (this.spinning) { throw new Error('The node is already spinning.'); } @@ -615,14 +638,37 @@ class Node extends rclnodejs.ShadowNode { } _registerEntity(kind, entity) { + if ( + this._destroying || + this._destroyed || + this.context._isShuttingDown || + this.context.isShutdown() + ) { + this._destroyEntity(kind, entity); + } + this._assertEntityCreationAllowed(); return this._entityRegistry.register(kind, entity); } + _assertEntityCreationAllowed() { + if (this._destroying || this._destroyed) { + throw new Error( + 'Cannot create entities while the node is being destroyed or has been destroyed.' + ); + } + if (this.context._isShuttingDown || this.context.isShutdown()) { + throw new Error( + 'Cannot create entities while the context is shutting down or shut down.' + ); + } + } + _destroyEntity(kind, entity) { this._entityRegistry.destroy(kind, entity); } _validateOptions(options) { + this._assertEntityCreationAllowed(); if ( options !== undefined && (options === null || typeof options !== 'object') @@ -678,6 +724,7 @@ class Node extends rclnodejs.ShadowNode { * @return {Timer} - An instance of Timer. */ createTimer(period, callback, optionsOrClock = null, clock = null) { + this._assertEntityCreationAllowed(); let options = {}; if (optionsOrClock instanceof Clock.Clock) { @@ -752,6 +799,7 @@ class Node extends rclnodejs.ShadowNode { * @returns {Promise} - Promise resolving to new instance of Rate. */ async createRate(hz = 1) { + this._assertEntityCreationAllowed(); if (typeof hz !== 'number') { throw new TypeValidationError('hz', hz, 'number', { nodeName: this.name(), @@ -1202,6 +1250,7 @@ class Node extends rclnodejs.ShadowNode { * @return {GuardCondition} - An instance of GuardCondition. */ createGuardCondition(callback) { + this._assertEntityCreationAllowed(); if (typeof callback !== 'function') { throw new TypeValidationError('callback', callback, 'function', { nodeName: this.name(), @@ -1218,29 +1267,39 @@ class Node extends rclnodejs.ShadowNode { * Destroy all resource allocated by this node, including * Timers/Publishers/Subscriptions * /Clients/Services + * Reentrant destruction is ignored. New entities and spinning are rejected + * during and after node destruction, and while its context is shutting down. * @return {undefined} */ destroy() { - this._dispatchGeneration++; - if (this.spinning) { - this.stop(); - } + if (this._destroying) return; - this._entityRegistry.destroyAll(); + this._destroying = true; + try { + this._dispatchGeneration++; + if (this.spinning) { + this.stop(); + } - this.context.onNodeDestroyed(this); + this._entityRegistry.destroyAll(); - if (this._enableRosout) { - rclnodejs.finiRosoutPublisherForNode(this.handle); - this._enableRosout = false; - } + this._destroyed = true; + this.context.onNodeDestroyed(this); - this.handle.release(); - this._clock = null; + if (this._enableRosout) { + rclnodejs.finiRosoutPublisherForNode(this.handle); + this._enableRosout = false; + } + + this.handle.release(); + this._clock = null; - if (this._rateTimerServer) { - this._rateTimerServer.shutdown(); - this._rateTimerServer = null; + if (this._rateTimerServer) { + this._rateTimerServer.shutdown(); + this._rateTimerServer = null; + } + } finally { + this._destroying = false; } } diff --git a/test/test-context.js b/test/test-context.js index 10e683af9..7e6204b3c 100644 --- a/test/test-context.js +++ b/test/test-context.js @@ -15,6 +15,8 @@ import assert from 'assert'; import { execFile } from 'node:child_process'; import rclnodejs from '../index.js'; +import sinon from 'sinon'; +import nativeLoader from '../lib/native_loader.js'; describe('context test suite', function () { this.timeout(60 * 1000); @@ -96,6 +98,97 @@ describe('context test suite', function () { assert.doesNotThrow(() => context.shutdown()); }); + it('rejects native node allocation during reentrant context shutdown', async function () { + const context = new rclnodejs.Context(); + await rclnodejs.init(context); + const previous = new rclnodejs.Node('previous_node', '', context); + const node = new rclnodejs.Node('reentrant_context', '', context); + const next = new rclnodejs.Node('next_node', '', context); + const sandbox = sinon.createSandbox(); + let rateRejection; + let callbacks = 0; + let startAttempts = 0; + try { + const subscription = node.createSubscription( + 'std_msgs/msg/String', + 'context_teardown_topic', + () => {} + ); + const createNode = sandbox + .stub(nativeLoader, 'createNode') + .throws(new Error('Unexpected native node allocation during shutdown')); + const createGuard = sandbox + .stub(nativeLoader, 'createGuardCondition') + .throws( + new Error('Unexpected native guard allocation during shutdown') + ); + const finalize = subscription.finalizeDestruction.bind(subscription); + Object.defineProperty(subscription, 'finalizeDestruction', { + configurable: true, + value: () => { + if (subscription.isDestroyed()) return; + finalize(); + callbacks++; + context.shutdown(); + assert.strictEqual(context.isShutdown(), false); + assert.strictEqual(context.isValid(), true); + for (const target of [previous, next]) { + Object.defineProperty(target, 'start', { + configurable: true, + value: () => startAttempts++, + }); + assert.throws( + () => target.createGuardCondition(() => {}), + /destroyed|shutting down/ + ); + assert.throws(() => target.spin(-1), /destroyed|shutting down/); + assert.throws(() => target.spinOnce(0), /destroyed|shutting down/); + } + rateRejection = assert.rejects( + next.createRate(10), + /context is shutting down/ + ); + for (const create of [ + () => new rclnodejs.Node('blocked_node', '', context), + () => rclnodejs.createNode('blocked_factory_node', '', context), + ]) { + assert.throws(create, /Context that is shutting down/); + } + }, + }); + node.spin(-1); + context.shutdown(); + await rateRejection; + + assert.strictEqual(createNode.callCount, 0); + assert.strictEqual(createGuard.callCount, 0); + assert.strictEqual(startAttempts, 0); + assert.strictEqual(callbacks, 1); + assert.strictEqual(context.isShutdown(), true); + assert.strictEqual(context.isValid(), false); + assert.strictEqual(context.nodes.length, 0); + assert.strictEqual(node.spinning, false); + assert.strictEqual(subscription.isDestroyed(), true); + for (const target of [previous, next]) { + assert.strictEqual(target.spinning, false); + for (const entities of Object.values( + target._entityRegistry.collections + )) { + assert.strictEqual(entities.length, 0); + } + } + } finally { + sandbox.restore(); + for (const target of [previous, next]) { + delete target.start; + if (target.spinning) target.stop(); + target.destroy(); + } + node.destroy(); + context.shutdown(); + } + }); + it('context domain id', async function () { let context = new rclnodejs.Context(BigInt(123)); await rclnodejs.init(context); diff --git a/test/test-destruction.js b/test/test-destruction.js index c1f4bd73d..b6b23f53f 100644 --- a/test/test-destruction.js +++ b/test/test-destruction.js @@ -16,6 +16,7 @@ import assert from 'assert'; import childProcess from 'child_process'; import sinon from 'sinon'; import rclnodejs from '../index.js'; +import nativeLoader from '../lib/native_loader.js'; import Entity from '../lib/entity.js'; import { fileURLToPath } from 'url'; import { dirname } from 'path'; @@ -111,6 +112,139 @@ describe('Node & Entity destroy testing', function () { } }); + it('rejects entity creation and spin restarts during and after node teardown', async function () { + const node = rclnodejs.createNode('reentrant_teardown'); + const sandbox = sinon.createSandbox(); + let unregisteredGuard; + let rateRejection; + let releases = 0; + let startAttempts = 0; + try { + const subscription = node.createSubscription( + 'std_msgs/msg/String', + 'reentrant_teardown_topic', + () => {} + ); + Object.defineProperty(node, '_registerEntity', { + configurable: true, + value: (kind, entity) => entity, + }); + unregisteredGuard = node.createGuardCondition(() => {}); + delete node._registerEntity; + const release = unregisteredGuard.handle.release.bind( + unregisteredGuard.handle + ); + Object.defineProperty(unregisteredGuard.handle, 'release', { + configurable: true, + value: () => { + releases++; + release(); + }, + }); + const creators = [ + 'createPublisher', + 'createSubscription', + 'createClient', + 'createService', + 'createTimer', + 'createGuardCondition', + ].map((name) => + sandbox + .stub(nativeLoader, name) + .throws(new Error('Unexpected native allocation during teardown')) + ); + const factories = [ + () => node.createPublisher('std_msgs/msg/String', 'blocked_pub'), + () => + node.createSubscription( + 'std_msgs/msg/String', + 'blocked_sub', + () => {} + ), + () => + node.createObservableSubscription( + 'std_msgs/msg/String', + 'blocked_observable' + ), + () => + node.createClient( + 'example_interfaces/srv/AddTwoInts', + 'blocked_client' + ), + () => + node.createService( + 'example_interfaces/srv/AddTwoInts', + 'blocked_service', + () => {} + ), + () => node.createTimer(1000000000n, () => {}), + () => node.createGuardCondition(() => {}), + ]; + const finalize = subscription.finalizeDestruction.bind(subscription); + Object.defineProperty(subscription, 'finalizeDestruction', { + configurable: true, + value: () => { + if (subscription.isDestroyed()) return; + finalize(); + node.destroy(); + assert.throws( + () => node._registerEntity('guards', unregisteredGuard), + /Cannot create entities while the node is being destroyed/ + ); + for (const create of factories) { + assert.throws( + create, + /Cannot create entities while the node is being destroyed/ + ); + } + rateRejection = assert.rejects( + node.createRate(10), + /Cannot create entities while the node is being destroyed/ + ); + Object.defineProperty(node, 'start', { + configurable: true, + value: () => startAttempts++, + }); + for (const spin of [() => node.spin(-1), () => node.spinOnce(0)]) { + assert.throws( + spin, + /Cannot spin a node while it is being destroyed/ + ); + } + }, + }); + node.spin(-1); + node.destroy(); + await rateRejection; + + for (const create of factories) { + assert.throws(create, /has been destroyed/); + } + await assert.rejects(node.createRate(10), /has been destroyed/); + assert.throws(() => node.spin(-1), /has been destroyed/); + assert.throws(() => node.spinOnce(0), /has been destroyed/); + assert.strictEqual(startAttempts, 0); + assert.strictEqual(node.spinning, false); + assert.strictEqual(releases, 1); + for (const create of creators) { + assert.strictEqual(create.callCount, 0); + } + for (const entities of Object.values(node._entityRegistry.collections)) { + assert.strictEqual(entities.length, 0); + } + } finally { + sandbox.restore(); + delete node.start; + delete node._registerEntity; + if (unregisteredGuard) { + delete unregisteredGuard.handle.release; + node.destroyGuardCondition(unregisteredGuard); + } + if (node.spinning) node.stop(); + node.destroy(); + } + }); + for (const teardown of ['node', 'context']) { for (const spinning of [false, true]) { it(`${teardown} teardown destroys every action${spinning ? ' while spinning' : ''}`, async function () { diff --git a/types/context.d.ts b/types/context.d.ts index 713720a21..bc5c0d861 100644 --- a/types/context.d.ts +++ b/types/context.d.ts @@ -75,6 +75,8 @@ declare module 'rclnodejs' { /** * Shutdown the context, includes destroying all nodes. + * Reentrant shutdown is ignored, and node creation is rejected while + * shutdown is in progress. */ shutdown(): void; diff --git a/types/node.d.ts b/types/node.d.ts index 330075a1f..74cdb0923 100644 --- a/types/node.d.ts +++ b/types/node.d.ts @@ -329,7 +329,7 @@ declare module 'rclnodejs' { * reported through Node.js uncaught exception handling. * @param node - The node to be spun up. * @param - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0. - * @throws Error if the node is already spinning or native executor cleanup is still in progress. + * @throws Error if the node or context is being destroyed or already destroyed, the node is already spinning, or native executor cleanup is still in progress. */ spin(timeout?: number): void; @@ -339,7 +339,7 @@ declare module 'rclnodejs' { * A synchronous callback exception stops the current ready batch and is thrown to the caller. * @param node - The node to be spun. * @param - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0. - * @throws An error if the node is already spinning or native executor cleanup is still in progress. + * @throws An error if the node or context is being destroyed or already destroyed, the node is already spinning, or native executor cleanup is still in progress. */ spinOnce(timeout?: number): void; @@ -530,6 +530,8 @@ declare module 'rclnodejs' { * Destroy all entities allocated by this node, including * Timers, Publishers, Subscriptions, Clients, Services * and Timers. + * Reentrant destruction is ignored. New entities and spinning are rejected + * during and after node destruction, and while its context is shutting down. */ destroy(): void; From 68f3b88be2164f423a2f58b7d46fbfd600f23e3a Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Sun, 29 Nov 2026 15:50:44 +0000 Subject: [PATCH 3/8] Fix spin regression fixture for teardown guards Keep the node's owning context live while forcing real native startup failure through an uninitialized context. Verify failed starts preserve stopped state and can recover without weakening teardown guards. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- test/test-spinning.js | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/test/test-spinning.js b/test/test-spinning.js index a69eabdf2..3d206b7f4 100644 --- a/test/test-spinning.js +++ b/test/test-spinning.js @@ -878,13 +878,29 @@ describe('Spin testing', function () { it('reports guard initialization failure without marking the node as spinning', function (done) { runInChild( ` - context.shutdown(); - assert.throws( - () => node.spin(-1), - /Failed to initialize executor guard condition/ - ); - assert.equal(node.spinning, false); + const invalidContext = new rclnodejs.Context(); + const nativeStart = node.start.bind(node); + try { + Object.defineProperty(node, 'start', { + configurable: true, + value: (_contextHandle, timeout) => + nativeStart(invalidContext.handle, timeout), + }); + for (let attempt = 0; attempt < 2; attempt++) { + assert.throws( + () => node.spin(-1), + /Failed to initialize executor guard condition/ + ); + assert.equal(node.spinning, false); + } + } finally { + delete node.start; + invalidContext.shutdown(); + } + node.spin(-1); + assert.equal(node.spinning, true); node.stop(); + assert.equal(node.spinning, false); `, done ); From 66843bc5e37cf071d587453bb8fa49e9bcb66153 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Mon, 30 Nov 2026 03:38:11 +0000 Subject: [PATCH 4/8] Fix context issue --- lib/context.js | 25 ++++- lib/node.js | 10 +- test/test-context.js | 235 +++++++++++++++++++++++++++++++++++++++++++ types/context.d.ts | 2 + types/node.d.ts | 1 + 5 files changed, 270 insertions(+), 3 deletions(-) diff --git a/lib/context.js b/lib/context.js index c2c969825..d056c86d9 100644 --- a/lib/context.js +++ b/lib/context.js @@ -68,6 +68,7 @@ class Context { this._handle = rclnodejs.createContext(); this._isShutdown = false; this._isShuttingDown = false; + this._shutdownDeferred = false; this._nodes = []; this._domainId = domainId; Context._instances.push(this); @@ -145,6 +146,8 @@ class Context { * Shut down the context including destroying all nodes. * Reentrant shutdown is ignored, and node creation is rejected while * shutdown is in progress. + * If a node is already being destroyed, native shutdown is deferred until + * its teardown finishes. Cleanup failures leave the context open for retry. * @returns {undefined} * @throws {Error} If there is a problem shutting down the context. */ @@ -158,6 +161,11 @@ class Context { node.destroy(); } + if (this._nodes.length > 0) { + this._shutdownDeferred = true; + return; + } + if (this.isInitialized()) { rclnodejs.shutdown(this.handle); } @@ -174,7 +182,7 @@ class Context { defaultContext = null; } } finally { - this._isShuttingDown = false; + if (!this._shutdownDeferred) this._isShuttingDown = false; } } @@ -189,6 +197,21 @@ class Context { } } + _onNodeDestructionFinished(node, completed) { + let resumeShutdown; + try { + if (!completed) return; + this.onNodeDestroyed(node); + resumeShutdown = this._shutdownDeferred; + } finally { + if (this._shutdownDeferred) { + this._shutdownDeferred = false; + this._isShuttingDown = false; + } + } + if (resumeShutdown) this.shutdown(); + } + _assertNodeCreationAllowed() { if (this.isShutdown() || this._isShuttingDown) { const state = this._isShuttingDown ? 'shutting down' : 'shutdown'; diff --git a/lib/node.js b/lib/node.js index 254104bf6..de75ab0ab 100644 --- a/lib/node.js +++ b/lib/node.js @@ -1269,12 +1269,14 @@ class Node extends rclnodejs.ShadowNode { * /Clients/Services * Reentrant destruction is ignored. New entities and spinning are rejected * during and after node destruction, and while its context is shutting down. + * The node stays registered with its context until cleanup succeeds. * @return {undefined} */ destroy() { if (this._destroying) return; this._destroying = true; + let destructionComplete = false; try { this._dispatchGeneration++; if (this.spinning) { @@ -1284,7 +1286,6 @@ class Node extends rclnodejs.ShadowNode { this._entityRegistry.destroyAll(); this._destroyed = true; - this.context.onNodeDestroyed(this); if (this._enableRosout) { rclnodejs.finiRosoutPublisherForNode(this.handle); @@ -1298,8 +1299,13 @@ class Node extends rclnodejs.ShadowNode { this._rateTimerServer.shutdown(); this._rateTimerServer = null; } + destructionComplete = true; } finally { - this._destroying = false; + try { + this.context._onNodeDestructionFinished(this, destructionComplete); + } finally { + this._destroying = false; + } } } diff --git a/test/test-context.js b/test/test-context.js index 7e6204b3c..a6be7223a 100644 --- a/test/test-context.js +++ b/test/test-context.js @@ -189,6 +189,241 @@ describe('context test suite', function () { } }); + it('defers context shutdown until active node teardowns finish', async function () { + const context = new rclnodejs.Context(); + await rclnodejs.init(context); + const first = rclnodejs.createNode('deferred_first', '', context); + const second = rclnodejs.createNode('deferred_second', '', context); + const other = rclnodejs.createNode('deferred_other', '', context); + const nodes = [first, second, other]; + const sandbox = sinon.createSandbox(); + const released = new Set(); + const shutdownReleases = []; + const snapshots = []; + let creationError; + let unexpectedNode; + try { + for (const node of nodes) { + const release = node.handle.release.bind(node.handle); + Object.defineProperty(node.handle, 'release', { + configurable: true, + value: () => { + release(); + released.add(node); + }, + }); + } + const shutdown = nativeLoader.shutdown; + sandbox.stub(nativeLoader, 'shutdown').callsFake((handle) => { + shutdownReleases.push(released.size); + return shutdown(handle); + }); + const publisher = other.createPublisher( + 'std_msgs/msg/String', + 'deferred_other_topic' + ); + const firstSubscription = first.createObservableSubscription( + 'std_msgs/msg/String', + 'deferred_first_topic' + ); + const secondSubscription = second.createObservableSubscription( + 'std_msgs/msg/String', + 'deferred_second_topic' + ); + const snapshot = () => ({ + shutdown: context.isShutdown(), + valid: context.isValid(), + nodes: context.nodes.length, + releases: released.size, + otherDestroyed: publisher.isDestroyed(), + }); + secondSubscription.observable.subscribe({ + complete: () => { + context.shutdown(); + snapshots.push(snapshot()); + }, + }); + firstSubscription.observable.subscribe({ + complete: () => { + second.destroy(); + snapshots.push(snapshot()); + try { + unexpectedNode = rclnodejs.createNode( + 'blocked_deferred_node', + '', + context + ); + } catch (error) { + creationError = error; + } + }, + }); + first.spin(-1); + first.destroy(); + + assert.deepStrictEqual(snapshots, [ + { + shutdown: false, + valid: true, + nodes: 2, + releases: 1, + otherDestroyed: true, + }, + { + shutdown: false, + valid: true, + nodes: 1, + releases: 2, + otherDestroyed: true, + }, + ]); + assert.ok(creationError); + assert.match(creationError.message, /Context that is shutting down/); + assert.deepStrictEqual(shutdownReleases, [nodes.length]); + assert.strictEqual(context.isShutdown(), true); + assert.strictEqual(context.isValid(), false); + assert.strictEqual(context.nodes.length, 0); + } finally { + sandbox.restore(); + for (const node of nodes) { + delete node.handle.release; + node.destroy(); + } + if (unexpectedNode) unexpectedNode.destroy(); + context.shutdown(); + } + }); + + it('keeps node completion notifications reentrant while deferring context shutdown', async function () { + const context = new rclnodejs.Context(); + await rclnodejs.init(context); + const node = rclnodejs.createNode('completion_notification', '', context); + const sandbox = sinon.createSandbox(); + const shutdownReleases = []; + let releases = 0; + let notifications = 0; + try { + const release = node.handle.release.bind(node.handle); + Object.defineProperty(node.handle, 'release', { + configurable: true, + value: () => { + release(); + releases++; + }, + }); + const shutdown = nativeLoader.shutdown; + sandbox.stub(nativeLoader, 'shutdown').callsFake((handle) => { + shutdownReleases.push(releases); + return shutdown(handle); + }); + const onNodeDestroyed = context.onNodeDestroyed.bind(context); + sandbox.stub(context, 'onNodeDestroyed').callsFake((target) => { + notifications++; + if (notifications === 1) { + target.destroy(); + context.shutdown(); + } + onNodeDestroyed(target); + }); + + node.destroy(); + + assert.strictEqual(notifications, 1); + assert.strictEqual(releases, 1); + assert.deepStrictEqual(shutdownReleases, [1]); + assert.strictEqual(context.isShutdown(), true); + assert.strictEqual(context.isValid(), false); + assert.strictEqual(context.nodes.length, 0); + } finally { + sandbox.restore(); + delete node.handle.release; + node.destroy(); + context.shutdown(); + } + }); + + for (const cleanup of ['entity', 'node']) { + it(`keeps deferred context shutdown retryable after ${cleanup} cleanup fails`, async function () { + const context = new rclnodejs.Context(); + await rclnodejs.init(context); + const node = rclnodejs.createNode('deferred_cleanup_retry', '', context); + const sandbox = sinon.createSandbox(); + let released = false; + let failed = false; + let client; + try { + client = node.createClient( + 'example_interfaces/srv/AddTwoInts', + 'deferred_retry_client' + ); + const service = node.createService( + 'example_interfaces/srv/AddTwoInts', + 'deferred_retry_service', + () => {} + ); + const subscription = node.createObservableSubscription( + 'std_msgs/msg/String', + 'deferred_retry_topic' + ); + const shutdown = sandbox.spy(nativeLoader, 'shutdown'); + const releaseNode = node.handle.release.bind(node.handle); + Object.defineProperty(node.handle, 'release', { + configurable: true, + value: () => { + if (cleanup === 'node' && !failed) { + failed = true; + throw new Error('Injected deferred cleanup failure'); + } + releaseNode(); + released = true; + }, + }); + if (cleanup === 'entity') { + const releaseClient = client.handle.release.bind(client.handle); + Object.defineProperty(client.handle, 'release', { + configurable: true, + value: () => { + if (!failed) { + failed = true; + throw new Error('Injected deferred cleanup failure'); + } + releaseClient(); + }, + }); + } + subscription.observable.subscribe({ + complete: () => context.shutdown(), + }); + node.spin(-1); + assert.throws( + () => node.destroy(), + /Injected deferred cleanup failure/ + ); + + assert.strictEqual(context.isShutdown(), false); + assert.strictEqual(context.isValid(), true); + assert.deepStrictEqual(context.nodes, [node]); + assert.strictEqual(shutdown.callCount, 0); + assert.strictEqual(released, false); + + context.shutdown(); + + assert.strictEqual(context.isShutdown(), true); + assert.strictEqual(context.isValid(), false); + assert.strictEqual(context.nodes.length, 0); + assert.strictEqual(shutdown.callCount, 1); + assert.strictEqual(released, true); + assert.strictEqual(service.isDestroyed(), true); + } finally { + sandbox.restore(); + delete node.handle.release; + if (client) delete client.handle.release; + node.destroy(); + context.shutdown(); + } + }); + } + it('context domain id', async function () { let context = new rclnodejs.Context(BigInt(123)); await rclnodejs.init(context); diff --git a/types/context.d.ts b/types/context.d.ts index bc5c0d861..513a78f13 100644 --- a/types/context.d.ts +++ b/types/context.d.ts @@ -77,6 +77,8 @@ declare module 'rclnodejs' { * Shutdown the context, includes destroying all nodes. * Reentrant shutdown is ignored, and node creation is rejected while * shutdown is in progress. + * If a node is already being destroyed, native shutdown is deferred until + * its teardown finishes. Cleanup failures leave the context open for retry. */ shutdown(): void; diff --git a/types/node.d.ts b/types/node.d.ts index 74cdb0923..f399dd032 100644 --- a/types/node.d.ts +++ b/types/node.d.ts @@ -532,6 +532,7 @@ declare module 'rclnodejs' { * and Timers. * Reentrant destruction is ignored. New entities and spinning are rejected * during and after node destruction, and while its context is shutting down. + * The node stays registered with its context until cleanup succeeds. */ destroy(): void; From 3641fd0dcecd83dd6876cc0f725a0530c22d5031 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Mon, 30 Nov 2026 14:12:14 +0800 Subject: [PATCH 5/8] Simplify flags --- lib/action/server_goal_handle.js | 1 - lib/context.js | 35 ++++++++++-------- lib/lifecycle_state.js | 7 ++++ lib/node.js | 55 ++++++++++++++-------------- test/test-context.js | 31 ++++++++++++++++ test/test-observable-subscription.js | 3 ++ 6 files changed, 88 insertions(+), 44 deletions(-) create mode 100644 lib/lifecycle_state.js diff --git a/lib/action/server_goal_handle.js b/lib/action/server_goal_handle.js index 8a3a9974b..ee18935f3 100644 --- a/lib/action/server_goal_handle.js +++ b/lib/action/server_goal_handle.js @@ -27,7 +27,6 @@ class ServerGoalHandle { this._actionServer = actionServer; this._goalInfo = goalInfo; this._goalRequest = goalRequest; - this._cancelRequested = false; this._deferred = new Deferred(); this._handle = rclnodejs.actionAcceptNewGoal( diff --git a/lib/context.js b/lib/context.js index d056c86d9..a91c50a25 100644 --- a/lib/context.js +++ b/lib/context.js @@ -14,6 +14,7 @@ import rclnodejs from './native_loader.js'; import { OperationError } from './errors.js'; +import { LifecycleState } from './lifecycle_state.js'; let defaultContext = null; @@ -66,9 +67,7 @@ class Context { */ constructor(domainId) { this._handle = rclnodejs.createContext(); - this._isShutdown = false; - this._isShuttingDown = false; - this._shutdownDeferred = false; + this._lifecycleState = LifecycleState.OPEN; this._nodes = []; this._domainId = domainId; Context._instances.push(this); @@ -112,7 +111,7 @@ class Context { * @returns {boolean} True if context has been shutdown; otherwise false */ isShutdown() { - return this._isShutdown; + return this._lifecycleState === LifecycleState.CLOSED; } /** @@ -152,9 +151,9 @@ class Context { * @throws {Error} If there is a problem shutting down the context. */ shutdown() { - if (this.isShutdown() || this._isShuttingDown) return; + if (!this._isOpen()) return; - this._isShuttingDown = true; + this._lifecycleState = LifecycleState.CLOSING; try { // shutdown and remove all nodes for (const node of this.nodes) { @@ -162,7 +161,7 @@ class Context { } if (this._nodes.length > 0) { - this._shutdownDeferred = true; + this._lifecycleState = LifecycleState.WAITING_FOR_NODE_TEARDOWN; return; } @@ -170,7 +169,7 @@ class Context { rclnodejs.shutdown(this.handle); } - this._isShutdown = true; + this._lifecycleState = LifecycleState.CLOSED; // remove context from _instances[] const index = Context._instances.indexOf(this); @@ -182,7 +181,9 @@ class Context { defaultContext = null; } } finally { - if (!this._shutdownDeferred) this._isShuttingDown = false; + if (this._lifecycleState === LifecycleState.CLOSING) { + this._lifecycleState = LifecycleState.OPEN; + } } } @@ -202,19 +203,23 @@ class Context { try { if (!completed) return; this.onNodeDestroyed(node); - resumeShutdown = this._shutdownDeferred; + resumeShutdown = + this._lifecycleState === LifecycleState.WAITING_FOR_NODE_TEARDOWN; } finally { - if (this._shutdownDeferred) { - this._shutdownDeferred = false; - this._isShuttingDown = false; + if (this._lifecycleState === LifecycleState.WAITING_FOR_NODE_TEARDOWN) { + this._lifecycleState = LifecycleState.OPEN; } } if (resumeShutdown) this.shutdown(); } + _isOpen() { + return this._lifecycleState === LifecycleState.OPEN; + } + _assertNodeCreationAllowed() { - if (this.isShutdown() || this._isShuttingDown) { - const state = this._isShuttingDown ? 'shutting down' : 'shutdown'; + if (!this._isOpen()) { + const state = this.isShutdown() ? 'shutdown' : 'shutting down'; throw new OperationError( `Can not add a Node to a Context that is ${state}`, { diff --git a/lib/lifecycle_state.js b/lib/lifecycle_state.js new file mode 100644 index 000000000..beca6d78d --- /dev/null +++ b/lib/lifecycle_state.js @@ -0,0 +1,7 @@ +export const LifecycleState = Object.freeze({ + OPEN: 'open', + CLOSING: 'closing', + FINALIZING: 'finalizing', + WAITING_FOR_NODE_TEARDOWN: 'waiting_for_node_teardown', + CLOSED: 'closed', +}); diff --git a/lib/node.js b/lib/node.js index de75ab0ab..4f4b80a8a 100644 --- a/lib/node.js +++ b/lib/node.js @@ -53,6 +53,7 @@ import Timer from './timer.js'; import TypeDescriptionService from './type_description_service.js'; import Entity from './entity.js'; import EntityRegistry from './entity_registry.js'; +import { LifecycleState } from './lifecycle_state.js'; import { SubscriptionEventCallbacks } from '../lib/event_handler.js'; import { PublisherEventCallbacks } from '../lib/event_handler.js'; import { validateFullTopicName } from './validator.js'; @@ -164,8 +165,7 @@ class Node extends rclnodejs.ShadowNode { this._postSetParametersCallbacks = []; this._logger = new Logging(rclnodejs.getNodeLoggerName(this.handle)); this._spinning = false; - this._destroying = false; - this._destroyed = false; + this._lifecycleState = LifecycleState.OPEN; // Detects stop/destroy during a ready batch, even if spinning restarts. this._dispatchGeneration = 0; this._enableRosout = options.enableRosout; @@ -554,19 +554,7 @@ class Node extends rclnodejs.ShadowNode { * @return {undefined} */ spin(timeout = 10) { - if (this._destroying || this._destroyed) { - throw new Error( - 'Cannot spin a node while it is being destroyed or has been destroyed.' - ); - } - if (this.context._isShuttingDown || this.context.isShutdown()) { - throw new Error( - 'Cannot spin a node while its context is shutting down or shut down.' - ); - } - if (this.spinning) { - throw new Error('The node is already spinning.'); - } + this._assertSpinAllowed(); this.start(this.context.handle, timeout); this._spinning = true; } @@ -621,12 +609,17 @@ class Node extends rclnodejs.ShadowNode { * @return {undefined} */ spinOnce(timeout = 10) { - if (this._destroying || this._destroyed) { + this._assertSpinAllowed(); + super.spinOnce(this.context.handle, timeout); + } + + _assertSpinAllowed() { + if (this._lifecycleState !== LifecycleState.OPEN) { throw new Error( 'Cannot spin a node while it is being destroyed or has been destroyed.' ); } - if (this.context._isShuttingDown || this.context.isShutdown()) { + if (!this.context._isOpen()) { throw new Error( 'Cannot spin a node while its context is shutting down or shut down.' ); @@ -634,15 +627,12 @@ class Node extends rclnodejs.ShadowNode { if (this.spinning) { throw new Error('The node is already spinning.'); } - super.spinOnce(this.context.handle, timeout); } _registerEntity(kind, entity) { if ( - this._destroying || - this._destroyed || - this.context._isShuttingDown || - this.context.isShutdown() + this._lifecycleState !== LifecycleState.OPEN || + !this.context._isOpen() ) { this._destroyEntity(kind, entity); } @@ -651,12 +641,12 @@ class Node extends rclnodejs.ShadowNode { } _assertEntityCreationAllowed() { - if (this._destroying || this._destroyed) { + if (this._lifecycleState !== LifecycleState.OPEN) { throw new Error( 'Cannot create entities while the node is being destroyed or has been destroyed.' ); } - if (this.context._isShuttingDown || this.context.isShutdown()) { + if (!this.context._isOpen()) { throw new Error( 'Cannot create entities while the context is shutting down or shut down.' ); @@ -1273,9 +1263,15 @@ class Node extends rclnodejs.ShadowNode { * @return {undefined} */ destroy() { - if (this._destroying) return; + if ( + this._lifecycleState === LifecycleState.CLOSING || + this._lifecycleState === LifecycleState.FINALIZING + ) { + return; + } - this._destroying = true; + const previousState = this._lifecycleState; + this._lifecycleState = LifecycleState.CLOSING; let destructionComplete = false; try { this._dispatchGeneration++; @@ -1285,7 +1281,7 @@ class Node extends rclnodejs.ShadowNode { this._entityRegistry.destroyAll(); - this._destroyed = true; + this._lifecycleState = LifecycleState.FINALIZING; if (this._enableRosout) { rclnodejs.finiRosoutPublisherForNode(this.handle); @@ -1304,7 +1300,10 @@ class Node extends rclnodejs.ShadowNode { try { this.context._onNodeDestructionFinished(this, destructionComplete); } finally { - this._destroying = false; + this._lifecycleState = + this._lifecycleState === LifecycleState.FINALIZING + ? LifecycleState.CLOSED + : previousState; } } } diff --git a/test/test-context.js b/test/test-context.js index a6be7223a..0dff85e76 100644 --- a/test/test-context.js +++ b/test/test-context.js @@ -406,6 +406,37 @@ describe('context test suite', function () { assert.strictEqual(shutdown.callCount, 0); assert.strictEqual(released, false); + if (cleanup === 'node') { + const assertUnusable = () => { + assert.throws( + () => node.createGuardCondition(() => {}), + /has been destroyed/ + ); + assert.throws(() => node.spin(-1), /has been destroyed/); + assert.throws(() => node.spinOnce(0), /has been destroyed/); + }; + assertUnusable(); + + const retryError = new Error('Injected cleanup retry failure'); + const destroyAll = sandbox + .stub(node._entityRegistry, 'destroyAll') + .throws(retryError); + try { + assert.throws( + () => context.shutdown(), + (error) => error === retryError + ); + assertUnusable(); + assert.strictEqual(context.isShutdown(), false); + assert.strictEqual(context.isValid(), true); + assert.deepStrictEqual(context.nodes, [node]); + assert.strictEqual(shutdown.callCount, 0); + assert.strictEqual(released, false); + } finally { + destroyAll.restore(); + } + } + context.shutdown(); assert.strictEqual(context.isShutdown(), true); diff --git a/test/test-observable-subscription.js b/test/test-observable-subscription.js index 96dca5aa8..72229dc72 100644 --- a/test/test-observable-subscription.js +++ b/test/test-observable-subscription.js @@ -279,7 +279,10 @@ describe('rclnodejs observable subscription test suite', function () { } node.spin(-1); node.destroy(); + assert.strictEqual(completions.length, observables.length); + assert.strictEqual(finalizations, observables.length); for (const obsSub of observables) { + assert.strictEqual(obsSub.isDestroyed, true); obsSub.destroy(); obsSub.complete(); } From 979b572041f684d04fa6af1fcefef5b22e744205 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Mon, 30 Nov 2026 14:35:05 +0800 Subject: [PATCH 6/8] Rename _assertEntityCreationAllowed() --- lib/action/client.js | 3 + lib/action/server.js | 3 + lib/entity_registry.js | 21 +++++- lib/lifecycle_state.js | 14 ++++ lib/node.js | 30 +++----- test/test-destruction.js | 100 +++++++++++++++++++++++++++ test/test-observable-subscription.js | 55 +++++++++++++++ 7 files changed, 205 insertions(+), 21 deletions(-) diff --git a/lib/action/client.js b/lib/action/client.js index ecb74fd24..58b2fc4c8 100644 --- a/lib/action/client.js +++ b/lib/action/client.js @@ -21,6 +21,7 @@ import DistroUtils from '../distro.js'; import Entity from '../entity.js'; import loader from '../interface_loader.js'; import QoS from '../qos.js'; +import { assertEntityCreationAllowed } from '../lifecycle_state.js'; import { TypeValidationError, ActionError, OperationError } from '../errors.js'; import { assertValidMessage } from '../message_validation.js'; @@ -55,6 +56,7 @@ class ActionClient extends Entity { constructor(node, typeClass, actionName, options) { super(null, null, options); + assertEntityCreationAllowed(node); this._node = node; this._typeClass = loader.loadInterface(typeClass); this._actionName = actionName; @@ -99,6 +101,7 @@ class ActionClient extends Entity { let type = this.typeClass.type(); + assertEntityCreationAllowed(node); this._handle = rclnodejs.actionCreateClient( node.handle, actionName, diff --git a/lib/action/server.js b/lib/action/server.js index 9c4d55cc9..1845bacdb 100644 --- a/lib/action/server.js +++ b/lib/action/server.js @@ -20,6 +20,7 @@ import Entity from '../entity.js'; import { CancelResponse, GoalEvent, GoalResponse } from './response.js'; import loader from '../interface_loader.js'; import QoS from '../qos.js'; +import { assertEntityCreationAllowed } from '../lifecycle_state.js'; import ServerGoalHandle from './server_goal_handle.js'; import { TypeValidationError } from '../errors.js'; @@ -87,6 +88,7 @@ class ActionServer extends Entity { ) { super(null, null, options); + assertEntityCreationAllowed(node); this._node = node; this._typeClass = loader.loadInterface(typeClass); this._actionName = actionName; @@ -117,6 +119,7 @@ class ActionServer extends Entity { let type = this.typeClass.type(); + assertEntityCreationAllowed(node); this._handle = rclnodejs.actionCreateServer( node.handle, node.getClock().handle, diff --git a/lib/entity_registry.js b/lib/entity_registry.js index bbab7c2b1..844141af6 100644 --- a/lib/entity_registry.js +++ b/lib/entity_registry.js @@ -74,13 +74,18 @@ class EntityRegistry { if (index > -1) { entities.splice(index, 1); } + return index; } destroy(kind, entity) { - this._remove(kind, entity); + const entityIndex = this._remove(kind, entity); if (entity.isDestroyed && entity.isDestroyed()) return; const events = [...(entity.events || [])]; + const eventPositions = events.map((event) => ({ + event, + index: this.collections.events.indexOf(event), + })); for (const event of events) { this._remove('events', event); } @@ -88,7 +93,19 @@ class EntityRegistry { !this._destroyingAll && (WAITABLE_COLLECTIONS.has(kind) || events.length > 0) ) { - this._node.syncHandles(); + try { + this._node.syncHandles(); + } catch (error) { + if (entityIndex > -1) { + this.collections[kind].splice(entityIndex, 0, entity); + } + for (const { event, index } of eventPositions.sort( + (first, second) => first.index - second.index + )) { + if (index > -1) this.collections.events.splice(index, 0, event); + } + throw error; + } } for (const event of events) { diff --git a/lib/lifecycle_state.js b/lib/lifecycle_state.js index beca6d78d..1d71cbc3b 100644 --- a/lib/lifecycle_state.js +++ b/lib/lifecycle_state.js @@ -5,3 +5,17 @@ export const LifecycleState = Object.freeze({ WAITING_FOR_NODE_TEARDOWN: 'waiting_for_node_teardown', CLOSED: 'closed', }); + +/** @ignore */ +export function assertEntityCreationAllowed(node) { + if (node._lifecycleState !== LifecycleState.OPEN) { + throw new Error( + 'Cannot create entities while the node is being destroyed or has been destroyed.' + ); + } + if (node.context._lifecycleState !== LifecycleState.OPEN) { + throw new Error( + 'Cannot create entities while the context is shutting down or shut down.' + ); + } +} diff --git a/lib/node.js b/lib/node.js index 4f4b80a8a..44f6523ef 100644 --- a/lib/node.js +++ b/lib/node.js @@ -53,7 +53,10 @@ import Timer from './timer.js'; import TypeDescriptionService from './type_description_service.js'; import Entity from './entity.js'; import EntityRegistry from './entity_registry.js'; -import { LifecycleState } from './lifecycle_state.js'; +import { + assertEntityCreationAllowed, + LifecycleState, +} from './lifecycle_state.js'; import { SubscriptionEventCallbacks } from '../lib/event_handler.js'; import { PublisherEventCallbacks } from '../lib/event_handler.js'; import { validateFullTopicName } from './validator.js'; @@ -636,29 +639,16 @@ class Node extends rclnodejs.ShadowNode { ) { this._destroyEntity(kind, entity); } - this._assertEntityCreationAllowed(); + assertEntityCreationAllowed(this); return this._entityRegistry.register(kind, entity); } - _assertEntityCreationAllowed() { - if (this._lifecycleState !== LifecycleState.OPEN) { - throw new Error( - 'Cannot create entities while the node is being destroyed or has been destroyed.' - ); - } - if (!this.context._isOpen()) { - throw new Error( - 'Cannot create entities while the context is shutting down or shut down.' - ); - } - } - _destroyEntity(kind, entity) { this._entityRegistry.destroy(kind, entity); } _validateOptions(options) { - this._assertEntityCreationAllowed(); + assertEntityCreationAllowed(this); if ( options !== undefined && (options === null || typeof options !== 'object') @@ -714,7 +704,7 @@ class Node extends rclnodejs.ShadowNode { * @return {Timer} - An instance of Timer. */ createTimer(period, callback, optionsOrClock = null, clock = null) { - this._assertEntityCreationAllowed(); + assertEntityCreationAllowed(this); let options = {}; if (optionsOrClock instanceof Clock.Clock) { @@ -789,7 +779,7 @@ class Node extends rclnodejs.ShadowNode { * @returns {Promise} - Promise resolving to new instance of Rate. */ async createRate(hz = 1) { - this._assertEntityCreationAllowed(); + assertEntityCreationAllowed(this); if (typeof hz !== 'number') { throw new TypeValidationError('hz', hz, 'number', { nodeName: this.name(), @@ -896,6 +886,7 @@ class Node extends rclnodejs.ShadowNode { ); } + assertEntityCreationAllowed(this); let publisher = publisherClass.createPublisher( this, typeClass, @@ -1029,6 +1020,7 @@ class Node extends rclnodejs.ShadowNode { ); } + assertEntityCreationAllowed(this); let subscription = SubscriptionClass.createSubscription( this, typeClass, @@ -1240,7 +1232,7 @@ class Node extends rclnodejs.ShadowNode { * @return {GuardCondition} - An instance of GuardCondition. */ createGuardCondition(callback) { - this._assertEntityCreationAllowed(); + assertEntityCreationAllowed(this); if (typeof callback !== 'function') { throw new TypeValidationError('callback', callback, 'function', { nodeName: this.name(), diff --git a/test/test-destruction.js b/test/test-destruction.js index b6b23f53f..3809395a2 100644 --- a/test/test-destruction.js +++ b/test/test-destruction.js @@ -112,6 +112,106 @@ describe('Node & Entity destroy testing', function () { } }); + for (const entity of ['publisher', 'subscription', 'observable']) { + for (const teardown of ['node', 'context']) { + it(`rejects ${entity} allocation after QoS callbacks destroy its ${teardown}`, async function () { + const context = new rclnodejs.Context(); + await rclnodejs.init(context); + const node = rclnodejs.createNode('qos_teardown_guard', '', context); + const sandbox = sinon.createSandbox(); + const allocation = sandbox + .stub( + nativeLoader, + entity === 'publisher' ? 'createPublisher' : 'createSubscription' + ) + .throws(new Error('Unexpected native allocation')); + let callbacks = 0; + try { + const options = { + qosOverridingOptions: + rclnodejs.QoSOverridingOptions.withDefaultPolicies({ + callback: () => { + callbacks++; + if (teardown === 'node') node.destroy(); + else context.shutdown(); + return { successful: true }; + }, + }), + }; + const create = () => { + if (entity === 'publisher') { + return node.createPublisher( + 'std_msgs/msg/String', + 'guarded', + options + ); + } + if (entity === 'subscription') { + return node.createSubscription( + 'std_msgs/msg/String', + 'guarded', + options, + () => {} + ); + } + return node.createObservableSubscription( + 'std_msgs/msg/String', + 'guarded', + options + ); + }; + assert.throws(create, /Cannot create entities/); + assert.strictEqual(callbacks, 1); + assert.strictEqual(allocation.callCount, 0); + } finally { + sandbox.restore(); + node.destroy(); + context.shutdown(); + } + }); + } + } + + for (const kind of ['client', 'server']) { + for (const teardown of ['node', 'context']) { + it(`rejects action ${kind} allocation after ${teardown} teardown`, async function () { + const context = new rclnodejs.Context(); + await rclnodejs.init(context); + const node = rclnodejs.createNode('action_teardown_guard', '', context); + if (teardown === 'node') node.destroy(); + else context.shutdown(); + const sandbox = sinon.createSandbox(); + const allocation = sandbox + .stub( + nativeLoader, + kind === 'client' ? 'actionCreateClient' : 'actionCreateServer' + ) + .throws(new Error('Unexpected native action allocation')); + try { + const create = () => + kind === 'client' + ? new rclnodejs.ActionClient( + node, + 'example_interfaces/action/Fibonacci', + 'guarded_action' + ) + : new rclnodejs.ActionServer( + node, + 'example_interfaces/action/Fibonacci', + 'guarded_action', + () => {} + ); + assert.throws(create, /Cannot create entities/); + assert.strictEqual(allocation.callCount, 0); + } finally { + sandbox.restore(); + node.destroy(); + context.shutdown(); + } + }); + } + } + it('rejects entity creation and spin restarts during and after node teardown', async function () { const node = rclnodejs.createNode('reentrant_teardown'); const sandbox = sinon.createSandbox(); diff --git a/test/test-observable-subscription.js b/test/test-observable-subscription.js index 72229dc72..52043266e 100644 --- a/test/test-observable-subscription.js +++ b/test/test-observable-subscription.js @@ -352,6 +352,61 @@ describe('rclnodejs observable subscription test suite', function () { } }); + for (const teardown of ['node', 'context']) { + it(`preserves failed observable cleanup for ${teardown} teardown`, function () { + const node = new rclnodejs.Node('failed_cleanup_owner'); + let callbacks; + if (DistroUtils.getDistroId() >= DistroUtils.getDistroId('jazzy')) { + callbacks = new SubscriptionEventCallbacks(); + callbacks.deadline = () => {}; + } + const observables = ['before', 'failed', 'after'].map((name) => + node.createObservableSubscription( + 'std_msgs/msg/String', + `failed_cleanup_${name}`, + undefined, + callbacks + ) + ); + const failed = observables[1]; + const subscriptions = [...node._subscriptions]; + const events = [...node._events]; + let completions = 0; + failed.observable.subscribe({ complete: () => completions++ }); + node.spin(-1); + Object.defineProperty(node, 'syncHandles', { + configurable: true, + value: () => { + throw new Error('Injected synchronization failure'); + }, + }); + try { + assert.throws( + () => failed.destroy(), + /Injected synchronization failure/ + ); + assert.deepStrictEqual(node._subscriptions, subscriptions); + assert.deepStrictEqual(node._events, events); + assert.strictEqual(failed.isDestroyed, false); + assert.strictEqual(completions, 0); + delete node.syncHandles; + + if (teardown === 'node') node.destroy(); + else node.context.shutdown(); + + assert.strictEqual(failed.isDestroyed, true); + assert.strictEqual(completions, 1); + assert.ok(observables.every((observable) => observable.isDestroyed)); + assert.ok(events.every((event) => event.isDestroyed())); + assert.strictEqual(node._subscriptions.length, 0); + assert.strictEqual(node._events.length, 0); + } finally { + delete node.syncHandles; + node.destroy(); + } + }); + } + // Regression test: destroy()/complete() used to only complete the RxJS // Subject, leaving the native ROS subscription alive. Plain RxJS // unsubscription (e.g. a `repeat()` resubscribing to the same wrapper's From 6585d87f828d7a2a5b0224d26d7c6d1c97aab714 Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Mon, 30 Nov 2026 16:07:14 +0800 Subject: [PATCH 7/8] Add comments --- lib/context.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/context.js b/lib/context.js index a91c50a25..5ec30388f 100644 --- a/lib/context.js +++ b/lib/context.js @@ -160,6 +160,9 @@ class Context { node.destroy(); } + // A completion callback can call shutdown() during node.destroy(). + // Reentrant destroy() returns early, leaving that node registered. + // Defer native shutdown until the outer teardown finishes. if (this._nodes.length > 0) { this._lifecycleState = LifecycleState.WAITING_FOR_NODE_TEARDOWN; return; From f94dd0f92cfa5d4ab676ffe3d8f3b750f93bf30c Mon Sep 17 00:00:00 2001 From: Minggang Wang Date: Mon, 30 Nov 2026 17:20:53 +0800 Subject: [PATCH 8/8] Add LICENSE --- lib/entity_registry.js | 21 +---------- lib/lifecycle_state.js | 14 +++++++ test/test-observable-subscription.js | 55 ---------------------------- 3 files changed, 16 insertions(+), 74 deletions(-) diff --git a/lib/entity_registry.js b/lib/entity_registry.js index 844141af6..bbab7c2b1 100644 --- a/lib/entity_registry.js +++ b/lib/entity_registry.js @@ -74,18 +74,13 @@ class EntityRegistry { if (index > -1) { entities.splice(index, 1); } - return index; } destroy(kind, entity) { - const entityIndex = this._remove(kind, entity); + this._remove(kind, entity); if (entity.isDestroyed && entity.isDestroyed()) return; const events = [...(entity.events || [])]; - const eventPositions = events.map((event) => ({ - event, - index: this.collections.events.indexOf(event), - })); for (const event of events) { this._remove('events', event); } @@ -93,19 +88,7 @@ class EntityRegistry { !this._destroyingAll && (WAITABLE_COLLECTIONS.has(kind) || events.length > 0) ) { - try { - this._node.syncHandles(); - } catch (error) { - if (entityIndex > -1) { - this.collections[kind].splice(entityIndex, 0, entity); - } - for (const { event, index } of eventPositions.sort( - (first, second) => first.index - second.index - )) { - if (index > -1) this.collections.events.splice(index, 0, event); - } - throw error; - } + this._node.syncHandles(); } for (const event of events) { diff --git a/lib/lifecycle_state.js b/lib/lifecycle_state.js index 1d71cbc3b..bffedb141 100644 --- a/lib/lifecycle_state.js +++ b/lib/lifecycle_state.js @@ -1,3 +1,17 @@ +// Copyright (c) 2026, The Robot Web Tools Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + export const LifecycleState = Object.freeze({ OPEN: 'open', CLOSING: 'closing', diff --git a/test/test-observable-subscription.js b/test/test-observable-subscription.js index 52043266e..72229dc72 100644 --- a/test/test-observable-subscription.js +++ b/test/test-observable-subscription.js @@ -352,61 +352,6 @@ describe('rclnodejs observable subscription test suite', function () { } }); - for (const teardown of ['node', 'context']) { - it(`preserves failed observable cleanup for ${teardown} teardown`, function () { - const node = new rclnodejs.Node('failed_cleanup_owner'); - let callbacks; - if (DistroUtils.getDistroId() >= DistroUtils.getDistroId('jazzy')) { - callbacks = new SubscriptionEventCallbacks(); - callbacks.deadline = () => {}; - } - const observables = ['before', 'failed', 'after'].map((name) => - node.createObservableSubscription( - 'std_msgs/msg/String', - `failed_cleanup_${name}`, - undefined, - callbacks - ) - ); - const failed = observables[1]; - const subscriptions = [...node._subscriptions]; - const events = [...node._events]; - let completions = 0; - failed.observable.subscribe({ complete: () => completions++ }); - node.spin(-1); - Object.defineProperty(node, 'syncHandles', { - configurable: true, - value: () => { - throw new Error('Injected synchronization failure'); - }, - }); - try { - assert.throws( - () => failed.destroy(), - /Injected synchronization failure/ - ); - assert.deepStrictEqual(node._subscriptions, subscriptions); - assert.deepStrictEqual(node._events, events); - assert.strictEqual(failed.isDestroyed, false); - assert.strictEqual(completions, 0); - delete node.syncHandles; - - if (teardown === 'node') node.destroy(); - else node.context.shutdown(); - - assert.strictEqual(failed.isDestroyed, true); - assert.strictEqual(completions, 1); - assert.ok(observables.every((observable) => observable.isDestroyed)); - assert.ok(events.every((event) => event.isDestroyed())); - assert.strictEqual(node._subscriptions.length, 0); - assert.strictEqual(node._events.length, 0); - } finally { - delete node.syncHandles; - node.destroy(); - } - }); - } - // Regression test: destroy()/complete() used to only complete the RxJS // Subject, leaving the native ROS subscription alive. Plain RxJS // unsubscription (e.g. a `repeat()` resubscribing to the same wrapper's