Skip to main content

greentic_runner_host/
lib.rs

1#![deny(unsafe_code)]
2//! Canonical Greentic host runtime.
3//!
4//! This crate owns tenant bindings, pack ingestion/watchers, ingress adapters,
5//! Wasmtime glue, session/state storage, and the HTTP server used by the
6//! `greentic-runner` CLI. Downstream crates embed it either through
7//! [`RunnerConfig`] + [`run`] (HTTP host) or [`HostBuilder`] (direct API access).
8
9use std::collections::{HashMap, HashSet};
10use std::fs;
11use std::path::PathBuf;
12use std::sync::Arc;
13use std::time::Duration;
14
15use crate::secrets::SecretsBackend;
16use anyhow::{Context, Result, anyhow};
17use greentic_config::ResolvedConfig;
18use greentic_config_types::TelemetryExporterKind;
19use greentic_config_types::{
20    NetworkConfig, PackSourceConfig, PacksConfig, PathsConfig, TelemetryConfig,
21};
22use greentic_telemetry::export::{ExportConfig as TelemetryExportConfig, ExportMode, Sampling};
23use runner_core::env::PackConfig;
24use serde_json::json;
25use tokio::signal;
26
27pub mod boot;
28pub mod cache;
29pub mod component_api;
30pub mod config;
31pub mod engine;
32pub mod extension_provider;
33pub mod fault;
34#[cfg(feature = "greentic-x-provider")]
35pub mod greentic_x_provider;
36pub mod gtbind;
37pub mod http;
38pub mod identify_hint;
39pub mod metrics;
40pub mod operator_metrics;
41pub mod operator_registry;
42pub mod pack;
43pub mod provider;
44pub mod provider_core;
45pub mod provider_core_only;
46pub mod routing;
47pub mod runner;
48pub mod runtime;
49pub mod runtime_refs;
50pub mod runtime_wasmtime;
51pub mod secrets;
52pub(crate) mod secrets_broker;
53pub mod sql;
54pub mod storage;
55pub mod telemetry;
56pub mod telemetry_scan;
57#[cfg(feature = "fault-injection")]
58pub mod testing;
59pub mod trace;
60pub mod validate;
61pub mod verify;
62pub mod wasi;
63pub mod watcher;
64
65mod activity;
66mod host;
67pub mod oauth;
68
69pub use activity::{Activity, ActivityKind, WelcomeFlowHint};
70pub use config::HostConfig;
71pub use gtbind::{PackBinding, TenantBindings};
72pub use host::TelemetryCfg;
73pub use host::{HostBuilder, RunnerHost, TenantHandle};
74pub use wasi::{PreopenSpec, RunnerWasiPolicy};
75
76pub use greentic_types::{EnvId, FlowId, PackId, TenantCtx, TenantId};
77
78pub use http::auth::AdminAuth;
79pub use routing::RoutingConfig;
80use routing::TenantRouting;
81pub use runner::HostServer;
82
83#[cfg(test)]
84pub(crate) mod test_support {
85    use super::*;
86    use crate::config::{OperatorPolicy, SecretsPolicy};
87    use crate::runtime::TenantRuntime;
88    use crate::secrets::default_manager;
89    use crate::storage::{new_session_store, new_state_store, session_host_from, state_host_from};
90    use crate::trace::TraceConfig;
91    use crate::validate::ValidationConfig;
92    use tempfile::TempDir;
93
94    pub(crate) fn fixture_pack_path() -> PathBuf {
95        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
96            .join("../../examples/packs/demo.gtpack")
97            .canonicalize()
98            .expect("fixture pack path")
99    }
100
101    fn minimal_config(workspace: &std::path::Path) -> Result<Arc<HostConfig>> {
102        let bindings_path = workspace.join("bindings.yaml");
103        std::fs::write(
104            &bindings_path,
105            r#"
106tenant: demo
107flow_type_bindings: {}
108rate_limits: {}
109retry: {}
110timers: []
111"#,
112        )?;
113        let mut config =
114            HostConfig::load_from_path(&bindings_path).context("load minimal host bindings")?;
115        config.secrets_policy = SecretsPolicy::allow_all();
116        config.operator_policy = OperatorPolicy::allow_all();
117        config.trace = TraceConfig::from_env();
118        config.validation = ValidationConfig::from_env();
119        Ok(Arc::new(config))
120    }
121
122    pub(crate) async fn build_test_runtime() -> Result<(TempDir, Arc<TenantRuntime>)> {
123        let workspace = TempDir::new().context("temp workspace")?;
124        let config = minimal_config(workspace.path())?;
125        let session_store = new_session_store();
126        let session_host = session_host_from(Arc::clone(&session_store));
127        let state_store = new_state_store();
128        let state_host = state_host_from(Arc::clone(&state_store));
129        let secrets = default_manager()?;
130        let pack_path = fixture_pack_path();
131        let runtime = TenantRuntime::load(
132            &pack_path,
133            config,
134            None,
135            Some(&pack_path),
136            None,
137            Arc::new(RunnerWasiPolicy::new()),
138            session_host,
139            Arc::clone(&session_store),
140            Arc::clone(&state_store),
141            state_host,
142            secrets,
143        )
144        .await?;
145        Ok((workspace, runtime))
146    }
147}
148
149/// User-facing configuration for running the unified host.
150#[derive(Clone)]
151pub struct RunnerConfig {
152    pub tenant_bindings: HashMap<String, TenantBindings>,
153    pub pack: PackConfig,
154    pub port: u16,
155    pub refresh_interval: Duration,
156    pub routing: RoutingConfig,
157    pub admin: AdminAuth,
158    pub telemetry: Option<TelemetryCfg>,
159    pub secrets_backend: SecretsBackend,
160    pub wasi_policy: RunnerWasiPolicy,
161    pub resolved_config: ResolvedConfig,
162    pub trace: trace::TraceConfig,
163    pub validation: validate::ValidationConfig,
164}
165
166impl RunnerConfig {
167    /// Build a [`RunnerConfig`] from a resolved greentic-config and the provided binding files.
168    pub fn from_config(resolved_config: ResolvedConfig, bindings: Vec<PathBuf>) -> Result<Self> {
169        if bindings.is_empty() {
170            anyhow::bail!("at least one gtbind file is required");
171        }
172        let tenant_bindings = gtbind::load_gtbinds(&bindings)?;
173        if tenant_bindings.is_empty() {
174            anyhow::bail!("no gtbind files loaded");
175        }
176        let mut pack = pack_config_from(
177            &resolved_config.config.packs,
178            &resolved_config.config.paths,
179            &resolved_config.config.network,
180        )?;
181        maybe_write_gtbind_index(&tenant_bindings, &resolved_config.config.paths, &mut pack)?;
182        let refresh = parse_refresh_interval(std::env::var("PACK_REFRESH_INTERVAL").ok())?;
183        let port = std::env::var("PORT")
184            .ok()
185            .and_then(|value| value.parse().ok())
186            .unwrap_or(8080);
187        let default_tenant = resolved_config
188            .config
189            .dev
190            .as_ref()
191            .map(|dev| dev.default_tenant.clone())
192            .unwrap_or_else(|| crate::routing::DEFAULT_TENANT.into());
193        let routing = RoutingConfig::from_env_with_default(default_tenant);
194        let paths = &resolved_config.config.paths;
195        ensure_paths_exist(paths)?;
196        let mut wasi_policy = default_wasi_policy(paths);
197        let mut env_allow = HashSet::new();
198        for binding in tenant_bindings.values() {
199            env_allow.extend(binding.env_passthrough.iter().cloned());
200        }
201        for key in env_allow {
202            wasi_policy = wasi_policy.allow_env(key);
203        }
204
205        let admin = AdminAuth::new(resolved_config.config.services.as_ref().and_then(|s| {
206            s.events
207                .as_ref()
208                .and_then(|svc| svc.headers.as_ref())
209                .and_then(|headers| headers.get("x-admin-token").cloned())
210        }));
211        let secrets_backend = SecretsBackend::from_config(&resolved_config.config.secrets)?;
212        Ok(Self {
213            tenant_bindings,
214            pack,
215            port,
216            refresh_interval: refresh,
217            routing,
218            admin,
219            telemetry: telemetry_from(&resolved_config.config.telemetry),
220            secrets_backend,
221            wasi_policy,
222            resolved_config,
223            trace: trace::TraceConfig::from_env(),
224            validation: validate::ValidationConfig::from_env(),
225        })
226    }
227
228    /// Override the HTTP port used by the host server.
229    pub fn with_port(mut self, port: u16) -> Self {
230        self.port = port;
231        self
232    }
233
234    pub fn with_wasi_policy(mut self, policy: RunnerWasiPolicy) -> Self {
235        self.wasi_policy = policy;
236        self
237    }
238}
239
240fn maybe_write_gtbind_index(
241    tenant_bindings: &HashMap<String, TenantBindings>,
242    paths: &PathsConfig,
243    pack: &mut PackConfig,
244) -> Result<()> {
245    let mut uses_locators = false;
246    for binding in tenant_bindings.values() {
247        for pack_binding in &binding.packs {
248            if pack_binding.pack_locator.is_some() {
249                uses_locators = true;
250            }
251        }
252    }
253    if !uses_locators {
254        return Ok(());
255    }
256
257    let mut entries = serde_json::Map::new();
258    for binding in tenant_bindings.values() {
259        let mut packs = Vec::new();
260        for pack_binding in &binding.packs {
261            let locator = pack_binding.pack_locator.as_ref().ok_or_else(|| {
262                anyhow::anyhow!(
263                    "gtbind {} missing pack_locator for pack {}",
264                    binding.tenant,
265                    pack_binding.pack_id
266                )
267            })?;
268            let (name, version_or_digest) =
269                pack_binding.pack_ref.split_once('@').ok_or_else(|| {
270                    anyhow::anyhow!(
271                        "gtbind {} invalid pack_ref {} (expected name@version)",
272                        binding.tenant,
273                        pack_binding.pack_ref
274                    )
275                })?;
276            if name != pack_binding.pack_id {
277                anyhow::bail!(
278                    "gtbind {} pack_ref {} does not match pack_id {}",
279                    binding.tenant,
280                    pack_binding.pack_ref,
281                    pack_binding.pack_id
282                );
283            }
284            let mut entry = serde_json::Map::new();
285            entry.insert("name".to_string(), json!(name));
286            if version_or_digest.contains(':') {
287                entry.insert("digest".to_string(), json!(version_or_digest));
288            } else {
289                entry.insert("version".to_string(), json!(version_or_digest));
290            }
291            entry.insert("locator".to_string(), json!(locator));
292            packs.push(serde_json::Value::Object(entry));
293        }
294        let main_pack = packs
295            .first()
296            .cloned()
297            .ok_or_else(|| anyhow::anyhow!("gtbind {} has no packs", binding.tenant))?;
298        let overlays = packs.into_iter().skip(1).collect::<Vec<_>>();
299        entries.insert(
300            binding.tenant.clone(),
301            json!({
302                "main_pack": main_pack,
303                "overlays": overlays,
304            }),
305        );
306    }
307
308    let index_path = paths.greentic_root.join("packs").join("gtbind.index.json");
309    if let Some(parent) = index_path.parent() {
310        fs::create_dir_all(parent)
311            .with_context(|| format!("failed to create {}", parent.display()))?;
312    }
313    let serialized = serde_json::to_vec_pretty(&serde_json::Value::Object(entries))?;
314    fs::write(&index_path, serialized)
315        .with_context(|| format!("failed to write {}", index_path.display()))?;
316    pack.index_location = runner_core::env::IndexLocation::File(index_path);
317    Ok(())
318}
319
320fn parse_refresh_interval(value: Option<String>) -> Result<Duration> {
321    let raw = value.unwrap_or_else(|| "30s".into());
322    humantime::parse_duration(&raw).map_err(|err| anyhow!("invalid PACK_REFRESH_INTERVAL: {err}"))
323}
324
325fn default_wasi_policy(paths: &PathsConfig) -> RunnerWasiPolicy {
326    let mut policy = RunnerWasiPolicy::default()
327        .with_env("GREENTIC_ROOT", paths.greentic_root.display().to_string())
328        .with_env("GREENTIC_STATE_DIR", paths.state_dir.display().to_string())
329        .with_env("GREENTIC_CACHE_DIR", paths.cache_dir.display().to_string())
330        .with_env("GREENTIC_LOGS_DIR", paths.logs_dir.display().to_string());
331    policy = policy
332        .with_preopen(PreopenSpec::new(&paths.state_dir, "/state"))
333        .with_preopen(PreopenSpec::new(&paths.cache_dir, "/cache"))
334        .with_preopen(PreopenSpec::new(&paths.logs_dir, "/logs"));
335    policy
336}
337
338fn ensure_paths_exist(paths: &PathsConfig) -> Result<()> {
339    for dir in [
340        &paths.greentic_root,
341        &paths.state_dir,
342        &paths.cache_dir,
343        &paths.logs_dir,
344    ] {
345        fs::create_dir_all(dir)
346            .with_context(|| format!("failed to ensure directory {}", dir.display()))?;
347    }
348    Ok(())
349}
350
351fn pack_config_from(
352    packs: &Option<PacksConfig>,
353    paths: &PathsConfig,
354    network: &NetworkConfig,
355) -> Result<PackConfig> {
356    if let Some(cfg) = packs {
357        let cache_dir = cfg.cache_dir.clone();
358        let index_location = match &cfg.source {
359            PackSourceConfig::LocalIndex { path } => {
360                runner_core::env::IndexLocation::File(path.clone())
361            }
362            PackSourceConfig::HttpIndex { url } => {
363                runner_core::env::IndexLocation::from_value(url)?
364            }
365            PackSourceConfig::OciRegistry { reference } => {
366                runner_core::env::IndexLocation::from_value(reference)?
367            }
368        };
369        let public_key = cfg
370            .trust
371            .as_ref()
372            .and_then(|trust| trust.public_keys.first().cloned());
373        return Ok(PackConfig {
374            source: runner_core::env::PackSource::Fs,
375            index_location,
376            cache_dir,
377            public_key,
378            network: Some(network.clone()),
379        });
380    }
381    let mut cfg = PackConfig::default_for_paths(paths)?;
382    cfg.network = Some(network.clone());
383    Ok(cfg)
384}
385
386fn telemetry_from(cfg: &TelemetryConfig) -> Option<TelemetryCfg> {
387    if !cfg.enabled || matches!(cfg.exporter, TelemetryExporterKind::None) {
388        return None;
389    }
390    let mut export = TelemetryExportConfig::json_default();
391    export.mode = match cfg.exporter {
392        TelemetryExporterKind::Otlp => ExportMode::OtlpGrpc,
393        TelemetryExporterKind::Stdout => ExportMode::JsonStdout,
394        TelemetryExporterKind::Gcp => ExportMode::GcpCloudTrace,
395        TelemetryExporterKind::Azure => ExportMode::AzureAppInsights,
396        TelemetryExporterKind::Aws => ExportMode::AwsXRay,
397        TelemetryExporterKind::None => return None,
398    };
399    export.endpoint = cfg.endpoint.clone();
400    export.sampling = Sampling::TraceIdRatio(cfg.sampling as f64);
401    Some(TelemetryCfg {
402        config: greentic_telemetry::TelemetryConfig {
403            service_name: "greentic-runner".into(),
404        },
405        export,
406    })
407}
408
409/// Spawn the in-process agentic-worker NATS service once, when opted in.
410///
411/// Gated on `GREENTIC_AGENTIC_SERVE_INPROC` (truthy) AND `GREENTIC_EVENTS_NATS_URL`
412/// (set) via [`runner::agent_node::should_serve_agentic_inproc`]. Loads
413/// process-level base agent configs from `GREENTIC_AGENT_MANIFESTS_DIR`
414/// (`<agent_id>.json` full [`greentic_aw_runtime::AgentConfig`] files) — the only
415/// process-level agent source, since pack-embedded and per-tenant `HostConfig`
416/// agents only exist inside `TenantRuntime::from_packs`.
417///
418/// Skips with a warning (continuing normal startup) when no agents are
419/// configured; [`serve_agentic`] itself further degrades gracefully when the
420/// runtime cannot be built (no `GREENTIC_AW_REDIS_URL` / LLM key). The spawned
421/// task owns the subscriber for the lifetime of the process.
422#[cfg(feature = "agentic-worker")]
423fn maybe_spawn_inproc_agentic_serve() {
424    use crate::runner::agent_node::{
425        load_process_agent_configs, serve_agentic, should_serve_agentic_inproc,
426    };
427
428    if !should_serve_agentic_inproc(|key| std::env::var(key).ok()) {
429        return;
430    }
431
432    // Both env vars are guaranteed present/non-empty by the gate above.
433    let nats_url = std::env::var("GREENTIC_EVENTS_NATS_URL").unwrap_or_default();
434    let agents = load_process_agent_configs();
435    if agents.is_empty() {
436        tracing::warn!(
437            "GREENTIC_AGENTIC_SERVE_INPROC set but no process-level agents found in \
438             GREENTIC_AGENT_MANIFESTS_DIR; in-process agentic serve skipped"
439        );
440        return;
441    }
442
443    let agent_count = agents.len();
444    tracing::info!(
445        agent_count,
446        nats_url = %nats_url,
447        "starting in-process agentic serve (GREENTIC_AGENTIC_SERVE_INPROC)"
448    );
449    tokio::spawn(async move {
450        if let Err(error) = serve_agentic(&nats_url, agents).await {
451            tracing::warn!(error = %error, "in-process agentic serve stopped with error");
452        }
453    });
454}
455
456/// Run the unified Greentic runner host until shutdown.
457pub async fn run(cfg: RunnerConfig) -> Result<()> {
458    let RunnerConfig {
459        tenant_bindings,
460        pack,
461        port,
462        refresh_interval,
463        routing,
464        admin,
465        telemetry,
466        secrets_backend,
467        wasi_policy,
468        resolved_config: _resolved_config,
469        trace,
470        validation,
471    } = cfg;
472
473    let mut builder = HostBuilder::new();
474    for bindings in tenant_bindings.into_values() {
475        let mut host_config = HostConfig::from_gtbind(bindings);
476        host_config.trace = trace.clone();
477        host_config.validation = validation.clone();
478        builder = builder.with_config(host_config);
479    }
480    if let Some(telemetry) = telemetry.clone() {
481        builder = builder.with_telemetry(telemetry);
482    }
483    builder = builder
484        .with_wasi_policy(wasi_policy.clone())
485        .with_secrets_manager(
486            secrets_backend
487                .build_manager()
488                .context("failed to initialise secrets backend")?,
489        );
490
491    let host = Arc::new(builder.build()?);
492    host.start().await?;
493
494    // Opt-in, once-per-process co-host of the agentic-worker NATS service.
495    // Default OFF: distributed deploys run a standalone `aw-serve` so the
496    // service scales independently. When enabled, this spawns a SINGLE
497    // subscriber for the whole process (NOT per-tenant — multiple subscribers
498    // on `greentic.agentic.request.v1` would each handle every request).
499    #[cfg(feature = "agentic-worker")]
500    maybe_spawn_inproc_agentic_serve();
501
502    let (watcher, reload_handle) =
503        watcher::start_pack_watcher(Arc::clone(&host), pack.clone(), refresh_interval).await?;
504
505    let routing = TenantRouting::new(routing.clone());
506    let server = HostServer::new(
507        port,
508        host.active_packs(),
509        routing,
510        host.health_state(),
511        Some(reload_handle),
512        admin.clone(),
513        Arc::clone(&host),
514    )?;
515
516    tokio::select! {
517        result = server.serve() => {
518            result?;
519        }
520        _ = signal::ctrl_c() => {
521            tracing::info!("received shutdown signal");
522        }
523    }
524
525    drop(watcher);
526    host.stop().await?;
527    Ok(())
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use crate::gtbind::{PackBinding, TenantBindings};
534    use greentic_config_types::PackTrustConfig;
535    use tempfile::TempDir;
536
537    fn paths(temp: &TempDir) -> PathsConfig {
538        PathsConfig {
539            greentic_root: temp.path().join("greentic"),
540            state_dir: temp.path().join("state"),
541            cache_dir: temp.path().join("cache"),
542            logs_dir: temp.path().join("logs"),
543        }
544    }
545
546    #[test]
547    fn parse_refresh_interval_uses_default_and_rejects_invalid_values() {
548        assert_eq!(
549            parse_refresh_interval(None).expect("default interval"),
550            Duration::from_secs(30)
551        );
552        assert!(parse_refresh_interval(Some("not-a-duration".into())).is_err());
553    }
554
555    #[test]
556    fn ensure_paths_exist_creates_expected_directories() {
557        let temp = TempDir::new().expect("tempdir");
558        let paths = paths(&temp);
559        ensure_paths_exist(&paths).expect("create directories");
560
561        assert!(paths.greentic_root.is_dir());
562        assert!(paths.state_dir.is_dir());
563        assert!(paths.cache_dir.is_dir());
564        assert!(paths.logs_dir.is_dir());
565    }
566
567    #[test]
568    fn maybe_write_gtbind_index_writes_locator_index() {
569        let temp = TempDir::new().expect("tempdir");
570        let paths = paths(&temp);
571        fs::create_dir_all(&paths.greentic_root).expect("greentic root");
572        let mut pack = PackConfig::default_for_paths(&paths).expect("pack config");
573        let tenant_bindings = HashMap::from([(
574            "demo".to_string(),
575            TenantBindings {
576                tenant: "demo".into(),
577                packs: vec![
578                    PackBinding {
579                        pack_id: "pack.main".into(),
580                        pack_ref: "pack.main@1.0.0".into(),
581                        pack_locator: Some("fs:///packs/main.gtpack".into()),
582                        flows: vec!["main".into()],
583                    },
584                    PackBinding {
585                        pack_id: "pack.overlay".into(),
586                        pack_ref: "pack.overlay@sha256:abcd".into(),
587                        pack_locator: Some("fs:///packs/overlay.gtpack".into()),
588                        flows: vec![],
589                    },
590                ],
591                env_passthrough: vec![],
592            },
593        )]);
594
595        maybe_write_gtbind_index(&tenant_bindings, &paths, &mut pack).expect("write gtbind index");
596
597        let index_path = paths.greentic_root.join("packs").join("gtbind.index.json");
598        let json: serde_json::Value =
599            serde_json::from_slice(&fs::read(&index_path).expect("read index")).expect("json");
600        assert_eq!(
601            json["demo"]["main_pack"]["locator"],
602            "fs:///packs/main.gtpack"
603        );
604        assert_eq!(json["demo"]["overlays"][0]["digest"], "sha256:abcd");
605        match pack.index_location {
606            runner_core::env::IndexLocation::File(path) => assert_eq!(path, index_path),
607            runner_core::env::IndexLocation::Remote(_) => panic!("expected generated file index"),
608        }
609    }
610
611    #[test]
612    fn pack_config_from_prefers_configured_pack_source() {
613        let temp = TempDir::new().expect("tempdir");
614        let paths = paths(&temp);
615        let packs = Some(PacksConfig {
616            source: PackSourceConfig::HttpIndex {
617                url: "https://example.com/index.json".into(),
618            },
619            cache_dir: temp.path().join("packs-cache"),
620            index_cache_ttl_secs: None,
621            trust: Some(PackTrustConfig {
622                public_keys: vec!["ed25519:test".into()],
623                require_signatures: true,
624            }),
625        });
626        let config = pack_config_from(&packs, &paths, &NetworkConfig::default())
627            .expect("pack config from packs");
628
629        match config.index_location {
630            runner_core::env::IndexLocation::Remote(url) => {
631                assert_eq!(url.as_str(), "https://example.com/index.json");
632            }
633            runner_core::env::IndexLocation::File(_) => panic!("expected remote index"),
634        }
635        assert_eq!(config.public_key.as_deref(), Some("ed25519:test"));
636        assert!(config.network.is_some());
637    }
638
639    #[test]
640    fn default_wasi_policy_sets_expected_env_and_preopens() {
641        let temp = TempDir::new().expect("tempdir");
642        let paths = paths(&temp);
643        let policy = default_wasi_policy(&paths);
644
645        assert_eq!(
646            policy.env_set.get("GREENTIC_ROOT"),
647            Some(&paths.greentic_root.display().to_string())
648        );
649        assert_eq!(policy.preopens.len(), 3);
650        assert_eq!(policy.preopens[0].guest_path, "/state");
651        assert_eq!(policy.preopens[1].guest_path, "/cache");
652        assert_eq!(policy.preopens[2].guest_path, "/logs");
653    }
654
655    #[test]
656    fn telemetry_from_is_disabled_without_exporter() {
657        assert!(telemetry_from(&TelemetryConfig::default()).is_none());
658    }
659}