sim_run_core/bootloader.rs
1//! A reusable bootloader for a binary that ships statically-linked libraries and
2//! boots them through the same [`LoadSession`] machinery the `sim` binary uses.
3//!
4//! Every product binary composes a [`Bootloader`], registers its serve library as a
5//! host factory, and dispatches the library's `cli/main/<verb>` entrypoint -- the
6//! exact path `sim --load host:<lib> <verb>` follows. A binary owns the one canonical
7//! runtime bootstrap through this type and constructs no `Cx` of its own.
8//!
9//! The pattern mirrors the interactive REPL boot (`sim repl`): a host-registered
10//! library exports a `cli/main/<verb>` function whose [`Callable`] runs the (possibly
11//! long-lived, blocking) serve loop and returns a truthy value at shutdown, which the
12//! bootloader maps to the process exit code.
13
14use std::ffi::OsString;
15
16use sim_kernel::{CapabilityName, Cx, Lib, Symbol};
17
18use crate::{
19 CliError, LibSourceSpec, LoadSession, RuntimeConfigState, parse_args, run_command_with_session,
20};
21
22/// A thin bootloader over [`LoadSession`] for a single-library product binary.
23///
24/// ```no_run
25/// # use sim_run_core::Bootloader;
26/// # struct MyServeLib;
27/// # impl MyServeLib { fn new() -> Self { Self } }
28/// # impl sim_kernel::Lib for MyServeLib {
29/// # fn manifest(&self) -> sim_kernel::LibManifest { unimplemented!() }
30/// # fn load(&self, _: &mut sim_kernel::LoadCx, _: &mut sim_kernel::Linker<'_>)
31/// # -> sim_kernel::Result<()> { Ok(()) }
32/// # }
33/// // `my-server ARGS...` boots exactly like `sim serve ARGS...`, dispatching the
34/// // library's `cli/main/serve` entrypoint. No Cx::new in the binary.
35/// let code = Bootloader::standard()
36/// .host_verb("serve", "lib/my-server", || Box::new(MyServeLib::new()))
37/// .run(std::iter::once("serve".into()).chain(std::env::args_os().skip(1)))?;
38/// std::process::exit(code);
39/// # Ok::<(), sim_run_core::CliError>(())
40/// ```
41pub struct Bootloader {
42 session: LoadSession,
43}
44
45impl Bootloader {
46 /// The standard boot session: the in-process host loader only, matching the
47 /// default `sim` binary. Add libraries with [`Bootloader::host_verb`].
48 pub fn standard() -> Self {
49 Self {
50 session: LoadSession::new(),
51 }
52 }
53
54 /// Registers a statically-linked library under `name` and makes it the default
55 /// source for `verb`, so a bare `<verb> ARGS...` dispatches to the library's
56 /// `cli/main/<verb>` entrypoint with no explicit `--load`.
57 ///
58 /// The library must be a [`LibTarget::HostRegistered`](sim_kernel::LibTarget)
59 /// lib that exports a `cli/main/<verb>` function (see
60 /// [`crate::cli_main_entrypoint_symbol`]).
61 pub fn host_verb<F>(self, verb: &str, name: &str, factory: F) -> Self
62 where
63 F: Fn() -> Box<dyn Lib> + Send + Sync + 'static,
64 {
65 Self {
66 session: self
67 .session
68 .with_host_factory(name.to_owned(), factory)
69 .with_default_verb_sources(
70 verb.to_owned(),
71 vec![LibSourceSpec::Host(name.to_owned())],
72 ),
73 }
74 }
75
76 /// Registers a statically-linked library under `name`, makes it the default
77 /// source for `verb`, and reads the supplied config library ids before the
78 /// host library is instantiated.
79 pub fn host_verb_with_config<F>(
80 self,
81 verb: &str,
82 name: &str,
83 config_libs: Vec<Symbol>,
84 factory: F,
85 ) -> Self
86 where
87 F: Fn(&RuntimeConfigState) -> Box<dyn Lib> + Send + Sync + 'static,
88 {
89 Self {
90 session: self
91 .session
92 .with_host_factory_with_config(name.to_owned(), factory)
93 .with_default_verb_sources(
94 verb.to_owned(),
95 vec![LibSourceSpec::Host(name.to_owned())],
96 )
97 .with_default_verb_config_libs(verb.to_owned(), config_libs),
98 }
99 }
100
101 /// Registers a statically-linked library under `name` WITHOUT binding it to a
102 /// verb -- for a supporting library the served verb needs, most commonly the boot
103 /// codec (register it under `codec/<name>` and pass `--codec <name>` so the boot
104 /// resolves the host codec instead of the default).
105 pub fn host_lib<F>(self, name: &str, factory: F) -> Self
106 where
107 F: Fn() -> Box<dyn Lib> + Send + Sync + 'static,
108 {
109 Self {
110 session: self.session.with_host_factory(name.to_owned(), factory),
111 }
112 }
113
114 /// Grants a capability the served library requires (for example a transport or
115 /// tool-call capability).
116 pub fn with_capability(self, capability: CapabilityName) -> Self {
117 Self {
118 session: self.session.with_capability(capability),
119 }
120 }
121
122 /// Installs context-level runtime support into the boot `Cx` before dispatch
123 /// (e.g. a codec, an eval policy, a supporting lib). Concrete serve behavior
124 /// stays in the loaded library.
125 pub fn with_context<F>(self, configure: F) -> Self
126 where
127 F: FnOnce(&mut Cx),
128 {
129 Self {
130 session: self.session.with_context(configure),
131 }
132 }
133
134 /// Boots the runtime, applies the registered libraries, and dispatches `args`
135 /// (typically the process arguments). A blocking serve verb runs to completion
136 /// here; its returned value becomes the process exit code.
137 pub fn run<I, S>(self, args: I) -> Result<i32, CliError>
138 where
139 I: IntoIterator<Item = S>,
140 S: Into<OsString>,
141 {
142 let mut session = self.session;
143 let command = parse_args(args)?;
144 run_command_with_session(command, &mut session)
145 }
146}