Tutorial 4: Cloud upload node¶
A node that talks to the network has to fail loudly, stay bounded and keep its credentials to itself. In this tutorial you build CloudUploadNode, which posts an incoming string to an HTTP endpoint with retries and raises NodeExecutionError on final failure so the graph's error trigger fires. You add a companion ErrorHandlerNode that reacts to that trigger, a masked read-only API key that never appears in logs or in the editor, a dry_run toggle that makes the node safe in the Mock Runner, and a NodeServiceBase hook that prepares shared resources once per service. All code lives in examples/tutorials/cloud_node/ and is run by the SDK's CI.
What you build¶
flowchart LR
S[Any node<br/>publishes String] -->|data_to_upload| C[CloudUploadNode]
C -->|upload_status| D[Downstream node]
C -->|start| D
C -.->|error| E[ErrorHandlerNode]
| Node | Inputs | Outputs | Configuration |
|---|---|---|---|
CloudUploadNode |
start, stop (triggers), data_to_upload (std_msgs/msg/String) |
start, error (triggers), upload_status (std_msgs/msg/String) |
endpoint text, api_key read-only text, dry_run toggle |
ErrorHandlerNode |
start, stop, error (triggers) |
start, error (triggers) |
none |
CloudNodeService |
not a node: a NodeServiceBase subclass registered next to the node classes |
Prerequisites: the environment from the Quickstart and the typed-configuration pattern from the device node tutorial. The trigger vocabulary (Start, Error, TriggerContext) is explained in Triggers.
1. The schema¶
The upload node declares one data input, one data output and the two trigger outputs a network node needs: start for the happy path and error for the failure path. Without an error output nothing downstream ever learns about a failed upload.
{
"id": "Examples",
"name": "CloudUploadNode",
"type": 1,
"description": "Posts an incoming string to an HTTP endpoint with bounded retries; fires error on final failure",
"tags": ["example", "tutorial", "cloud", "http"],
"inputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"stop": { "rosType": "Stop", "edgeType": 2 },
"data_to_upload": { "rosType": "std_msgs/msg/String", "edgeType": 1 }
},
"outputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"error": { "rosType": "Error", "edgeType": 2 },
"upload_status": { "rosType": "std_msgs/msg/String", "edgeType": 1 }
},
"executionContext": {
"type": "EXECUTION_TARGET_TYPE_GRPC",
"target": "",
"className": "CloudUploadNode"
},
"configuration": {
"endpoint": "https://example.invalid/upload",
"dry_run": "true"
}
}
Two details matter here:
- The
configurationblock seeds the staticconfigmap.dry_rundefaults to"true"so a node dropped from the palette never calls the network until someone switches the toggle off. - There is no
api_keyentry in the schema. Static configuration is plain text in a file you commit; the key comes from a deploy-time value instead (next section).
2. Typed configuration with a masked secret¶
on_get_configuration() describes the widgets the editor shows. Every entry is a NodeConfigEntry with a typed configValue; returning plain strings does not work.
def on_get_configuration(self) -> dict[str, NodeConfigEntry]:
# Every entry is typed: the UI renders stringValue as a text field and
# toggleValue as an on/off switch. The API key is readOnly and only a
# mask is ever sent to the UI, so the secret never leaves the node.
return {
"endpoint": NodeConfigEntry(
configValue=NodeConfigValue(stringValue=self.endpoint),
displayLabel="Endpoint",
description="HTTPS URL that receives the JSON payload",
required=True,
),
"api_key": NodeConfigEntry(
configValue=NodeConfigValue(stringValue=SECRET_MASK if self._api_key else ""),
displayLabel="API key",
description=f"Bearer token; set via configuration or the {API_KEY_ENV} variable",
readOnly=True,
),
"dry_run": NodeConfigEntry(
configValue=NodeConfigValue(toggleValue=ToggleValue(enabled=self.dry_run)),
displayLabel="Dry run",
description="Log the upload instead of calling the endpoint",
),
}
| Entry | Branch | Widget | Why |
|---|---|---|---|
endpoint |
stringValue |
text field, required=True |
The URL is ordinary configuration and may be edited in the editor. |
api_key |
stringValue, readOnly=True |
text field flagged read-only | The editor shows ******** (or nothing when no key is set). The real value is never sent to the UI. |
dry_run |
toggleValue |
on/off switch | Lets you exercise the node without a network. |
readOnly is metadata for the editor: the SDK passes it through unchanged and never reads it, so it does not protect anything by itself. The protection is in on_configure(), which ignores whatever the editor sends back for api_key:
self.endpoint = get_config_value("endpoint", config, dynamic_config) or ""
dry_run = get_config_value("dry_run", config, dynamic_config)
self.dry_run = True if dry_run is None else dry_run.strip().lower() == "true"
self._api_key = config.get("api_key") or os.environ.get(API_KEY_ENV, "")
get_config_value()prefers the typed UI value and falls back to the static string map. AtoggleValuecomes back as the string"true"or"false", which is why the toggle is compared to"true".- The API key is read from the static
configmap (a deploy-time override of the schema block) or from theCLOUD_API_KEYenvironment variable. The typed map is never consulted for it, so the mask that round-trips through the editor cannot overwrite the real key. - The configure log line prints
api_key=setorapi_key=missing, never the value. Apply the same rule to every log and every error message the node emits: the text of an exception raised fromon_executeis copied into theerrortrigger and travels to other nodes.
Secrets never leave the node
Do not return the secret from on_get_configuration(), do not put it in self.log_*() calls, and do not include it in the message of the exception you raise. The full source is committed; the value must come from the environment or from a configuration override applied at deploy time.
3. Execute: bounded work, then raise¶
on_execute reads the latched message, short-circuits in dry-run mode, and otherwise posts with retries. If the post still fails, it raises NodeExecutionError.
def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
try:
msg = self.get_data("data_to_upload")
if msg is None:
self.log_warning("No message on 'data_to_upload' yet, skipping this run")
return
if self.dry_run:
self.log_info(f"DRY_RUN: would POST {len(msg.data)} chars to {self.endpoint!r}")
self.publish("upload_status", String(data="DRY_RUN"))
return
try:
status_code = self._post_with_retry(msg.data)
except requests.RequestException as exc:
# Raising out of on_execute makes the SDK fire the "error" output
# trigger with the message below and put the node in ERROR state.
# Keep the secret out of the message: it travels to other nodes.
raise NodeExecutionError(
f"Upload to {self.endpoint!r} failed after 3 attempts: {exc}"
) from exc
self.publish("upload_status", String(data=f"OK:{status_code}"))
self.log_info(f"Uploaded {len(msg.data)} chars, HTTP {status_code}")
except NodeExecutionError:
raise
except Exception as exc:
raise NodeExecutionError(f"CloudUploadNode failed: {exc}") from exc
What the SDK does with an exception that escapes on_execute:
| Step | Detail |
|---|---|
| Error trigger | Every output whose type is Error fires, carrying a TriggerContext whose err_info holds the exception class (err_type) and its text (err_msg). If no Error output is declared, nothing fires. |
| State | The node moves to ERROR. Further Start triggers are refused until the next Configure, which returns it to CONFIGURED. |
| Start trigger | Not fired. Only a successful run fires the start output and returns the node to CONFIGURED. |
| Return to the engine | The SDK logs Execution error: ... and raises NodeExecutionError("Node Execution failed: <your message>"). |
So the rule is simple: raise to say "this run failed", return normally to say "this run is done". Publishing a FAILED string on a data port instead of raising would fire start downstream and leave the failure invisible to the graph. The outer try/except converts any unexpected exception into NodeExecutionError as well, so a bug in the node produces the same error path as a network failure.
The if msg is None branch is not an error: get_data() returns None until the first message arrives on the port, and a warning plus an early return is the right reaction to that.
4. Retries that stay bounded¶
on_execute runs on the node's own single-worker executor. The next Start trigger for this node waits in the executor queue until the current run returns, so a retry loop directly controls how long the node is unavailable. The tutorial uses tenacity, which the SDK already depends on, and caps the worst case at three attempts:
@retry(
stop=stop_after_attempt(3),
wait=wait_fixed(1),
retry=retry_if_exception_type(requests.RequestException),
reraise=True,
)
def _post_with_retry(self, payload: str) -> int:
# Worst case per on_execute: 3 attempts x 5 s timeout + 2 x 1 s wait.
# Keep this bounded: the next Start trigger waits until on_execute returns.
response = requests.post(
self.endpoint,
json={"payload": payload},
headers={"Authorization": f"Bearer {self._api_key}"},
timeout=REQUEST_TIMEOUT_S,
)
response.raise_for_status()
return response.status_code
| Setting | Value | Effect |
|---|---|---|
timeout=REQUEST_TIMEOUT_S |
5 s | No request can hang longer than this; requests raises a Timeout, which is a RequestException. |
stop_after_attempt(3) |
3 | Worst case per run: 3 x 5 s plus 2 x 1 s of waiting, 17 s. |
retry_if_exception_type(requests.RequestException) |
Retries connection errors, timeouts and raise_for_status() failures; anything else propagates immediately. |
|
reraise=True |
After the last attempt the original RequestException is raised, so on_execute can wrap it in NodeExecutionError with a message of its own. |
Do not reach for asyncio here. The SDK calls on_execute as a plain synchronous method on its executor thread; a blocking HTTP call with a timeout is the correct shape. If a single upload legitimately takes longer than a Start-to-Start interval, shorten the work per run rather than spawning threads that outlive the run.
5. The error handler node¶
An Error input trigger routes to on_execute, exactly like Start. The difference is the trigger_context argument: it arrives with err_info set, so is_triggered_by_error() returns True.
def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
# Start and Error both land here. Only the Error path carries err_info.
if trigger_context is not None and trigger_context.is_triggered_by_error():
err_info = trigger_context.err_info
self.log_error(
f"Upstream node {trigger_context.source_node!r} failed: "
f"{err_info.err_type}: {err_info.err_msg} "
f"(transaction {err_info.transaction_id})"
)
self.errors_seen.append(err_info.err_msg)
return
source = trigger_context.source_node if trigger_context else "unknown"
self.log_info(f"ErrorHandlerNode started normally by {source!r}; nothing to handle")
The schema declares the extra input next to start and stop:
{
"id": "Examples",
"name": "ErrorHandlerNode",
"type": 1,
"description": "Logs the source and details of an upstream error trigger",
"tags": ["example", "tutorial", "error-handling"],
"inputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"stop": { "rosType": "Stop", "edgeType": 2 },
"error": { "rosType": "Error", "edgeType": 2 }
},
"outputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"error": { "rosType": "Error", "edgeType": 2 }
},
"executionContext": {
"type": "EXECUTION_TARGET_TYPE_GRPC",
"target": "",
"className": "ErrorHandlerNode"
},
"configuration": {}
}
In the editor, connect CloudUploadNode.error to ErrorHandlerNode.error. When an upload fails after three attempts the handler logs a line such as Upstream node 'CloudUploadNode' failed: <class '...NodeExecutionError'>: Upload to 'https://...' failed after 3 attempts: ....
TriggerContext field |
What the handler gets |
|---|---|
source_node |
The class name of the node that raised. |
err_info.err_type |
The exception class of the escaped exception, as a string. |
err_info.err_msg |
The exception text. This is why the upload node keeps the API key out of it. |
err_info.transaction_id |
A UUID generated when the error was recorded, useful to correlate log lines across nodes. |
Always guard the context: a plain Start leaves err_info at None, and trigger_context itself is None when the node is executed from the Mock Runner. The handler returns without publishing anything; in a real graph you would send a notification, write to a log sink or publish a status string on a data port of your own.
6. Prepare dependencies once per service¶
Some work belongs to the node service as a whole, not to a node instance: downloading a model, fetching remote configuration, opening a pooled session. Subclass NodeServiceBase and override on_prepare_node_dependencies(). It is a class method because it runs before any node object exists.
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)
Register the class in the startup script, 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()
| Behaviour | Detail |
|---|---|
| When | Once per service, as a post-deployment step, before any node is configured. Not per node, not per execute. |
| Argument | configuration is a plain mapping decoded from the request; it may be None. Accept the optional parameter even if you do not use it. |
| Default | A no-op. A service without dependencies needs no subclass and no set_node_service_class() call. |
| Failure | Raise. The exception is returned to the caller as a failed preparation instead of a SUCCESS result. |
| Logging | Use cls.LOG, the logger the base class provides; there is no self.log_info() yet. |
The tutorial only warms a class-level dictionary so that the test can assert the hook ran. Keep state you prepare here at class level, or in files, because the node instances created later are separate objects.
7. Run it in the Mock Runner¶
Start the Mock Runner as in the Quickstart, copy the folder examples/tutorials/cloud_node/ into the src/ directory of your node project and click Reload Code. The backend imports every module it finds under src/ except test_*.py, so both nodes appear in the palette; service.py is imported too but defines no node and its hook never runs here.
- Drag CloudUploadNode onto the canvas, click Init. The card shows the three widgets; Dry run is on and API key is empty.
- Click Configure. The log shows
endpoint='' dry_run=True api_key=missing: the Mock Runner does not deliver the staticconfigurationblock, so the endpoint from the schema is absent unless you type it into the form. - Open Inputs, type a payload next to
data_to_upload, click Override, then Execute. Outputs showsDRY_RUNonupload_statusand the log says how many characters would have been posted. - Switch Dry run off, type any unreachable URL into Endpoint, Configure, Execute. After three attempts the run fails, the log shows
Execution error: Upload to ... failed after 3 attempts, and the card is inERROR. Click Configure to recover, then Execute again.
What the Mock Runner cannot show you here, and where to test it instead:
| Behaviour | In the Mock Runner | Test with |
|---|---|---|
The error trigger reaching ErrorHandlerNode |
Nothing fires; the trigger adapter is a dummy and trigger_context is always None. |
The unit test in test_cloud_node.py, or a run on an engine. |
| The read-only API key | The widget is a plain text field. Whatever you type is ignored, because on_configure reads only config and the environment. |
Set CLOUD_API_KEY in the container environment for a real upload. |
CloudNodeService.on_prepare_node_dependencies() |
Never runs; the module is imported, but the Mock Runner registers no service class and never calls the hook. | The unit test, or a deployment on an engine. |
8. What the tests check¶
examples/tutorials/cloud_node/test_cloud_node.py runs without ROS 2 and without a network. It installs the shared stubs, drives the nodes through a FakeDataFlow, replaces requests.post with a fake and sets the tenacity wait to zero so the three-attempt path stays fast. The tests pin every promise this page makes:
- dry run publishes
DRY_RUNand never callsrequests.post; - a successful post publishes
OK:<status>and sendsAuthorization: Bearer <key>with a 5 s timeout; - a connection error or an HTTP 503 is retried three times and ends in
NodeExecutionErrorwhose text does not contain the key, and no log line contains it either; on_get_configuration()returns typed entries,api_keyisreadOnlyand shows the mask;- a static
api_keywins over the environment variable; ErrorHandlerNoderecords the error from an error-carryingTriggerContextand ignores a plain Start;CloudNodeService.on_prepare_node_dependencies()runs as a class method and fills the cache.
Run them from the SDK repository root:
PYTHONPATH="$(pwd):$(pwd)/src" poetry run pytest examples/tutorials/cloud_node -q -p no:cacheprovider
How the stubs and the fake dataflow work is described in Testing.
Full source of CloudUploadNode
class CloudUploadNode(NodeBase):
"""Posts ``data_to_upload`` to ``endpoint``; publishes the outcome on ``upload_status``."""
def __init__(self) -> None:
super().__init__()
# Plain defaults only; real setup happens in on_configure().
self.endpoint: str = ""
self.dry_run: bool = True
self._api_key: str = ""
def on_get_configuration(self) -> dict[str, NodeConfigEntry]:
# Every entry is typed: the UI renders stringValue as a text field and
# toggleValue as an on/off switch. The API key is readOnly and only a
# mask is ever sent to the UI, so the secret never leaves the node.
return {
"endpoint": NodeConfigEntry(
configValue=NodeConfigValue(stringValue=self.endpoint),
displayLabel="Endpoint",
description="HTTPS URL that receives the JSON payload",
required=True,
),
"api_key": NodeConfigEntry(
configValue=NodeConfigValue(stringValue=SECRET_MASK if self._api_key else ""),
displayLabel="API key",
description=f"Bearer token; set via configuration or the {API_KEY_ENV} variable",
readOnly=True,
),
"dry_run": NodeConfigEntry(
configValue=NodeConfigValue(toggleValue=ToggleValue(enabled=self.dry_run)),
displayLabel="Dry run",
description="Log the upload instead of calling the endpoint",
),
}
def on_configure(
self,
config: ScalarMap[str, str],
dynamic_config: Optional[MessageMap[str, NodeConfigEntry]] = None,
) -> None:
# get_config_value() prefers the typed UI value and falls back to the
# static string map, so both sources work with one call per key.
self.endpoint = get_config_value("endpoint", config, dynamic_config) or ""
dry_run = get_config_value("dry_run", config, dynamic_config)
self.dry_run = True if dry_run is None else dry_run.strip().lower() == "true"
# The secret comes from the static configuration or the environment only.
# The UI value is a mask (see on_get_configuration), so it is never read back.
self._api_key = config.get("api_key") or os.environ.get(API_KEY_ENV, "")
# Log whether the key is present, never the key itself.
self.log_info(
f"CloudUploadNode configured: endpoint={self.endpoint!r} dry_run={self.dry_run} "
f"api_key={'set' if self._api_key else 'missing'}"
)
def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
try:
msg = self.get_data("data_to_upload")
if msg is None:
self.log_warning("No message on 'data_to_upload' yet, skipping this run")
return
if self.dry_run:
self.log_info(f"DRY_RUN: would POST {len(msg.data)} chars to {self.endpoint!r}")
self.publish("upload_status", String(data="DRY_RUN"))
return
try:
status_code = self._post_with_retry(msg.data)
except requests.RequestException as exc:
# Raising out of on_execute makes the SDK fire the "error" output
# trigger with the message below and put the node in ERROR state.
# Keep the secret out of the message: it travels to other nodes.
raise NodeExecutionError(
f"Upload to {self.endpoint!r} failed after 3 attempts: {exc}"
) from exc
self.publish("upload_status", String(data=f"OK:{status_code}"))
self.log_info(f"Uploaded {len(msg.data)} chars, HTTP {status_code}")
except NodeExecutionError:
raise
except Exception as exc:
raise NodeExecutionError(f"CloudUploadNode failed: {exc}") from exc
@retry(
stop=stop_after_attempt(3),
wait=wait_fixed(1),
retry=retry_if_exception_type(requests.RequestException),
reraise=True,
)
def _post_with_retry(self, payload: str) -> int:
# Worst case per on_execute: 3 attempts x 5 s timeout + 2 x 1 s wait.
# Keep this bounded: the next Start trigger waits until on_execute returns.
response = requests.post(
self.endpoint,
json={"payload": payload},
headers={"Authorization": f"Bearer {self._api_key}"},
timeout=REQUEST_TIMEOUT_S,
)
response.raise_for_status()
return response.status_code
def on_stop(self, trigger_context: Optional[TriggerContext] = None) -> None:
self.log_info("CloudUploadNode stopped")
Where to next¶
- Triggers for custom trigger ports and the full
TriggerContextcontract. - Configuration for sliders, dropdowns and re-configure semantics.
- Health reporting to report a failing endpoint as an unhealthy node between runs.
- Lifecycle and states for the
ERRORstate, teardown order and threads.