diff --git a/lib/action/client.js b/lib/action/client.js index ecb74fd2..58b2fc4c 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 9c4d55cc..1845bacd 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/action/server_goal_handle.js b/lib/action/server_goal_handle.js index 8a3a9974..ee18935f 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 a6a308b1..5ec30388 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,7 +67,7 @@ class Context { */ constructor(domainId) { this._handle = rclnodejs.createContext(); - this._isShutdown = false; + this._lifecycleState = LifecycleState.OPEN; this._nodes = []; this._domainId = domainId; Context._instances.push(this); @@ -110,7 +111,7 @@ class Context { * @returns {boolean} True if context has been shutdown; otherwise false */ isShutdown() { - return this._isShutdown; + return this._lifecycleState === LifecycleState.CLOSED; } /** @@ -142,31 +143,50 @@ 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. */ shutdown() { - if (this.isShutdown()) return; + if (!this._isOpen()) return; - // shutdown and remove all nodes - for (const node of this.nodes) { - node.destroy(); - } + this._lifecycleState = LifecycleState.CLOSING; + try { + // shutdown and remove all nodes + for (const node of this.nodes) { + node.destroy(); + } - if (this.isInitialized()) { - rclnodejs.shutdown(this.handle); - } + // 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; + } - this._isShutdown = true; + if (this.isInitialized()) { + rclnodejs.shutdown(this.handle); + } - // remove context from _instances[] - const index = Context._instances.indexOf(this); - if (index > -1) { - Context._instances.splice(index, 1); - } + this._lifecycleState = LifecycleState.CLOSED; - if (this.isDefaultContext()) { - defaultContext = null; + // remove context from _instances[] + const index = Context._instances.indexOf(this); + if (index > -1) { + Context._instances.splice(index, 1); + } + + if (this.isDefaultContext()) { + defaultContext = null; + } + } finally { + if (this._lifecycleState === LifecycleState.CLOSING) { + this._lifecycleState = LifecycleState.OPEN; + } } } @@ -181,23 +201,47 @@ class Context { } } - onNodeCreated(node) { - if (!node) { - throw new OperationError('Node must be defined to add to Context', { - code: 'NODE_UNDEFINED', - entityType: 'context', - }); + _onNodeDestructionFinished(node, completed) { + let resumeShutdown; + try { + if (!completed) return; + this.onNodeDestroyed(node); + resumeShutdown = + this._lifecycleState === LifecycleState.WAITING_FOR_NODE_TEARDOWN; + } finally { + if (this._lifecycleState === LifecycleState.WAITING_FOR_NODE_TEARDOWN) { + this._lifecycleState = LifecycleState.OPEN; + } } + if (resumeShutdown) this.shutdown(); + } - if (this.isShutdown()) { + _isOpen() { + return this._lifecycleState === LifecycleState.OPEN; + } + + _assertNodeCreationAllowed() { + if (!this._isOpen()) { + const state = this.isShutdown() ? 'shutdown' : 'shutting down'; throw new OperationError( - 'Can not add a Node to a Context that is shutdown', + `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', { + code: 'NODE_UNDEFINED', + entityType: 'context', + }); + } + + this._assertNodeCreationAllowed(); if (this._nodes.includes(node)) { // do nothing diff --git a/lib/lifecycle_state.js b/lib/lifecycle_state.js new file mode 100644 index 00000000..bffedb14 --- /dev/null +++ b/lib/lifecycle_state.js @@ -0,0 +1,35 @@ +// 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', + FINALIZING: 'finalizing', + 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 00115c0a..44f6523e 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'; @@ -51,6 +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 { + 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'; @@ -71,7 +77,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, @@ -123,6 +129,7 @@ class Node extends rclnodejs.ShadowNode { _init(name, namespace, options, context, args, useGlobalArguments) { options = Node._normalizeOptions(options); + context._assertNodeCreationAllowed(); this.handle = rclnodejs.createNode( name, @@ -161,6 +168,7 @@ class Node extends rclnodejs.ShadowNode { this._postSetParametersCallbacks = []; this._logger = new Logging(rclnodejs.getNodeLoggerName(this.handle)); this._spinning = false; + this._lifecycleState = LifecycleState.OPEN; // Detects stop/destroy during a ready batch, even if spinning restarts. this._dispatchGeneration = 0; this._enableRosout = options.enableRosout; @@ -545,13 +553,11 @@ 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.spinning) { - throw new Error('The node is already spinning.'); - } + this._assertSpinAllowed(); this.start(this.context.handle, timeout); this._spinning = true; } @@ -602,17 +608,38 @@ 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) { + 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._isOpen()) { + 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.'); } - super.spinOnce(this.context.handle, timeout); } _registerEntity(kind, entity) { + if ( + this._lifecycleState !== LifecycleState.OPEN || + !this.context._isOpen() + ) { + this._destroyEntity(kind, entity); + } + assertEntityCreationAllowed(this); return this._entityRegistry.register(kind, entity); } @@ -621,6 +648,7 @@ class Node extends rclnodejs.ShadowNode { } _validateOptions(options) { + assertEntityCreationAllowed(this); if ( options !== undefined && (options === null || typeof options !== 'object') @@ -676,6 +704,7 @@ class Node extends rclnodejs.ShadowNode { * @return {Timer} - An instance of Timer. */ createTimer(period, callback, optionsOrClock = null, clock = null) { + assertEntityCreationAllowed(this); let options = {}; if (optionsOrClock instanceof Clock.Clock) { @@ -750,6 +779,7 @@ class Node extends rclnodejs.ShadowNode { * @returns {Promise} - Promise resolving to new instance of Rate. */ async createRate(hz = 1) { + assertEntityCreationAllowed(this); if (typeof hz !== 'number') { throw new TypeValidationError('hz', hz, 'number', { nodeName: this.name(), @@ -856,6 +886,7 @@ class Node extends rclnodejs.ShadowNode { ); } + assertEntityCreationAllowed(this); let publisher = publisherClass.createPublisher( this, typeClass, @@ -910,6 +941,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 +1020,8 @@ class Node extends rclnodejs.ShadowNode { ); } - let subscription = Subscription.createSubscription( + assertEntityCreationAllowed(this); + let subscription = SubscriptionClass.createSubscription( this, typeClass, topic, @@ -979,12 +1030,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 +1055,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 +1069,7 @@ class Node extends rclnodejs.ShadowNode { ); observableSubscription = new ObservableSubscription(subscription, this); + this._registerEntity('subscriptions', subscription); return observableSubscription; } @@ -1177,6 +1232,7 @@ class Node extends rclnodejs.ShadowNode { * @return {GuardCondition} - An instance of GuardCondition. */ createGuardCondition(callback) { + assertEntityCreationAllowed(this); if (typeof callback !== 'function') { throw new TypeValidationError('callback', callback, 'function', { nodeName: this.name(), @@ -1193,29 +1249,54 @@ 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. + * The node stays registered with its context until cleanup succeeds. * @return {undefined} */ destroy() { - this._dispatchGeneration++; - if (this.spinning) { - this.stop(); + if ( + this._lifecycleState === LifecycleState.CLOSING || + this._lifecycleState === LifecycleState.FINALIZING + ) { + return; } - this._entityRegistry.destroyAll(); + const previousState = this._lifecycleState; + this._lifecycleState = LifecycleState.CLOSING; + let destructionComplete = false; + 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._lifecycleState = LifecycleState.FINALIZING; + + if (this._enableRosout) { + rclnodejs.finiRosoutPublisherForNode(this.handle); + this._enableRosout = false; + } - this.handle.release(); - this._clock = null; + this.handle.release(); + this._clock = null; - if (this._rateTimerServer) { - this._rateTimerServer.shutdown(); - this._rateTimerServer = null; + if (this._rateTimerServer) { + this._rateTimerServer.shutdown(); + this._rateTimerServer = null; + } + destructionComplete = true; + } finally { + try { + this.context._onNodeDestructionFinished(this, destructionComplete); + } finally { + this._lifecycleState = + this._lifecycleState === LifecycleState.FINALIZING + ? LifecycleState.CLOSED + : previousState; + } } } diff --git a/lib/observable_subscription.js b/lib/observable_subscription.js index 2dd4f1b8..b735e054 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 ac776960..324c2722 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-context.js b/test/test-context.js index 10e683af..0dff85e7 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,363 @@ 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('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); + + 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); + 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/test/test-destruction.js b/test/test-destruction.js index c1f4bd73..3809395a 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,239 @@ 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(); + 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/test/test-observable-subscription.js b/test/test-observable-subscription.js index ff38c36c..72229dc7 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,141 @@ 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(); + 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(); + } + + 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/test/test-spinning.js b/test/test-spinning.js index a69eabdf..3d206b7f 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 ); diff --git a/types/context.d.ts b/types/context.d.ts index 713720a2..513a78f1 100644 --- a/types/context.d.ts +++ b/types/context.d.ts @@ -75,6 +75,10 @@ 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 25b8f212..f399dd03 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; @@ -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. @@ -528,6 +530,9 @@ 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. + * The node stays registered with its context until cleanup succeeds. */ destroy(): void; diff --git a/types/observable_subscription.d.ts b/types/observable_subscription.d.ts index c0213865..31d20a65 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;