Service-level hooks¶
A node service can host graph nodes, custom gRPC services, or both. Shared
preparation and resource cleanup belong in a class extending NodeServiceBase,
registered with set_node_service_class() before run().
When you need it¶
Ask one question: does something have to happen once per container, before the first node is configured, and would repeating it in every node's on_configure() be wasteful or wrong?
| Situation | Where the work belongs |
|---|---|
| Open a device handle, connect to a broker, allocate buffers for this node | on_configure() of the node (per instance, released in on_cleanup()) |
| Download model files that every node in the container loads | Service hook |
| Fetch remote configuration or credentials shared by all nodes | Service hook |
| Pull a large dataset or warm a cache the nodes only read | Service hook |
| Release ROS nodes, watches or devices owned by the whole service | NodeServiceBase.on_shutdown() |
| Nothing shared, each node is self-contained | No hook. The default is a no-op and you register nothing. |
The hook is optional. A project that never calls set_node_service_class() behaves exactly as before: the SDK falls back to the no-op base class.
Preparing dependencies¶
Create one class that extends NodeServiceBase and override the class method:
from typing import Any, Mapping
from neuraverse_sdk.node_service_base import NodeServiceBase
class MyService(NodeServiceBase):
@classmethod
def on_prepare_node_dependencies(cls, configuration: Mapping[str, Any] | None = None) -> None:
...
| Behaviour | |
|---|---|
| Kind | A @classmethod. It runs before any node instance exists, so there is no self, no dataflow and no node configuration to read. |
configuration |
A plain dict of the values the caller sent with the request, or None. Decoded to Python str, float, bool, dict, list or None. Often empty; always handle a missing key. |
| Return value | Ignored. Returning normally means "prepared". |
| On exception | The SDK does not swallow it. The request fails with an error whose message starts with Failed to prepare node dependencies and contains your exception text. Raise to signal failure. |
| Default | Logs one line saying there is nothing to prepare and returns. |
| Logging | Use cls.LOG, a logger the base class provides. The node logging helpers (self.log_info() and friends) need an instance and are not available here. |
| Scope | Once per node service, not once per node class and not once per node instance. |
Keep the configuration parameter
Declare the hook with the optional configuration argument exactly as above. The SDK always passes one positional argument; an override without it fails with a TypeError the first time the platform calls it.
Register it¶
Registration happens in the startup script, next to the node classes and before run():
from neuraverse_sdk.node_manager_service import run, set_node_classes, set_node_service_class
set_node_classes([CloudUploadNode, ErrorHandlerNode])
set_node_service_class(CloudNodeService)
run()
set_node_service_class() takes the class itself, not an instance. Exactly one service class is held per container; calling the function twice keeps the last one. If you never call it, the SDK uses NodeServiceBase, whose hook does nothing. Where the startup script lives in a node project is described in Project layout and build.
Releasing resources when the service exits¶
Python calls on_shutdown() once on the registered service class after the
servers shut down and before the process exits. It runs on SIGTERM, Ctrl+C,
normal service completion, and startup failure.
Use a synchronous @classmethod. An ExitStack gives you one place to register
cleanup methods for shared devices and watches:
from contextlib import ExitStack
from neuraverse_sdk.node_service_base import NodeServiceBase
class ApplicationService(NodeServiceBase):
resources = ExitStack()
@classmethod
def on_shutdown(cls) -> None:
cls.resources.close()
Register each resource when you acquire it, for example
ApplicationService.resources.callback(device.close), then register
ApplicationService with set_node_service_class() before run().
The stack also handles partial startup and continues calling other cleanup
methods if one raises.
The hook runs on the main thread before the event loop joins its workers, so
it can stop a watch that would otherwise keep a worker alive. Use bounded waits
when closing or joining resources. Further SIGTERMs are ignored during cleanup.
If the hook raises, the SDK logs the failure and exits with status 1.
Node stop execution and cleanup RPCs do not call this service hook.
It works in custom-only, mixed and node-only hosts. A service without an
override gets a no-op. Put resource cleanup here: code after run(), destructors,
and exit-handler callbacks are bypassed by the SDK's forced process exit.
SIGKILL cannot invoke the hook.
When the platform calls preparation¶
The platform triggers the hook through the PrepareNodeDependencies request of your node service as a post-deployment step, after the container is up and before the first node is configured or initialized. The sequence inside your container is always the same:
- The request arrives with an optional key/value map.
- The SDK decodes the map into a plain dictionary.
- It calls
YourService.on_prepare_node_dependencies(configuration)once. - If the call returns, the caller receives
SUCCESSwith the messageNode dependencies prepared successfully. If it raises, the caller receives an error carrying your exception text.
Three consequences shape how you write the hook:
| Consequence | What to do |
|---|---|
| The SDK keeps no record that the hook ran. A repeated request runs it again. | Make it idempotent: skip a download whose file exists, reuse an open session, guard with a class attribute. |
The SDK does not block on_configure() until the hook has run. The ordering comes from the platform, not from a lock in your container. |
Have the nodes check for the prepared artefact in on_configure() and fail with a clear message if it is missing, instead of assuming it is there. |
| The request is a single blocking call and the caller may time it out. | Keep the hook bounded: no infinite retries, no waiting on user input. Fail fast and let the operator retry. |
Example: warming a cache for the cloud nodes¶
The cloud upload tutorial ships a small service class. It stores what it prepared on the class, because that is the only place a class method can put state that the nodes see later:
class CloudNodeService(NodeServiceBase):
"""Prepares what the cloud nodes need once, before any node instance exists."""
# Class-level cache: there is no instance when the hook runs.
warmed: dict[str, str] = {}
@classmethod
def on_prepare_node_dependencies(cls, configuration: Mapping[str, Any] | None = None) -> None:
cls.LOG.info("CloudNodeService: preparing dependencies for %s", cls.__name__)
endpoint = str((configuration or {}).get("endpoint", ""))
# A real service would download model files, fetch remote configuration
# or open a pooled HTTP session here. This tutorial only warms a cache.
cls.warmed["endpoint"] = endpoint
cls.warmed["prepared"] = "true"
# Raise on failure: the SDK maps the exception to an error response of
# the PrepareNodeDependencies RPC, so the caller sees the preparation failed.
cls.LOG.info("CloudNodeService: dependencies ready (endpoint=%r)", endpoint)
A real service would replace the two dictionary writes with the download or the remote fetch. The pattern to keep is the shape: read from configuration defensively, do the shared work, store the result on the class, and let any exception escape. The full project is in the Cloud upload tutorial.
Sharing the result with the nodes¶
Nodes never receive the service object; there is none. Two ways to hand the prepared result over work well:
| Approach | When to use it |
|---|---|
Class attribute on the service class (CloudNodeService.warmed["endpoint"]), read from the node's on_configure() |
Small in-memory results: parsed configuration, a loaded model object, an open client. Same process, no serialization. |
A well-known path on disk (/models/weights.bin), opened by each node in on_configure() |
Large files. Survives a node re-configure and is easy to inspect in the container. |
In both cases the node should treat a missing result as a configuration error and raise from on_configure() with a message that names the hook, so the log tells the operator what did not run.
Testing the hook¶
Because the hook is a class method with plain Python arguments, a unit test calls it directly. No FakeDataFlow, no node instance:
from examples.tutorials.cloud_node.service import CloudNodeService
def test_service_hook_is_a_classmethod_and_warms_the_cache() -> None:
CloudNodeService.warmed.clear()
CloudNodeService.on_prepare_node_dependencies({"endpoint": "https://example.test/upload"})
assert CloudNodeService.warmed["prepared"] == "true"
CloudNodeService.warmed.clear()
CloudNodeService.on_prepare_node_dependencies()
assert CloudNodeService.warmed["endpoint"] == ""
Test the two calls the platform can make: with a populated map and with no argument at all. Reset any class-level state between tests, since it outlives the test function. The general test setup for node projects is in Testing.
In the Mock Runner¶
The Mock Runner never sends PrepareNodeDependencies. The preparation hook does
not run there, and a node that depends on its result will fail in on_configure()
unless you give it a fallback. Two options:
- run the hook yourself in a unit test or a small script before starting the mock, so the well-known path or cache is populated,
- or give the node a development switch (a
toggleValuesuch asdry_runorsimulate) under which it does not need the prepared artefact.
The end-to-end behaviour, the request arriving after deployment and the error reaching the operator when the hook raises, needs a real engine.
The shutdown hook belongs to the SDK run() entry point. Stopping a graph in
the Mock Runner does not invoke it; test it by terminating a real NodeService
process.
Checklist¶
| Goal | What to do |
|---|---|
| Nothing shared between nodes | Do nothing. The default hook is a no-op. |
| Download or fetch once per container | Subclass NodeServiceBase, override on_prepare_node_dependencies(cls, configuration=None) as a @classmethod. |
| Make the platform call it | set_node_service_class(MyService) in the startup script before run(). |
| Report a failure | Raise. The request fails with your exception text; do not swallow the error and return. |
| Survive a repeated call | Make the hook idempotent and keep it bounded in time. |
| Hand results to the nodes | Class attribute or a well-known path; check for it in on_configure(). |
| Release shared resources at process shutdown | Override on_shutdown(cls) as a synchronous @classmethod; handle partial startup and bound cleanup waits. |
| Test it | Call the class method directly with a dict and with no argument. |