1use std::{
2 collections::{BTreeMap, BTreeSet},
3 sync::Arc,
4};
5
6use sim_kernel::{
7 CapabilityName, CatalogSource, Cx, DefaultFactory, Error as KernelError, GrantSeat, HandleSeed,
8 Lib, LibId, LibLoader, LibManifest, LibSource as KernelLibSource,
9 LibSourceSpec as KernelLibSourceSpec, LoaderRegistry, NoopEvalPolicy, Symbol,
10};
11use sim_lib_stream_host::native_audio_provider_capability;
12
13use crate::{
14 CliBoot, CliError, ConfigReportKind, CratesIoResolver, CratesIoSpec, LibSourceSpec,
15 LoadReceipt, LoadReceiptRole,
16 codec_boot::{boot_codec_name, codec_lib_symbol, explicit_codec_source_index},
17 config::{RuntimeConfigState, load_config_sources},
18 crates_io::fallback_spec_for_symbol,
19 host::{HostLibRegistry, HostSourceLoader, host_receipt},
20 source::symbol_from_text,
21};
22
23pub struct LoadSession {
25 cx: Cx,
26 seat: GrantSeat,
30 loaders: LoaderRegistry,
31 hosts: HostLibRegistry,
32 crates_io: CratesIoResolver,
33 catalog_sources: BTreeMap<Symbol, LibSourceSpec>,
34 default_verb_sources: BTreeMap<String, Vec<LibSourceSpec>>,
35 default_verb_config_libs: BTreeMap<String, Vec<Symbol>>,
36 receipts: Vec<LoadReceipt>,
37 config: RuntimeConfigState,
38 native_audio_provider_active: bool,
39}
40
41trait GrantOutcome {
42 fn expect_granted(self);
43}
44
45impl GrantOutcome for () {
46 fn expect_granted(self) {}
47}
48
49impl GrantOutcome for Result<(), KernelError> {
50 fn expect_granted(self) {
51 self.expect("load session grant seat grants into its own Cx");
52 }
53}
54
55macro_rules! expect_granted {
56 ($grant:expr) => {{
57 #[allow(clippy::let_unit_value)]
58 let grant_result = $grant;
59 #[allow(clippy::unit_arg)]
60 grant_result.expect_granted();
61 }};
62}
63
64impl LoadSession {
65 pub fn new() -> Self {
67 Self::with_cache_root(std::path::PathBuf::from(".sim/cache/libs"))
68 }
69
70 pub fn with_cache_root(cache_root: std::path::PathBuf) -> Self {
72 let mut loaders = LoaderRegistry::new();
73 loaders.add_loader(HostSourceLoader);
74 let (cx, seat) = Cx::new_seated(
75 Arc::new(NoopEvalPolicy),
76 Arc::new(DefaultFactory),
77 HandleSeed::new(1),
78 );
79 Self {
80 cx,
81 seat,
82 loaders,
83 hosts: HostLibRegistry::default(),
84 crates_io: CratesIoResolver::new(cache_root),
85 catalog_sources: BTreeMap::new(),
86 default_verb_sources: BTreeMap::new(),
87 default_verb_config_libs: BTreeMap::new(),
88 receipts: Vec::new(),
89 config: RuntimeConfigState::default(),
90 native_audio_provider_active: false,
91 }
92 }
93
94 pub fn crates_io_cache_root(&self) -> &std::path::Path {
96 self.crates_io.cache_dir()
97 }
98
99 pub fn add_loader(&mut self, loader: impl LibLoader + 'static) {
101 self.loaders.add_loader(loader);
102 }
103
104 pub fn install_supplied_capsule(&mut self, capsule: Box<dyn Lib>) -> Result<LibId, CliError> {
107 self.cx
108 .load_lib(capsule.as_ref())
109 .map_err(|error| CliError::new(format!("install supplied capsule: {error}")))
110 }
111
112 pub fn add_catalog_source(&mut self, symbol: impl AsRef<str>, source: CatalogSource) {
114 let symbol = symbol_from_text(symbol.as_ref());
115 self.catalog_sources
116 .insert(symbol.clone(), catalog_source_spec(source.clone()));
117 self.loaders.add_source(symbol, source);
118 }
119
120 pub fn with_catalog_source(mut self, symbol: impl AsRef<str>, source: CatalogSource) -> Self {
122 self.add_catalog_source(symbol, source);
123 self
124 }
125
126 pub fn with_loader(mut self, loader: impl LibLoader + 'static) -> Self {
128 self.add_loader(loader);
129 self
130 }
131
132 pub fn add_host_factory(
134 &mut self,
135 name: impl Into<String>,
136 factory: impl Fn() -> Box<dyn Lib> + Send + Sync + 'static,
137 ) {
138 self.hosts.add(name, factory);
139 }
140
141 pub fn add_host_factory_with_config(
144 &mut self,
145 name: impl Into<String>,
146 factory: impl Fn(&RuntimeConfigState) -> Box<dyn Lib> + Send + Sync + 'static,
147 ) {
148 self.hosts.add_with_config(name, factory);
149 }
150
151 pub fn with_host_factory(
153 mut self,
154 name: impl Into<String>,
155 factory: impl Fn() -> Box<dyn Lib> + Send + Sync + 'static,
156 ) -> Self {
157 self.add_host_factory(name, factory);
158 self
159 }
160
161 pub fn with_host_factory_with_config(
163 mut self,
164 name: impl Into<String>,
165 factory: impl Fn(&RuntimeConfigState) -> Box<dyn Lib> + Send + Sync + 'static,
166 ) -> Self {
167 self.add_host_factory_with_config(name, factory);
168 self
169 }
170
171 pub fn with_crates_io_resolver(mut self, resolver: CratesIoResolver) -> Self {
173 self.crates_io = resolver;
174 self
175 }
176
177 pub fn with_context(mut self, configure: impl FnOnce(&mut Cx)) -> Self {
182 configure(&mut self.cx);
183 self
184 }
185
186 pub fn with_capability(mut self, capability: CapabilityName) -> Self {
193 expect_granted!(self.seat.grant(&mut self.cx, capability));
194 self
195 }
196
197 pub fn add_default_verb_sources(
199 &mut self,
200 verb: impl Into<String>,
201 sources: Vec<LibSourceSpec>,
202 ) {
203 self.default_verb_sources.insert(verb.into(), sources);
204 }
205
206 pub fn add_default_verb_config_libs(&mut self, verb: impl Into<String>, libs: Vec<Symbol>) {
209 self.default_verb_config_libs.insert(verb.into(), libs);
210 }
211
212 pub fn with_default_verb_sources(
215 mut self,
216 verb: impl Into<String>,
217 sources: Vec<LibSourceSpec>,
218 ) -> Self {
219 self.add_default_verb_sources(verb, sources);
220 self
221 }
222
223 pub fn with_default_verb_config_libs(
226 mut self,
227 verb: impl Into<String>,
228 libs: Vec<Symbol>,
229 ) -> Self {
230 self.add_default_verb_config_libs(verb, libs);
231 self
232 }
233
234 pub fn cx(&self) -> &Cx {
236 &self.cx
237 }
238
239 pub(crate) fn cx_mut(&mut self) -> &mut Cx {
240 &mut self.cx
241 }
242
243 pub(crate) fn crates_io(&self) -> &CratesIoResolver {
244 &self.crates_io
245 }
246
247 pub(crate) fn hosts(&self) -> &HostLibRegistry {
248 &self.hosts
249 }
250
251 pub(crate) fn catalog_sources(&self) -> &BTreeMap<Symbol, LibSourceSpec> {
252 &self.catalog_sources
253 }
254
255 pub(crate) fn resolve_data_source(&self, source: KernelLibSourceSpec) -> KernelLibSourceSpec {
256 self.loaders.resolve_source_spec(&source)
257 }
258
259 pub(crate) fn inspect_data_source_manifest(
260 &mut self,
261 source: KernelLibSourceSpec,
262 ) -> Result<LibManifest, CliError> {
263 self.loaders
264 .inspect_manifest(&mut self.cx, source.into())
265 .map_err(|err| CliError::new(format!("inspect source: {err}")))
266 }
267
268 pub fn receipts(&self) -> &[LoadReceipt] {
270 &self.receipts
271 }
272
273 pub fn config_state(&self) -> &RuntimeConfigState {
275 &self.config
276 }
277
278 pub fn config_state_mut(&mut self) -> &mut RuntimeConfigState {
280 &mut self.config
281 }
282
283 pub fn native_audio_provider_active(&self) -> bool {
285 self.native_audio_provider_active
286 }
287
288 pub fn load_boot(&mut self, boot: &CliBoot) -> Result<&[LoadReceipt], CliError> {
290 self.native_audio_provider_active = false;
291 let boot = self.boot_with_default_verb_sources(boot);
292 let config_libs = config_libs_for_boot(&boot, &self.default_verb_config_libs);
293 let codec_name = boot_codec_name(&boot);
294 let codec_symbol = codec_lib_symbol(codec_name);
295 let codec_index = self.boot_codec_source_index(&boot, &codec_symbol);
296 self.config = load_config_sources(&mut self.cx, &pre_site_config(&boot), &config_libs);
297 let preloaded_config_sources =
298 self.load_config_site_sources(&boot, codec_name, &codec_symbol, codec_index)?;
299 self.config = load_config_sources(&mut self.cx, &boot.config, &config_libs);
300 self.load_native_audio_provider(&boot);
301 match codec_index {
302 Some(index) if preloaded_config_sources.contains(&index) => {}
303 Some(index) => {
304 self.load_boot_codec_source(codec_name, &codec_symbol, &boot.loads[index])?;
305 }
306 None => {
307 self.load_boot_codec_source(
308 codec_name,
309 &codec_symbol,
310 &LibSourceSpec::Symbol(codec_symbol.clone()),
311 )?;
312 }
313 }
314 for (index, source) in boot.loads.iter().enumerate() {
315 if Some(index) != codec_index && !preloaded_config_sources.contains(&index) {
316 self.load_source(source)?;
317 }
318 }
319 Ok(&self.receipts)
320 }
321
322 fn load_config_site_sources(
323 &mut self,
324 boot: &CliBoot,
325 codec_name: &str,
326 codec_symbol: &str,
327 codec_index: Option<usize>,
328 ) -> Result<BTreeSet<usize>, CliError> {
329 let mut preloaded = BTreeSet::new();
330 if boot.config.site_sources.is_empty() {
331 return Ok(preloaded);
332 }
333 for (index, source) in boot.loads.iter().enumerate() {
334 let Ok(manifest) = self.inspect_source_manifest(source) else {
335 continue;
336 };
337 if !manifest_exports_requested_site(&manifest, &boot.config.site_sources) {
338 continue;
339 }
340 if Some(index) == codec_index {
341 self.load_boot_codec_source(codec_name, codec_symbol, source)?;
342 } else {
343 self.load_source(source)?;
344 }
345 preloaded.insert(index);
346 }
347 Ok(preloaded)
348 }
349
350 fn load_native_audio_provider(&mut self, boot: &CliBoot) {
351 let Some(source) = boot.native_audio_provider.as_deref() else {
352 return;
353 };
354 match self.load_source_with_role(source, LoadReceiptRole::Library) {
355 Ok(_) => {
356 expect_granted!(
357 self.seat
358 .grant(&mut self.cx, native_audio_provider_capability())
359 );
360 self.native_audio_provider_active = true;
361 }
362 Err(err) => {
363 self.config
364 .push_diagnostic(format!("native audio provider skipped: {err}"));
365 }
368 }
369 }
370
371 fn boot_with_default_verb_sources(&self, boot: &CliBoot) -> CliBoot {
372 if !boot.loads.is_empty() {
373 return boot.clone();
374 }
375 let Some(verb) = boot
376 .payload
377 .args
378 .first()
379 .map(|arg| arg.to_string_lossy().into_owned())
380 else {
381 return boot.clone();
382 };
383 let Some(sources) = self.default_verb_sources.get(&verb) else {
384 return boot.clone();
385 };
386 let mut boot = boot.clone();
387 boot.loads.clone_from(sources);
388 boot
389 }
390
391 fn boot_codec_source_index(&mut self, boot: &CliBoot, codec_symbol: &str) -> Option<usize> {
392 if let Some(index) = explicit_codec_source_index(boot, codec_symbol) {
393 return Some(index);
394 }
395
396 let codec_symbol = symbol_from_text(codec_symbol);
397 for (index, source) in boot.loads.iter().enumerate() {
398 if self
401 .inspect_source_manifest(source)
402 .ok()
403 .is_some_and(|manifest| manifest_exports_codec(&manifest, &codec_symbol))
404 {
405 return Some(index);
406 }
407 }
408 None
409 }
410
411 pub fn load_source(&mut self, source: &LibSourceSpec) -> Result<LoadReceipt, CliError> {
413 self.load_source_with_role(source, LoadReceiptRole::Library)
414 }
415
416 fn inspect_source_manifest(&mut self, source: &LibSourceSpec) -> Result<LibManifest, CliError> {
417 match source {
418 LibSourceSpec::Host(name) => self.hosts.inspect_manifest(name, &self.config),
419 LibSourceSpec::CratesIo(spec) => {
420 let resolved = self.crates_io.resolve(spec)?;
421 let data_source = sim_run_loaders::path_source_spec(resolved.artifact);
422 ensure_loadable_path(&data_source, source)?;
423 self.inspect_data_source_manifest(data_source)
424 }
425 _ => {
426 let data_source = source
427 .to_kernel_data_source()
428 .expect("non-host sources have data forms");
429 ensure_loadable_path(&data_source, source)?;
430 self.inspect_data_source_manifest(data_source)
431 }
432 }
433 }
434
435 fn load_boot_codec_source(
436 &mut self,
437 codec_name: &str,
438 codec_symbol: &str,
439 source: &LibSourceSpec,
440 ) -> Result<LoadReceipt, CliError> {
441 let role = LoadReceiptRole::boot_codec(codec_name, codec_symbol);
442 match self.load_source_with_role(source, role.clone()) {
443 Ok(receipt) => Ok(receipt),
444 Err(_) if self.hosts.contains(codec_symbol) => {
445 self.load_source_with_role(&LibSourceSpec::Host(codec_symbol.to_owned()), role)
446 }
447 Err(err) => Err(no_codec_error(codec_name, err)),
448 }
449 }
450
451 fn load_source_with_role(
452 &mut self,
453 source: &LibSourceSpec,
454 role: LoadReceiptRole,
455 ) -> Result<LoadReceipt, CliError> {
456 if let LibSourceSpec::Host(name) = source {
457 return self.load_host_source(source, name, role);
458 }
459 if let LibSourceSpec::CratesIo(spec) = source {
460 return self.load_crates_io_source(source, spec, role);
461 }
462
463 let data_source = source
464 .to_kernel_data_source()
465 .expect("non-host sources have data forms");
466 ensure_loadable_path(&data_source, source)?;
467 let fallback = match source {
468 LibSourceSpec::Symbol(symbol) => fallback_spec_for_symbol(symbol),
469 _ => None,
470 };
471 match self.load_data_source(source, data_source, role.clone()) {
472 Ok(receipt) => Ok(receipt),
473 Err(err) => match fallback {
474 Some(spec) => {
475 self.load_crates_io_source(&LibSourceSpec::CratesIo(spec.clone()), &spec, role)
476 }
477 None => Err(err),
478 },
479 }
480 }
481
482 fn load_data_source(
483 &mut self,
484 source: &LibSourceSpec,
485 data_source: KernelLibSourceSpec,
486 role: LoadReceiptRole,
487 ) -> Result<LoadReceipt, CliError> {
488 let receipt = self
489 .loaders
490 .load_and_register_with_receipt(&mut self.cx, data_source)
491 .map_err(|err| load_error(source, err))?;
492 let receipt = LoadReceipt {
493 lib_id: receipt.lib_id,
494 role,
495 requested_source: LibSourceSpec::from_kernel_data_source(receipt.requested_source),
496 resolved_source: LibSourceSpec::from_kernel_data_source(receipt.resolved_source),
497 manifest: receipt.manifest,
498 dependencies: receipt.dependencies,
499 exports: receipt.exports,
500 };
501 self.receipts.push(receipt.clone());
502 Ok(receipt)
503 }
504
505 fn load_crates_io_source(
506 &mut self,
507 source: &LibSourceSpec,
508 spec: &CratesIoSpec,
509 role: LoadReceiptRole,
510 ) -> Result<LoadReceipt, CliError> {
511 let resolved = self.crates_io.resolve(spec)?;
512 let data_source = sim_run_loaders::path_source_spec(resolved.artifact);
513 ensure_loadable_path(&data_source, source)?;
514 let receipt = self
515 .loaders
516 .load_and_register_with_receipt(&mut self.cx, data_source)
517 .map_err(|err| load_error(source, err))?;
518 let receipt = LoadReceipt {
519 lib_id: receipt.lib_id,
520 role,
521 requested_source: source.clone(),
522 resolved_source: LibSourceSpec::from_kernel_data_source(receipt.resolved_source),
523 manifest: receipt.manifest,
524 dependencies: receipt.dependencies,
525 exports: receipt.exports,
526 };
527 self.receipts.push(receipt.clone());
528 Ok(receipt)
529 }
530
531 pub fn unload_receipt(&mut self, receipt: &LoadReceipt) -> Result<Vec<LibId>, CliError> {
533 self.cx.unload_lib(receipt.lib_id).map_err(|err| {
534 CliError::new(format!("unload failed for {}: {err}", receipt.manifest.id))
535 })
536 }
537
538 fn load_host_source(
539 &mut self,
540 source: &LibSourceSpec,
541 name: &str,
542 role: LoadReceiptRole,
543 ) -> Result<LoadReceipt, CliError> {
544 let lib = self.hosts.instantiate(name, &self.config)?;
545 let lib_id = self
546 .loaders
547 .load_and_register(&mut self.cx, KernelLibSource::Host(lib))
548 .map_err(|err| load_error(source, err))?;
549 let loaded = self
550 .cx
551 .registry()
552 .libs()
553 .iter()
554 .find(|loaded| loaded.id == lib_id)
555 .cloned()
556 .ok_or_else(|| CliError::new(format!("loaded lib id {lib_id:?} is not registered")))?;
557 let receipt = host_receipt(source.clone(), role, loaded, self.cx.registry().libs());
558 self.receipts.push(receipt.clone());
559 Ok(receipt)
560 }
561}
562
563fn catalog_source_spec(source: CatalogSource) -> LibSourceSpec {
564 match source {
565 CatalogSource::Open { kind, payload } => {
566 LibSourceSpec::from_kernel_data_source(KernelLibSourceSpec::Open { kind, payload })
567 }
568 }
569}
570
571fn config_libs_for_boot(
572 boot: &CliBoot,
573 default_verb_config_libs: &BTreeMap<String, Vec<Symbol>>,
574) -> Vec<Symbol> {
575 let codec_name = boot_codec_name(boot);
576 let mut libs = Vec::new();
577 push_unique_symbol(&mut libs, symbol_from_text(&codec_lib_symbol(codec_name)));
578 for source in &boot.loads {
579 if let Some(symbol) = config_lib_for_source(source) {
580 push_unique_symbol(&mut libs, symbol);
581 }
582 }
583 if let Some(source) = boot.native_audio_provider.as_deref()
584 && let Some(symbol) = config_lib_for_source(source)
585 {
586 push_unique_symbol(&mut libs, symbol);
587 }
588 if let Some(verb) = boot
589 .payload
590 .args
591 .first()
592 .and_then(|arg| arg.as_os_str().to_str().map(str::to_owned))
593 && let Some(symbols) = default_verb_config_libs.get(&verb)
594 {
595 for symbol in symbols {
596 push_unique_symbol(&mut libs, symbol.clone());
597 }
598 }
599 if let Some(request) = boot.config_report.as_ref() {
600 match &request.kind {
601 ConfigReportKind::Effective { lib } => push_unique_symbol(&mut libs, lib.clone()),
602 ConfigReportKind::Status | ConfigReportKind::Sources => {
603 for lib in representative_config_report_libs() {
604 push_unique_symbol(&mut libs, lib);
605 }
606 }
607 }
608 }
609 libs
610}
611
612fn representative_config_report_libs() -> [Symbol; 3] {
613 [
614 Symbol::qualified("sim", "cookbook"),
615 Symbol::qualified("stream", "host"),
616 Symbol::qualified("model", "defaults"),
617 ]
618}
619
620fn config_lib_for_source(source: &LibSourceSpec) -> Option<Symbol> {
621 match source {
622 LibSourceSpec::Symbol(symbol) | LibSourceSpec::Host(symbol) => {
623 Some(symbol_from_text(symbol))
624 }
625 LibSourceSpec::Path(_)
626 | LibSourceSpec::Url(_)
627 | LibSourceSpec::Bytes(_)
628 | LibSourceSpec::Open { .. }
629 | LibSourceSpec::CratesIo(_) => None,
630 }
631}
632
633fn push_unique_symbol(symbols: &mut Vec<Symbol>, symbol: Symbol) {
634 if !symbols.iter().any(|existing| existing == &symbol) {
635 symbols.push(symbol);
636 }
637}
638
639impl Default for LoadSession {
640 fn default() -> Self {
641 Self::new()
642 }
643}
644
645fn ensure_loadable_path(
646 data_source: &KernelLibSourceSpec,
647 source: &LibSourceSpec,
648) -> Result<(), CliError> {
649 if let KernelLibSourceSpec::Open { kind, payload } = data_source
650 && kind == &sim_run_loaders::path_source_kind()
651 && let Ok(path) = sim_run_loaders::path_from_payload(payload)
652 && !path.exists()
653 {
654 return Err(CliError::new(format!(
655 "path source not found for {source}: {}",
656 path.display()
657 )));
658 }
659 Ok(())
660}
661
662fn load_error(source: &LibSourceSpec, err: KernelError) -> CliError {
663 CliError::new(format!("load failed for {source}: {err}"))
664}
665
666fn no_codec_error(codec_name: &str, err: CliError) -> CliError {
667 CliError::new(format!(
668 "no codec '{codec_name}' available; provide one with --load ({err})"
669 ))
670}
671
672fn manifest_exports_codec(manifest: &LibManifest, codec_symbol: &Symbol) -> bool {
673 manifest.exports.iter().any(|export| match export {
674 sim_kernel::Export::Codec { symbol, .. } => symbol == codec_symbol,
675 _ => false,
676 })
677}
678
679fn manifest_exports_requested_site(manifest: &LibManifest, sites: &[Symbol]) -> bool {
680 manifest.exports.iter().any(|export| match export {
681 sim_kernel::Export::Site { symbol, .. } => sites.iter().any(|site| site == symbol),
682 _ => false,
683 })
684}
685
686fn pre_site_config(boot: &CliBoot) -> crate::ConfigLoadOptions {
687 let mut config = boot.config.clone();
688 config.site_sources.clear();
689 config
690}