Skip to content

Latest commit

 

History

History
774 lines (622 loc) · 35.2 KB

message-parser-guide.md

File metadata and controls

774 lines (622 loc) · 35.2 KB

Writing a MessageParser Plugin

Tracks the v5 plugin ABI (PJ_ABI_VERSION == 5). The parser write-host supports per-record writes and an optional Arrow stream batch path for parser-shaped formats that naturally decode batches. SchemaHandler-based parsers additionally expose pj.parser_functional.v2 and pj.parser_route_claims.v1; no C++ result object crosses the plugin boundary. For ABI evolution rules, error semantics, and noexcept discipline see ARCHITECTURE.md.

Vocabulary used throughout this guide:

  • PJ::Status — alias for PJ::Expected<void>. Return PJ::okStatus() / PJ::unexpected("reason").
  • PJ::Span<const uint8_t> — non-owning view over the payload bytes.
  • PJ::Timestamp — int64_t nanoseconds since the Unix epoch. The host provides one; the parser may override it from the payload (see "Embedded timestamp extraction").

When MessageParser is the Wrong Choice

If your input is a complete file/container or source-owned stream (Parquet file, MCAP bag, database export), prefer a DataSource that calls writeHost().appendArrowStream(...). Use a MessageParser when the host has selected a topic/encoding and supplies payloads to decode. If one parse() call naturally yields a batch, the parser write host can accept it through writeHost().appendArrowStream(...).

A MessageParser is the right choice when:

  • Each message is independently decodable (JSON line, single Protobuf message, ROS message, Influx line).
  • You produce up to a few dozen named numeric fields per call.
  • Or, one payload for a selected encoding naturally expands to a batch for the parser's bound topic.
  • The encoding may be paired with multiple transports (a Protobuf parser used by both an MQTT and a ZMQ source).

What is a MessageParser?

A MessageParser plugin is a shared library (.so / .dylib / .dll) that decodes raw byte payloads — JSON, Protobuf, ROS messages, Influx line protocol, etc. — into named numeric fields that PlotJuggler can plot. Plugins link against the plotjuggler_sdk::plugin_sdk authoring target (no Qt or host internals) and communicate through a stable C ABI.

MessageParsers are typically used via delegated ingest: a DataSource plugin acquires raw data from files or network streams and pushes raw payloads through the host, which routes them to the appropriate parser based on encoding name.

Quick Start

  1. Subclass PJ::MessageParserPluginBase.
  2. For new parsers, register SchemaHandler entries for functional scalar and/or builtin-object output. For a legacy push-only parser, override parse() instead. Optionally override bindSchema() (call the base implementation first), saveConfig(), and loadConfig().
  3. Export with PJ_MESSAGE_PARSER_PLUGIN(YourClass, R"({"id":"...","name":"...","version":"...","encoding":["..."]})")
  4. Build as a shared library linking plotjuggler_sdk::plugin_sdk

For a namespaced class in a static build, provide the getter-symbol token separately: PJ_MESSAGE_PARSER_PLUGIN_NAMED(my::Parser, MyParser, kManifest). Dynamic builds may use either form.

A complete example lives at pj_plugins/examples/mock_json_parser.cpp.

parse() supports scalar push ingestion. It alone does not advertise functional parsing. Rebuilt legacy parsers stay on the host's compatibility path until they register a SchemaHandler. Capabilities reflect registration; there is no manual flag to maintain.

Plugin Contract

Follow these rules. Some are enforced by manifest validation or SDK trampolines; others prevent runtime parse failures.

MUST

  • Return PJ::okStatus() / PJ::unexpected("reason") from parse() and other fallible methods.
  • Honour the encoding(s) declared in the manifest's "encoding" array — the host routes binding requests by encoding name.
  • Leave the parser in a consistent state after a failed parse() so the next parse() call still works (do not corrupt cached field handles or schemas).
  • Keep parse() topic-agnostic — the write host is already topic-scoped at bind time. writeHost().ensureField("x") becomes <topic>/x in the datastore automatically.

MUST NOT

  • Throw exceptions across parse()/bindSchema()/bind(registry)/ loadConfig()/saveConfig(). The SDK trampolines catch as a fallback, but the host loses the chance to report a useful reason.
  • Call any host method outside the host's callback thread.
  • Cache the write host view across instances or threads — it is bound to one parser instance for one topic.
  • Assume bindSchema() is called for every encoding. JSON / text parsers may never receive it. Only require schema for encodings that need it (Protobuf, ROS, IDL).

Step by Step

For a new parser, use the SchemaHandler example. The legacy push example below decodes one numeric text payload; it does not implement JSON parsing. Use existing utilities for shared parsing and timestamp operations.

1. Declare your class

#include <pj_plugins/sdk/message_parser_plugin_base.hpp>
#include <pj_base/number_parse.hpp>

class MyNumberParser : public PJ::MessageParserPluginBase {
 public:
  PJ::Status parse(PJ::Timestamp timestamp_ns,
                    PJ::Span<const uint8_t> payload) override;
};

2. Implement parse()

When parse() is called, the SDK default bind() has already resolved the parser write service from the host's service registry. Use writeHost() (protected) to write decoded fields. Return okStatus() on success, or unexpected("reason") on failure.

PJ::Status MyNumberParser::parse(PJ::Timestamp timestamp_ns,
                                PJ::Span<const uint8_t> payload) {
  if (!writeHostBound()) {
    return PJ::unexpected("write host not bound");
  }

  const std::string_view text(
      reinterpret_cast<const char*>(payload.data()), payload.size());
  const auto value = PJ::parseNumber<double>(text);
  if (!value) {
    return PJ::unexpected("invalid numeric payload");
  }
  const PJ::sdk::NamedFieldValue fields[] = {{.name = "value", .value = *value}};
  return writeHost().appendRecord(
      timestamp_ns, PJ::Span<const PJ::sdk::NamedFieldValue>(fields, 1));
}

The write host is topic-scoped — the host binds it to a specific topic before calling parse(). Fields written via writeHost().appendRecord() are automatically namespaced under that topic. The parser does not need to know or manage topic names.

3. Export the plugin

At file scope, after the class definition. The second argument is a JSON manifest string literal (see Manifest Schema below):

PJ_MESSAGE_PARSER_PLUGIN(MyNumberParser,
    R"({"id":"number-parser","name":"Number Parser","version":"1.0.0","encoding":["text-number"]})")

This generates the extern "C" entry point that the host resolves via dlsym. The manifest is embedded as a compile-time constant in the vtable, so the host can read it without creating an instance.

4. Build

add_library(my_parser_plugin SHARED my_parser.cpp)
target_link_libraries(my_parser_plugin PRIVATE plotjuggler_sdk::plugin_sdk)

Headless parsers need no other dependencies. The same installed umbrella target includes the SDK for parser configuration dialogs. pj_base and pj_dialog_sdk are in-tree implementation targets, not the downstream authoring interface.

Lifecycle

The host drives the parser through these phases:

create() -> bind(registry) -> [bind_schema()] -> parse()* -> destroy()
  1. create — the host calls create() to allocate a new parser instance.
  2. bind — the host provides a service registry. The SDK default bind resolves mandatory "pj.parser_write.v1" plus optional "pj.parser_object_write.v1" and "pj.parser_runtime.v1" services. Must complete before parse(); either optional service may be absent.
  3. bind_schema (optional) — for parsers that need schema (Protobuf, ROS, IDL), the host provides the schema bytes and type name. Parsers that don't need schema (JSON, Influx) can ignore this call.
  4. parse — called once per message. The parser decodes the payload and writes fields via writeHost().
  5. destroy — the host destroys the instance.

Write Host API

Access via writeHost() (protected). The write host is topic-scoped — every field and record you write is automatically placed under the parser's assigned topic.

Method Purpose
ensureField(name, type) Optional: pre-register a field. Enables appendBoundRecord. Returns a FieldHandle.
appendRecord(timestamp, fields) Write a row of named field values. Auto-creates new fields.
appendBoundRecord(timestamp, fields) Write using pre-resolved field handles (faster).
appendArrowStream(stream, ts_col) Optional batch path. Hand an ArrowArrayStream* to the host for the parser's bound topic. Success transfers ownership to the host; failure leaves ownership with the plugin.
setFieldMetadata(field, json) Optional (SDK 1.2.0): attach a metadata document to a field of the bound topic; its description shows as a tooltip. See Field descriptions.

Most parsers should use appendRecord() or appendBoundRecord(); one parse() call normally decodes one logical message. Use appendArrowStream() when one payload naturally contains many rows for the bound topic. Batch encodings can then stay in the parser family without per-row loops.

Recoverable Runtime Diagnostics

Use parserRuntimeHost() for recoverable conditions in the current message or equivalent problems across messages. This optional view is always safe to call. Reporting is a no-op if an older or minimal host lacks "pj.parser_runtime.v1". Use parserRuntimeHostBound() when sink presence affects plugin behavior.

parserRuntimeHost().reportDiagnostic(
    PJ::sdk::ParserDiagnosticLevel::Warning,
    "integer_overflow",
    "Some integer values exceeded the target field width",
    overflow_count);

The arguments have distinct contracts:

  • stable_code is a plugin-defined, machine-stable deduplication key such as integer_overflow. Never put a localized sentence, field value, counter, or other value-filled prose in this key. Put human-readable detail in message.
  • occurrences is the number of equivalent events represented by this call; it defaults to one. Prefer one report with an accumulated count when the parser already has that count.
  • Info, Warning, and Error describe severity. An Error diagnostic still does not fail parse() by itself.

reportDiagnostic() is thread-safe and noexcept, may be called from the parse callback thread, and must return without blocking that thread. The host queues and aggregates reports by (parser manifest ID, bound schema/type, level, stable_code), retaining representative message text; bounded queues, rate limiting, UI delivery, and final summaries are host policy.

Diagnostics do not replace parse errors. If the current message cannot be parsed, return PJ::unexpected("reason") through the existing Status path. Use runtime diagnostics for recoverable optional-field errors, partial schema mismatches, overflow affecting only some values, and similar conditions where the parse can still succeed.

classifySchema() is a pure, side-effect-free query. It must never report a runtime diagnostic; wait until a parse callback has observed the condition.

Named vs bound writes

For simple parsers, use appendRecord() with NamedFieldValue — fields are auto-created on first non-null value, and names are resolved on each call:

const PJ::sdk::NamedFieldValue fields[] = {
    {.name = "temperature", .value = 23.5},
    {.name = "humidity", .value = 61.0}};
writeHost().appendRecord(timestamp_ns, PJ::Span(fields));

For high-throughput parsers, pre-register fields with ensureField() and use appendBoundRecord() with BoundFieldValue — field handles are resolved once:

// During bind_schema or first parse:
auto temp_field = writeHost().ensureField("temperature",
                                          PJ::PrimitiveType::kFloat64);
auto hum_field = writeHost().ensureField("humidity",
                                          PJ::PrimitiveType::kFloat64);

// During each parse:
const PJ::sdk::BoundFieldValue fields[] = {
    {.field = *temp_field, .value = 23.5},
    {.field = *hum_field, .value = 61.0}};
writeHost().appendBoundRecord(timestamp_ns, PJ::Span(fields));

For payloads that decode directly into an Arrow stream, prefer the RAII overload so ownership is handled correctly:

PJ::sdk::ArrowStreamHolder stream(build_payload_stream(payload));
auto status = writeHost().appendArrowStream(std::move(stream), "timestamp");
if (!status) {
  return status;
}

Field descriptions

A parser can explain what a field means. setFieldMetadata() (SDK 1.2.0) attaches a metadata document to a field of the bound topic: a flat JSON object of string values. Two keys are canonical: description, which the host shows as a tooltip on the field's row in the dataset list, and unit. Set it once per load, after ensureField(), not on every parse:

#include <pj_base/sdk/metadata_document.hpp>

auto temp_field = writeHost().ensureField("temperature", PJ::PrimitiveType::kFloat64);
if (temp_field) {
  // Optional: an older host returns an error, which the parser can ignore.
  (void)writeHost().setFieldMetadata(
      *temp_field, PJ::sdk::MetadataDocumentBuilder().description("Air temperature").unit("degC").build());
}
  • A reload starts without any document, and the parser sets them again as it meets the fields. A reload that fails keeps the previous ones.
  • Each call replaces the whole document, so send every key each time. An empty string or an object with no key clears it.
  • The host keeps keys it does not know.
  • Text is UTF-8: convert text read in another encoding (a Latin-1 °C in a DBC file) first, or the host rejects the whole document.
  • The host rejects a value that is not a string and a document above its size bound (PlotJuggler accepts 4 KiB). Keep a description to a sentence or two: it is shown as a tooltip.
  • Only fields of the bound topic: a handle of another topic is rejected. There is no topic-level call, because the topic belongs to the data source that created it.
  • On a host older than 1.2.0 the call returns an error. Check supportsFieldMetadata() first, or ignore the error; the plugin keeps its min_sdk_required.

Optional Features

Route claims and functional v2

MessageParserPluginBase answers two extension ids itself; parser authors do not implement them by hand:

  • pj.parser_route_claims.v1 is always answered. It classifies exact handler-table coverage (a type without a handler is declined) and never reports wildcard claims. The host synthesizes the universal wildcard scalar claim from each manifest encoding.
  • pj.parser_functional.v2 delivers scalar records and canonical-wire objects through synchronous caller-owned sinks, including one splice-eligible object field. It is answered only when the bound type has a handler; before bindSchema(), when any handler is registered.

The host resolves scalar and object routes independently. A parser may keep the scalar route for a type it flattens while another provider owns that type's canonical-object route.

Schema binding

Override bindSchema() to receive schema data before parsing begins. The default implementation records the bound type name, which the SchemaHandler dispatch looks up, so an override must call MessageParserPluginBase::bindSchema() first.

PJ::Status bindSchema(std::string_view type_name,
                       PJ::Span<const uint8_t> schema) override {
  if (auto status = PJ::MessageParserPluginBase::bindSchema(type_name, schema);
      !status) {
    return status;
  }
  // Store schema for use during parse().
  schema_.assign(schema.begin(), schema.end());
  // Build lookup tables, compile descriptors, etc.
  return PJ::okStatus();
}

If the plugin has its own type-name convention, normalize type_name before delegating, and register handlers under that same canonical form.

type_name identifies the encoding-specific message type, such as "sensor_msgs/msg/Imu" for ros2msg or "my.package.ImuSample" for Protobuf. schema contains encoding-specific bytes, such as ROS .msg definition text or a Protobuf FileDescriptorSet binary.

Configuration persistence

Override saveConfig() / loadConfig() to support layout save/restore:

std::string saveConfig() const override { return config_json_; }

PJ::Status loadConfig(std::string_view json) override {
  config_json_ = std::string(json);
  // Parse JSON and apply settings.
  // e.g. max_array_size_, use_embedded_timestamp_, etc.
  return PJ::okStatus();
}

Common configuration patterns:

  • Array clamping: {"max_array_size": 100} — limits how many array elements are expanded into individual series. Read and write it through PJ::sdk::arrayLimitFromJson() / arrayLimitToJson() (pj_plugins/sdk/parser_array_policy.hpp): the canonical keys (max_array_size, array_policy = clamp | skip) plus the legacy per-parser booleans, so every parser interprets a shared config the same way.
  • Embedded timestamps: {"use_embedded_timestamp": true} — the parser extracts timestamp from the payload (e.g. ROS Header.stamp) instead of using the host-provided timestamp_ns.

Embedded timestamp extraction

parse() receives the host's timestamp_ns. If the payload contains a timestamp (e.g. a ROS Header or protobuf timestamp field), the parser may write records with that timestamp instead:

PJ::Status parse(PJ::Timestamp timestamp_ns,
                  PJ::Span<const uint8_t> payload) override {
  // Extract embedded timestamp from payload.
  PJ::Timestamp ts = use_embedded_timestamp_
      ? extractTimestamp(payload)
      : timestamp_ns;

  const PJ::sdk::NamedFieldValue fields[] = { /* ... */ };
  return writeHost().appendRecord(ts, PJ::Span(fields));
}

This is a parser-internal decision, controlled via loadConfig().

Dialog integration

A MessageParser can provide a configuration dialog by exporting a dialog vtable from the same .so. This is useful for parsers that need GUI-based schema selection (e.g. Protobuf .proto file loading, include-path management, message-type selection).

The host resolves the dialog via MessageParserLibrary::resolveDialogVtable().

Ownership model — independent owned instance

A parser dialog is an independent owned instance. A DataSource dialog is a source member accessed through a borrowed getDialog() handle.

The host creates the parser dialog with dialog_vt->create() and runs it through its dialog runtime. It passes the resulting config JSON to parser instances through load_config(). The classes share a JSON config schema but are otherwise decoupled.

The host creates parser instances per topic during ensureParserBinding(). The dialog should appear once per parser library. The parser vtable therefore needs no parser-owned borrowed-dialog slot and provides none.

     Parser .so
┌──────────────────────────────────┐
│  class ProtoDialog               │  ← PJ::DialogPluginTyped
│    (file picker, include paths,  │
│     message-type combo)          │
│                                  │
│  class ProtoParser               │  ← PJ::MessageParserPluginBase
│    (no dialog_ member)           │
│    loadConfig(json) applies it   │
│                                  │
│  PJ_MESSAGE_PARSER_PLUGIN(...)   │  → exports parser vtable
│  PJ_DIALOG_PLUGIN(ProtoDialog,   │  → exports dialog vtable
│                   kManifestJson) │
└──────────────────────────────────┘

One .so, two vtables, but no ownership link between dialog and parser instances. The host creates the dialog independently and bridges config via JSON.

Lifecycle scenarios

Inline (embedded in a DataSource dialog): Declare a pj_parser_slot placeholder in the source dialog. The host detects it and resolves the parser library for the selected encoding. It creates an owned parser dialog and renders it in the slot.

Standalone: The host shows the parser dialog as a modal from a settings panel or parser-selection UI. This is host-application logic, not protocol.

Config flow for delegated sources

The host stores the JSON string returned by saveConfig() and passes it back to loadConfig(). When the source dialog embeds a parser dialog, the host adds a _parser_config key to that JSON, which PJ::sdk::parserConfigOverride() (pj_plugins/sdk/streaming_source.hpp) reads.

  1. Source calls runtimeHost().ensureParserBinding(request) — the source may leave parser_config_json empty in the request.
  2. Host intercepts, injects the stored parser config into parser.load_config() before calling parse().

Protobuf example sketch

A Protobuf parser dialog would typically manage:

  • .proto file selection (file picker)
  • Include paths for imports
  • Root message-type selection (combo box populated after parsing .proto files)
  • Config JSON: {"proto_files": [...], "include_paths": [...], "message_type": "..."}

The parser's loadConfig() receives this JSON and compiles the descriptor pool. parse() decodes with the selected message type. The dialog and parser share only the JSON schema contract; they never reference each other.

Manifest Schema

The manifest is a JSON string literal embedded in the vtable. The host reads it without instantiating the plugin.

Key Type Required Description
id string yes Stable plugin identifier used by the host catalog. Must be unique per plugin.
name string yes Human-readable plugin name.
version string yes Semver version string.
encoding array of strings yes Case-sensitive registered encodings this parser handles, e.g. ["json"], ["protobuf"], or ["ros1msg", "ros2msg"]. The host uses this list to match binding requests to parsers; one parser may register more than one encoding.

min_sdk_required, suggested_sdk_version (with a floor_test) and the deprecated min_plotjuggler_version are optional compatibility keys common to every family; see REQUIREMENTS.md §2.1.

Example:

{
  "id": "protobuf-parser",
  "name": "Protobuf Parser",
  "version": "1.0.0",
  "encoding": ["protobuf"]
}

Threading Model

All parser callbacks — bind(), bindSchema(), parse(), loadConfig(), saveConfig() — are called on the host's thread. The host guarantees single-threaded access per parser instance: no two callbacks will overlap for the same instance.

Write host methods (appendRecord(), ensureField(), etc.) must be called from the same thread that invoked parse(). Do not cache the write host view and call it from a background thread.

Lifecycle Invariants

The host guarantees the following call ordering:

  1. create() — always first.
  2. bind(registry) — before parse().
  3. bind_schema() (optional) — before parse(), called at most once.
  4. load_config() — before parse(), may be called multiple times.
  5. parse() — called once per message, may be called many times.
  6. destroy() — always last.

The host will never call parse() before bind(registry), and destroy() is always the last call.

Error Handling

All fallible SDK methods return PJ::Status (Expected<void>). Return okStatus() on success, unexpected("reason") on failure.

Patterns

Check-and-propagate — the standard pattern for write host calls:

auto field = writeHost().ensureField("temperature", PJ::PrimitiveType::kFloat64);
if (!field) {
  return PJ::unexpected(field.error());
}

Parse failures — when parse() encounters malformed payload data:

  • Return unexpected("reason") — the host logs the error and may skip the message. This is always safe; the host will continue calling parse() for subsequent messages.
  • Do not leave the parser in an inconsistent state — ensure field handles and internal buffers remain valid for the next parse() call.

Exception safety — the SDK base class catches all C++ exceptions in virtual method trampolines and converts them to PJ_error_t out-params plus false. You never need to worry about exceptions crossing the C ABI boundary.

How Parsers Are Used (Host Perspective)

DataSource plugins that act as transports (MQTT, ZMQ, MCAP, ROS bag files) don't decode payloads themselves. Instead they declare kCapabilityDelegatedIngest and push raw bytes through the host:

DataSource                        Host                         MessageParser
    │                               │                               │
    │  ensureParserBinding(         │                               │
    │    topic="sensor/imu",        │                               │
    │    encoding="protobuf",       │──→ load parser .so            │
    │    type_name="ImuSample",     │──→ create()                   │
    │    schema=descriptor_bytes)   │──→ bind(registry)             │
    │                               │──→ bind_schema("ImuSample",   │
    │                               │       descriptor_bytes)       │
    │  ←── binding handle           │                               │
    │                               │                               │
    │  pushMessage(handle,          │                               │
    │    timestamp, fetcher)        │──→ parse(timestamp, payload)  │
    │                               │       │                       │
    │                               │       │ writeHost().append... │
    │                               │       ▼                       │
    │                               │    data stored                │

The parser is topic-scoped — the host binds a separate write host per topic, so ensureField("x") in the parser creates "sensor/imu/x" in the datastore.

Testing

Use PJ::sdk::testing::ParserWriteRecorder from pj_base/include/pj_base/sdk/testing/parser_write_recorder.hpp to write parser unit tests without re-implementing the fake write-host vtable. Pair it with ParserRuntimeRecorder when the parser emits diagnostics:

#include <pj_base/sdk/testing/parser_write_recorder.hpp>
#include <pj_base/sdk/testing/parser_runtime_recorder.hpp>

TEST(MyParserTest, Basic) {
  auto library = PJ::MessageParserLibrary::load(PJ_MY_PARSER_PLUGIN_PATH);
  auto handle = library->createHandle();

  PJ::sdk::testing::ParserWriteRecorder recorder;
  PJ::sdk::testing::ParserRuntimeRecorder diagnostic_recorder;
  PJ::ServiceRegistryBuilder registry;
  registry.registerService<PJ::sdk::ParserWriteHostService>(recorder.makeHost());
  registry.registerService<PJ::sdk::ParserRuntimeHostService>(
      diagnostic_recorder.makeHost());
  ASSERT_TRUE(handle.bind(registry.view()));

  const uint8_t payload[] = { /* ... */ };
  ASSERT_TRUE(handle.parse(1000, payload));

  ASSERT_EQ(recorder.rows().size(), 1u);
  EXPECT_EQ(recorder.rows()[0].fields[0].name, "temperature");
  EXPECT_DOUBLE_EQ(recorder.rows()[0].fields[0].numeric, 23.5);
  ASSERT_EQ(diagnostic_recorder.diagnostics().size(), 1u);
  EXPECT_EQ(diagnostic_recorder.diagnostics()[0].stable_code,
            "integer_overflow");
}

Each RecordedField exposes its primitive type, .numeric, .bool_value and .string_value. .numeric covers all integer/float types and maps bools to 1.0/0.0. Tests can assert uniformly without type dispatch code.

Examples

  • pj_plugins/examples/mock_json_parser.cpp — minimal parser that treats payloads as text-encoded doubles and writes one "value" field per message.
  • pj_plugins/examples/mock_schema_parser.cpp — richer parser demonstrating the high-throughput pattern: ensureField() + appendBoundRecord(), schema binding, config persistence, and error handling.
  • pj_plugins/tests/message_parser_functional_extension_test.cpp — functional C-extension contract, exact-once sinks, exception containment, truthful migration detection, malformed providers, and anchor release.
  • pj_plugins/tests/functional_image_parser_plugin.cpp plus message_parser_library_test.cpp — real-DSO ownership test proving a decoded object survives parser destruction and plugin unload.

Builtin-object pipeline

Beyond the scalar-column output that parse() and the sdk::ParserWriteHostService cover, the SDK offers a second, narrow output channel for canonical builtin objects returned by the parser and visualised by widgets that never learn the source-specific wire format.

The table-driven SchemaHandler routes on MessageParserPluginBase participate:

PJ::sdk::SchemaHandler handler;
handler.object_type = PJ::sdk::BuiltinObjectType::kImage;
handler.parse_scalars =
    [](PJ::Timestamp ts, PJ::Span<const uint8_t> payload)
        -> PJ::Expected<PJ::sdk::ScalarRecord> { /* ... */ };
handler.parse_object =
    [](PJ::Timestamp ts, PJ::sdk::PayloadView payload)
        -> PJ::Expected<PJ::sdk::ObjectRecord> { /* ... */ };
  • classifySchema is the a-priori declaration — given a type name + schema bytes, announce which BuiltinObjectType this schema produces (kNone for scalar-only; the enum is in pj_base/builtin/builtin_object.hpp and the catalog in builtin_type.md). The host consults the answer before it ever sees the payload, so it can pick the right ObjectIngestPolicy for the topic.
  • Classification is side-effect free. classifySchema must not emit parser runtime diagnostics; diagnostics belong to parse callbacks that have observed actual message data.
  • parse_scalars returns a ScalarRecord: small-metadata fields (width, height, frame_id, …) plus an optional parser-controlled timestamp.
  • parse_object returns an ObjectRecord: the actual builtin value, type-erased as PJ::sdk::BuiltinObject (an explicit BuiltinObjectType tag plus the opaque value), plus an optional parser-controlled timestamp. The host downcasts with obj.get<PJ::sdk::Image>() to dispatch to the matching viewer.

The types above are plugin-author C++ conveniences, not the binary boundary. After bindSchema, MessageParserPluginBase advertises functional v2 when the bound type has a handler. Its trampolines:

  1. invokes parseScalars / parseObject inside the plugin DSO;
  2. delivers scalar fields through one synchronous caller-owned C sink, or serialize the builtin to canonical PJ.* protobuf wire bytes and deliver (type, optional timestamp, bytes) through one object sink; v2 may instead identify one frozen bulk field as a splice into the parse payload;
  3. destroys every plugin-side C++ result before returning.

MessageParserHandle::parseScalarsFunctional() copies or consumes scalar views only during the callback.

parseObjectFunctional() uses the v2 extension and reconstructs a valid splice when present. It checks that the emitted type matches the binding's expected object type, then decodes synchronously into a host-owned ObjectRecord. That value remains safe after the parser instance and shared library are gone. Provider/sink exceptions, unknown or mismatched object tags, malformed tables or splices, and zero/multiple sink calls fail closed.

For large objects with an existing ownership anchor, pass sdk::PayloadView instead of a bare Span. The C extension transfers one PJ_payload_t anchor reference into the plugin and releases it exactly once. Handlers can then propagate the input buffer without an initial copy.

The DSO boundary still performs one canonical serialization and one host decode. This avoids exporting plugin allocators, destructors, RTTI, STL layout or type-erasure internals. Measure this path for image/point-cloud workloads. New host code reads parser output through it rather than through direct C++ calls; the direct bridge is described below.

Parsers built before SDK 0.22 expose no usable functional extension: pre-0.21 builds expose none, and 0.21 builds expose only the retired v1. New host code negotiates v2.

PlotJuggler 4 reads objects from every parser by casting the opaque context to MessageParserPluginBase* and calling parseObject(). That direct C++ bridge is deprecated but supported through 1.x. For a parser author it has one consequence: a parser and the host must agree on the layout of the builtin struct the parser returns, so a parser that emits a type whose struct changed in an SDK release has to be rebuilt against that release. The SDK treats such a change as a MAJOR for exactly that reason (see ABI rules). Nothing in a parser's source depends on the bridge, and nothing changes for it when the host moves to v2.

Builtin types and their canonical codecs live under pj_base/builtin/, one header per type. serializeBuiltinObject() / deserializeBuiltinObject() cover every stable builtin tag, RobotDescription included. A zero-byte payload is the valid proto3 default message when the separate type tag is known. sdk::Image carries an open-ended std::string encoding ("rgb8", "bgr8", "mono8", "jpeg", "png", "compressedDepth", …) so raw and compressed images share a single type. New types are appended without changing the BuiltinObject type (its tag-plus-opaque-value erasure is forward-compatible by construction).

Reference implementation: parser_ros in the official plugins repository (pj-official-plugins) — a SchemaHandler table driven by a static catalog(). PLUGIN_DEVELOPMENT.md in that repository gives a top-down walkthrough.

Common Mistakes

Symptom Cause Fix
Plugin loads but parse() is never called encoding array in the manifest does not match the encoding name the source requests Match the binding request's encoding string exactly (case-sensitive)
Host cannot bind the parser at runtime Manifest missing the encoding array entirely Add "encoding": ["…"] (required for parsers)
First parse() after restart fails silently Schema-derived state lost; bindSchema() was not called for this encoding because none is needed Initialize lazily in parse() for schema-less encodings
appendBoundRecord() returns failure Field handles obtained before bind(registry) completed (or reused after destroy) Acquire field handles inside parse() or after bind(registry); never cache them across instances
Throughput is one quarter of the source's input rate Parser decodes a naturally batched payload one row at a time If the payload is parser-shaped, use parser appendArrowStream(); if it is a whole source/container, move bulk decoding to a DataSource
Embedded timestamp ignored even when configured Parser uses the host-supplied timestamp_ns and never extracts from payload Read the config flag in loadConfig; choose between extracted and host timestamps inside parse()
Memory grows unboundedly across parse() calls Per-message state leaked (e.g. descriptor pools rebuilt per call) Build schema-derived caches in bindSchema() or loadConfig(), not in parse()