An RTI inside your process

With the cargo feature embedded, the Rust client microrti-client carries the MicroRTI engine, the HLA 4 RTI itself. Your program then creates an RTI in its own memory, and its federates connect to it with plain function calls. There is no microrti server to start and no port to choose, and the Federate Protocol is not used. The Python package has the same thing, EmbeddedRti. This page shows both, and what changes compared with a server.

When to use it

An embedded RTI fits when every federate runs in one process:

  • tests, where each test can have an RTI of its own, with nothing to start or stop around it and no port to pick;
  • notebooks and short Python scripts;
  • simulations whose federates are threads or objects of one program;
  • demos that must run from one binary. The repository’s restaurant demo does this: it runs a waiter and a guest federate on an RTI inside its process unless you give it an RTI address with --rti.

When federates run in other processes or on other machines, or are written in Java or C++, they need a server they can reach over the network: the microrti binary, or the same server started from your Rust program (see when other processes must reach it).

Rust

Add the client with the feature:

[dependencies]
microrti-client = { version = "0.5", features = ["embedded"] }

This program creates an RTI, connects two federates to it in two different ways, and has one send an interaction to the other. It was built against microrti-client 0.5.0:

use std::sync::mpsc;
use std::time::Duration;

use microrti_client::embedded::{EmbeddedRti, RtiConfig};
use microrti_client::{
    Callback, CallbackFn, CallbackModel, FomModule, NullFederateAmbassador, ParameterHandleValueMap,
    ResignAction, RtiAmbassador, RtiConfiguration, RtiResult, decode_hla_unicode_string,
    encode_hla_unicode_string,
};

const FOM: &str = r#"<?xml version="1.0"?>
<objectModel xmlns="http://standards.ieee.org/IEEE1516-2025">
  <interactions><interactionClass><name>HLAinteractionRoot</name>
    <interactionClass><name>Greeting</name><sharing>PublishSubscribe</sharing>
      <transportation>HLAreliable</transportation><order>Receive</order>
      <parameter><name>Text</name><dataType>HLAunicodeString</dataType></parameter>
    </interactionClass>
  </interactionClass></interactions>
</objectModel>"#;

fn main() -> RtiResult<()> {
    // The RTI lives in this process, as long as a handle to it does.
    let embedded = EmbeddedRti::new(RtiConfig::default());

    // First federate: an ambassador made by the embedded RTI itself.
    let speaker = embedded.ambassador();
    speaker.connect(NullFederateAmbassador, CallbackModel::Evoked)?;
    speaker.create_federation_execution("Hello", &FomModule::content("Hello.xml", FOM))?;
    speaker.join_federation_execution("speaker", "Hello")?;

    // Second federate: ordinary code that only knows an RTI address, here "embedded:".
    embedded.register("embedded");
    let (queue, callbacks) = mpsc::channel();
    let federate_ambassador = CallbackFn::new(move |callback: Callback| queue.send(callback).or(Ok(())));
    let listener = RtiAmbassador::new();
    let configuration = RtiConfiguration::new().with_rti_address("embedded:");
    listener.connect_with_configuration(federate_ambassador, CallbackModel::Evoked, &configuration)?;
    listener.join_federation_execution("listener", "Hello")?;

    let greeting = speaker.get_interaction_class_handle("Greeting")?;
    let text = speaker.get_parameter_handle(&greeting, "Text")?;
    speaker.publish_interaction_class(&greeting)?;
    listener.subscribe_interaction_class(&greeting)?;

    let values = ParameterHandleValueMap::from([(text.clone(), encode_hla_unicode_string("hello, world"))]);
    speaker.send_interaction(&greeting, &values, b"")?;

    // EVOKED: the callback runs here, when the listener asks for it.
    listener.evoke_callback(Duration::from_secs(1))?;
    for callback in callbacks.try_iter() {
        if let Callback::ReceiveInteraction { parameter_values, .. } = callback {
            let said = parameter_values.get(&text).and_then(|value| decode_hla_unicode_string(value).ok());
            println!("listener heard: {}", said.unwrap_or_default());
        }
    }

    for rti in [&speaker, &listener] {
        rti.resign_federation_execution(ResignAction::NoAction)?;
    }
    speaker.destroy_federation_execution("Hello")?;
    for rti in [&speaker, &listener] {
        rti.disconnect()?;
    }
    Ok(())
}
cargo run
listener heard: hello, world

The program reaches the RTI in two ways:

  • embedded.ambassador() returns an RtiAmbassador whose Connect always reaches this RTI, whatever RTI address it is given. Use it when the code that creates the federate also creates the RTI.
  • embedded.register("embedded") makes this RTI the process-wide connector for the address scheme embedded. From then on, any RtiAmbassador::new() in the process reaches it with the RTI address embedded:. Use it when the federate code reads its RTI address from a setting: point the setting at embedded: in tests and at tcp://rti.example.org:15164 in production, and the federate code does not change.

Everything after Connect is the same API as with a server, callbacks and both callback models included.

Settings

RtiConfig holds the settings of the engine, which today means the authorisation. An embedded RTI with a password refuses federates without it, as a server would:

use std::time::Duration;

use microrti_client::embedded::{EmbeddedRti, RtiConfig};
use microrti_client::{CallbackModel, Credentials, NullFederateAmbassador, RtiResult};

fn main() -> RtiResult<()> {
    let embedded =
        EmbeddedRti::with_tick_period(RtiConfig::with_password("open sesame"), Duration::from_millis(20));
    let rti = embedded.ambassador();
    if let Err(error) = rti.connect(NullFederateAmbassador, CallbackModel::Evoked) {
        println!("without credentials: {error}");
    }
    let credentials = Credentials::plain_text_password("open sesame");
    rti.connect_with_credentials(NullFederateAmbassador, CallbackModel::Evoked, &credentials)?;
    println!("with the password: connected = {}", rti.is_connected());
    rti.disconnect()
}
without credentials: Unauthorized: this RTI requires credentials
with the password: connected = true

EmbeddedRti::with_tick_period sets the period of the tick thread (see below); EmbeddedRti::new uses 100 ms. EmbeddedRti::from_rti takes an engine (microrti_client::embedded::Rti) that you built yourself, for example with an authorisation service of your own (Rti::with_authorizer), and with_rti runs a closure on the engine.

If the program never talks to a server, you can leave the Federate Protocol out of the build. With default-features = false the client has no network link and does not pull in Tokio; the first program above builds and runs unchanged with:

[dependencies]
microrti-client = { version = "0.5", default-features = false, features = ["embedded"] }

Since version 0.5.0 such a build still has an HTTP client (ureq, with rustls), which the embedded RTI uses to read FOM modules named by http: and https: URLs.

FOM modules named by URL

An embedded RTI reads the FOM modules that its federates name by URL as the microrti server does by default: every file: URL of an absolute path, and every http: and https: URL. A name without a scheme is refused, here FomModule::url("Chat.xml"):

CouldNotOpenFOM: could not open FOM module 'Chat.xml': not a URL: write a file:, http: or https: URL, or send the content of the module

Version 0.4 read such a name as a path relative to the working directory of the process. Write FomModule::file("Chat.xml"), which reads the file in the federate and sends its content, or a file: URL with an absolute path. To restrict what the RTI reads, for example when the URLs come from a user:

use std::time::Duration;

use microrti_client::embedded::{EmbeddedRti, FomUrlPolicy, FomUrlReader, RtiConfig};

let embedded = EmbeddedRti::new(RtiConfig::default());
// Only the files of the directory "foms", named by file: URLs such as file:Chat.xml.
embedded.set_fom_url_policy(FomUrlPolicy::directory("foms")?);
// Or none at all, and 5 seconds for all the modules of one call instead of 30.
embedded.set_fom_url_reader(FomUrlReader::new(FomUrlPolicy::refused()).with_timeout(Duration::from_secs(5)));

The setting applies to the calls that begin afterwards. With FomUrlPolicy::refused(), the answer is the one the server gives with fom_urls = "none" (FOM modules named by URL). The reading happens outside the lock of the RTI, so the other federates of the process go on while one call waits for its modules.

Python

The Python package has EmbeddedRti built in. Its constructor takes two keyword arguments, password and tick_period (in seconds), and it has the same ambassador() and register(scheme) methods. The package is not on PyPI; Python client explains how to install it. This script ran with version 0.3.0 of the package:

import microrti
from microrti import CallbackModel, Credentials, EmbeddedRti, FomModule, ResignAction, RtiAmbassador
from microrti.encoding import decode, encode

FOM = FomModule.content(
    "Hello.xml",
    """<?xml version="1.0"?>
<objectModel xmlns="http://standards.ieee.org/IEEE1516-2025">
  <interactions><interactionClass><name>HLAinteractionRoot</name>
    <interactionClass><name>Greeting</name><sharing>PublishSubscribe</sharing>
      <transportation>HLAreliable</transportation><order>Receive</order>
      <parameter><name>Text</name><dataType>HLAunicodeString</dataType></parameter>
    </interactionClass>
  </interactionClass></interactions>
</objectModel>""",
)

embedded = EmbeddedRti()
speaker = embedded.ambassador()
speaker.connect(None, CallbackModel.EVOKED)
speaker.create_federation_execution("Hello", FOM)
speaker.join_federation_execution("speaker", "Hello")

embedded.register("embedded")
heard = []
listener = RtiAmbassador()
listener.connect(heard.append, CallbackModel.EVOKED, "embedded:")
listener.join_federation_execution("listener", "Hello")

greeting = speaker.get_interaction_class_handle("Greeting")
text = speaker.get_parameter_handle(greeting, "Text")
speaker.publish_interaction_class(greeting)
listener.subscribe_interaction_class(greeting)
speaker.send_interaction(greeting, {text: encode("HLAunicodeString", "hello, world")})

listener.evoke_callback(1.0)
for callback in heard:
    if isinstance(callback, microrti.callbacks.ReceiveInteraction):
        print("listener heard:", decode("HLAunicodeString", callback.parameter_values[text]))

for rti in (speaker, listener):
    rti.resign_federation_execution(ResignAction.NO_ACTION)
speaker.destroy_federation_execution("Hello")
for rti in (speaker, listener):
    rti.disconnect()

locked = EmbeddedRti(password="open sesame")
rti = locked.ambassador()
try:
    rti.connect(None, CallbackModel.EVOKED)
except microrti.Unauthorized as error:
    print("refused:", error)
rti.connect(None, CallbackModel.EVOKED, credentials=Credentials.plain_text_password("open sesame"))
print("connected:", rti.is_connected())
rti.disconnect()
listener heard: hello, world
refused: this RTI requires credentials
connected: True

Here the listener passes heard.append as its federate ambassador: any function works, and receives each callback as a value of microrti.callbacks. A subclass of FederateAmbassador works as well.

The FOM modules named by URL follow the same rules as in Rust, with the same names: embedded.set_fom_url_policy(FomUrlPolicy.directory("foms")) or FomUrlPolicy.refused(), and embedded.set_fom_url_reader(FomUrlReader(FomUrlPolicy.refused()).with_timeout(5)) for a time limit in seconds. A reader carries its own policy, so set the reader first and the policy after it, or give the reader the policy you want.

What differs from a server

The engine is the same one the microrti server runs, so the services behave the same. What surrounds the engine differs:

microrti serverEmbedded RTI
How federates reach itFederate Protocol over TCP, TLS, WebSocket or secure WebSocketa function call under one lock; no network
Who can joinany federate that can reach a listener, in any languagefederates of this process only
Sessionsheartbeats, timeouts, resume after a broken connectionnone: there is no connection to break
SettingsRID file and command lineRtiConfig (authorisation), the tick period and the FOM URL policy, in code
TLS, message size limityesnot applicable
Loginfo lines for sessions, joins and resignsnone of its own
MOM service report logs (11.5.2)files in service_report_directorykept in memory
Federation savesin memory, or files in save_directoryin memory, unless you give the engine a store of your own (Rti::set_snapshot_store)
FOM modules named by URLfile:, http: and https: URLs read by default; fom_urls or fom_url_directory restrict themthe same by default; set_fom_url_policy restricts them
Lifetimeuntil the process is stoppeduntil the last handle and the last connection are dropped

Section 7 of the architecture page draws the embedded RTI next to the network link.

The tick thread

A background thread named microrti-embedded-tick calls the engine every 100 ms (or the period you chose) for the work that depends on the wall clock: the periodic reports of the MOM and update rate reduction (6.1.13). Logical time does not depend on it. If the thread cannot be started, the RTI works without that wall-clock work, and the failure is logged through tracing.

Lifetime

EmbeddedRti is a handle: cloning it gives another handle to the same RTI. The tick thread stops when the last handle is dropped. Ambassadors still connected at that moment keep working, but nothing drives the wall-clock work any more; when they disconnect too, the RTI is gone, and its federation executions with it. register keeps a handle in the process-wide connectors, so a registered RTI lives until the process ends.

When other processes must reach it

If your program should start the RTI itself but federates outside the process must join, start the real server from Rust instead. The microrti crate is the server as a library:

[dependencies]
microrti = "0.5"
microrti-client = "0.5"
use microrti::{RtiServer, ServerSettings, TransportKind};
use microrti_client::{CallbackModel, NullFederateAmbassador, RtiAmbassador, RtiConfiguration};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A real Federate Protocol server on the loopback interface, port chosen by the system.
    let server = RtiServer::start(ServerSettings::loopback(&[TransportKind::Tcp]))?;
    let address = server.local_endpoint(TransportKind::Tcp).ok_or("no TCP listener")?;
    println!("RTI listening on {address}");

    let rti = RtiAmbassador::new();
    let configuration = RtiConfiguration::new().with_rti_address(address.as_str());
    rti.connect_with_configuration(NullFederateAmbassador, CallbackModel::Evoked, &configuration)?;
    println!("connected federates: {}", server.status().connected_count());
    rti.disconnect()?;
    server.shutdown();
    Ok(())
}
RTI listening on tcp://127.0.0.1:59111
connected federates: 1

Any Federate Protocol client on the same machine, such as a Python script or a Java federate, can connect to the printed address while the server runs. ServerSettings has the same settings as the RID file of Configure the RTI, save_directory and the FOM URL settings included. Version 0.5.0 replaced its field fom_url_directory by fom_urls, of type FomUrls (All, the default, None or Directory(path)), and added fom_url_timeout and fom_url_root_certificates to ServerSettings and to Rid: code that builds either with a struct literal, without ..ServerSettings::default() or ..Rid::default(), must set them.

let settings = ServerSettings {
    fom_urls: FomUrls::None,
    fom_url_timeout: Duration::from_secs(10),
    ..ServerSettings::loopback(&[TransportKind::Tcp])
};

RtiServer::start_with_rti, which takes an engine you built yourself, does not apply save_directory; give that engine the store behind the setting instead, with rti.set_snapshot_store(Box::new(FileSnapshotStore::open("saves")?)). The engine reads no URL itself: the server reads the modules named by URL, as its ServerSettings say, whatever engine it was given.

Next steps