1mod initial_kv_setter;
2mod launch_metadata;
3mod max_instance_memory;
4mod sqlite_statements;
5mod stdio;
6mod summary;
7mod variable;
8
9use std::path::PathBuf;
10use std::{future::Future, sync::Arc};
11
12use anyhow::{Context, Result};
13#[cfg(feature = "experimental-wasm-features")]
14use clap::ValueEnum;
15use clap::{Args, IntoApp, Parser};
16use spin_app::App;
17use spin_common::sloth;
18use spin_common::ui::quoted_path;
19use spin_common::url::parse_file_url;
20use spin_factors::RuntimeFactors;
21use spin_factors_executor::{ComponentLoader, FactorsExecutor};
22
23use crate::{loader::ComponentLoader as ComponentLoaderImpl, Trigger, TriggerApp};
24pub use initial_kv_setter::InitialKvSetterHook;
25pub use launch_metadata::LaunchMetadata;
26pub use max_instance_memory::MaxInstanceMemoryHook;
27pub use sqlite_statements::SqlStatementExecutorHook;
28use stdio::FollowComponents;
29pub use stdio::StdioLoggingExecutorHooks;
30pub use summary::{KeyValueDefaultStoreSummaryHook, SqliteDefaultStoreSummaryHook};
31pub use variable::VariablesValidatorHook;
32
33pub const APP_LOG_DIR: &str = "APP_LOG_DIR";
34pub const SPIN_TRUNCATE_LOGS: &str = "SPIN_TRUNCATE_LOGS";
35pub const DISABLE_WASMTIME_CACHE: &str = "DISABLE_WASMTIME_CACHE";
36pub const FOLLOW_LOG_OPT: &str = "FOLLOW_ID";
37pub const WASMTIME_CACHE_FILE: &str = "WASMTIME_CACHE_FILE";
38pub const RUNTIME_CONFIG_FILE: &str = "RUNTIME_CONFIG_FILE";
39
40pub const SPIN_LOCKED_URL: &str = "SPIN_LOCKED_URL";
42pub const SPIN_LOCAL_APP_DIR: &str = "SPIN_LOCAL_APP_DIR";
43pub const SPIN_WORKING_DIR: &str = "SPIN_WORKING_DIR";
44
45#[derive(Parser, Debug)]
47#[clap(
48 override_usage = "spin [COMMAND] [OPTIONS]",
49 next_help_heading = help_heading::<T, B::Factors>()
50)]
51pub struct FactorsTriggerCommand<T: Trigger<B::Factors>, B: RuntimeFactorsBuilder> {
52 #[clap(
55 name = APP_LOG_DIR,
56 short = 'L',
57 long = "log-dir",
58 env = "SPIN_LOG_DIR",
59 )]
60 pub log: Option<PathBuf>,
61
62 #[clap(
64 name = SPIN_TRUNCATE_LOGS,
65 long = "truncate-logs",
66 )]
67 pub truncate_logs: bool,
68
69 #[clap(
71 name = DISABLE_WASMTIME_CACHE,
72 long = "disable-cache",
73 env = DISABLE_WASMTIME_CACHE,
74 conflicts_with = WASMTIME_CACHE_FILE,
75 takes_value = false,
76 )]
77 pub disable_cache: bool,
78
79 #[clap(
81 name = WASMTIME_CACHE_FILE,
82 long = "cache",
83 env = WASMTIME_CACHE_FILE,
84 conflicts_with = DISABLE_WASMTIME_CACHE,
85 )]
86 pub cache: Option<PathBuf>,
87
88 #[clap(long = "disable-pooling")]
90 pub disable_pooling: bool,
91
92 #[clap(long = "debug-info", takes_value = false)]
95 pub debug_info: bool,
96
97 #[clap(
99 name = FOLLOW_LOG_OPT,
100 long = "follow",
101 )]
102 pub follow_components: Vec<String>,
103
104 #[clap(
106 long = "quiet",
107 short = 'q',
108 aliases = &["sh", "shush"],
109 conflicts_with = FOLLOW_LOG_OPT,
110 )]
111 pub silence_component_logs: bool,
112
113 #[clap(
115 name = RUNTIME_CONFIG_FILE,
116 long = "runtime-config-file",
117 env = RUNTIME_CONFIG_FILE,
118 )]
119 pub runtime_config_file: Option<PathBuf>,
120
121 #[cfg(feature = "experimental-wasm-features")]
122 #[clap(long, value_enum)]
123 pub experimental_wasm_feature: Vec<ExperimentalWasmFeature>,
124
125 #[clap(long)]
132 pub state_dir: Option<String>,
133
134 #[clap(flatten)]
135 pub trigger_args: T::CliArgs,
136
137 #[clap(flatten)]
138 pub builder_args: B::CliArgs,
139
140 #[clap(long = "help-args-only", hide = true)]
141 pub help_args_only: bool,
142
143 #[clap(long = "launch-metadata-only", hide = true)]
144 pub launch_metadata_only: bool,
145}
146
147#[cfg(feature = "experimental-wasm-features")]
148#[derive(Clone, Debug, ValueEnum)]
149pub enum ExperimentalWasmFeature {
150 Gc,
151 ReferenceTypes,
152 Exceptions,
153 FunctionReferences,
154}
155
156#[derive(Debug, Default)]
158pub struct FactorsConfig {
159 pub working_dir: PathBuf,
161 pub runtime_config_file: Option<PathBuf>,
163 pub state_dir: UserProvidedPath,
165 pub local_app_dir: Option<String>,
167 pub follow_components: FollowComponents,
169 pub log_dir: UserProvidedPath,
171 pub truncate_logs: bool,
173}
174
175#[derive(Args)]
178pub struct NoCliArgs;
179
180impl<T: Trigger<B::Factors>, B: RuntimeFactorsBuilder> FactorsTriggerCommand<T, B> {
181 pub async fn run(self) -> Result<()> {
183 if self.help_args_only {
185 Self::command()
186 .disable_help_flag(true)
187 .help_template("{all-args}")
188 .print_long_help()?;
189 return Ok(());
190 }
191
192 if self.launch_metadata_only {
194 let lm = LaunchMetadata::infer::<T, B>();
195 let json = serde_json::to_string_pretty(&lm)?;
196 eprintln!("{json}");
197 return Ok(());
198 }
199
200 let working_dir = std::env::var(SPIN_WORKING_DIR).context(SPIN_WORKING_DIR)?;
202 let locked_url = std::env::var(SPIN_LOCKED_URL).context(SPIN_LOCKED_URL)?;
203 let local_app_dir = std::env::var(SPIN_LOCAL_APP_DIR).ok();
204
205 let follow_components = self.follow_components();
206
207 let app = {
209 let path = parse_file_url(&locked_url)?;
210 let contents = std::fs::read(&path)
211 .with_context(|| format!("failed to read manifest at {}", quoted_path(&path)))?;
212 let locked =
213 serde_json::from_slice(&contents).context("failed to parse app lock file JSON")?;
214 App::new(locked_url, locked)
215 };
216
217 if let Err(unmet) = app.ensure_needs_only(T::TYPE, &T::supported_host_requirements()) {
219 anyhow::bail!("This application requires the following features that are not available in this version of the '{}' trigger: {unmet}", T::TYPE);
220 }
221
222 let trigger = T::new(self.trigger_args, &app)?;
223 let mut builder: TriggerAppBuilder<T, B> = TriggerAppBuilder::new(trigger);
224 let config = builder.engine_config();
225
226 if !self.disable_cache {
228 config.enable_cache(&self.cache)?;
229 }
230
231 if self.disable_pooling {
232 config.disable_pooling();
233 }
234
235 if self.debug_info {
236 config.enable_debug_info();
237 }
238
239 #[cfg(feature = "experimental-wasm-features")]
240 {
241 let wasmtime_config = config.wasmtime_config();
242 for wasm_feature in self.experimental_wasm_feature {
243 match wasm_feature {
244 ExperimentalWasmFeature::Gc => wasmtime_config.wasm_gc(true),
245 ExperimentalWasmFeature::ReferenceTypes => {
246 wasmtime_config.wasm_reference_types(true)
247 }
248 ExperimentalWasmFeature::Exceptions => wasmtime_config.wasm_exceptions(true),
249 ExperimentalWasmFeature::FunctionReferences => {
250 wasmtime_config.wasm_function_references(true)
251 }
252 };
253 }
254 }
255
256 let state_dir = match &self.state_dir {
257 Some(s) if s.is_empty() => UserProvidedPath::Unset,
259 Some(s) => UserProvidedPath::Provided(PathBuf::from(s)),
260 None => UserProvidedPath::Default,
261 };
262 let log_dir = match &self.log {
263 Some(p) if p.as_os_str().is_empty() => UserProvidedPath::Unset,
265 Some(p) => UserProvidedPath::Provided(p.clone()),
266 None => UserProvidedPath::Default,
267 };
268 let common_options = FactorsConfig {
269 working_dir: PathBuf::from(working_dir),
270 runtime_config_file: self.runtime_config_file.clone(),
271 state_dir,
272 local_app_dir: local_app_dir.clone(),
273 follow_components,
274 log_dir,
275 truncate_logs: self.truncate_logs,
276 };
277
278 let run_fut = builder
279 .run(
280 app,
281 common_options,
282 self.builder_args,
283 &ComponentLoaderImpl::new(),
284 )
285 .await?;
286
287 let (abortable, abort_handle) = futures::future::abortable(run_fut);
288 ctrlc::set_handler(move || abort_handle.abort())?;
289 match abortable.await {
290 Ok(Ok(())) => {
291 tracing::info!("Trigger executor shut down: exiting");
292 Ok(())
293 }
294 Ok(Err(err)) => {
295 tracing::error!("Trigger executor failed");
296 Err(err)
297 }
298 Err(_aborted) => {
299 tracing::info!("User requested shutdown: exiting");
300 Ok(())
301 }
302 }
303 }
304
305 fn follow_components(&self) -> FollowComponents {
306 if self.silence_component_logs {
307 FollowComponents::None
308 } else if self.follow_components.is_empty() {
309 FollowComponents::All
310 } else {
311 let followed = self.follow_components.clone().into_iter().collect();
312 FollowComponents::Named(followed)
313 }
314 }
315}
316
317const SLOTH_WARNING_DELAY_MILLIS: u64 = 1250;
318
319fn warn_if_wasm_build_slothful() -> sloth::SlothGuard {
320 #[cfg(debug_assertions)]
321 let message = "\
322 This is a debug build - preparing Wasm modules might take a few seconds\n\
323 If you're experiencing long startup times please switch to the release build";
324
325 #[cfg(not(debug_assertions))]
326 let message = "Preparing Wasm modules is taking a few seconds...";
327
328 sloth::warn_if_slothful(SLOTH_WARNING_DELAY_MILLIS, format!("{message}\n"))
329}
330
331fn help_heading<T: Trigger<F>, F: RuntimeFactors>() -> Option<&'static str> {
332 if T::TYPE == <help::HelpArgsOnlyTrigger as Trigger<F>>::TYPE {
333 Some("TRIGGER OPTIONS")
334 } else {
335 let heading = format!("{} TRIGGER OPTIONS", T::TYPE.to_uppercase());
336 let as_str = Box::new(heading).leak();
337 Some(as_str)
338 }
339}
340
341pub struct TriggerAppBuilder<T, B> {
343 engine_config: spin_core::Config,
344 pub trigger: T,
345 _factors_builder: std::marker::PhantomData<B>,
346}
347
348impl<T: Trigger<B::Factors>, B: RuntimeFactorsBuilder> TriggerAppBuilder<T, B> {
349 pub fn new(trigger: T) -> Self {
350 Self {
351 engine_config: spin_core::Config::default(),
352 trigger,
353 _factors_builder: Default::default(),
354 }
355 }
356
357 pub fn engine_config(&mut self) -> &mut spin_core::Config {
358 &mut self.engine_config
359 }
360
361 pub async fn build(
363 &mut self,
364 app: App,
365 common_options: FactorsConfig,
366 options: B::CliArgs,
367 loader: &impl ComponentLoader<B::Factors, T::InstanceState>,
368 ) -> anyhow::Result<TriggerApp<T, B::Factors>> {
369 let mut core_engine_builder = {
370 self.trigger.update_core_config(&mut self.engine_config)?;
371
372 spin_core::Engine::builder(&self.engine_config)?
373 };
374 self.trigger.add_to_linker(core_engine_builder.linker())?;
375
376 let (factors, runtime_config) = B::build(&common_options, &options)?;
377
378 let mut executor = FactorsExecutor::new(core_engine_builder, factors)?;
379 B::configure_app(&mut executor, &runtime_config, &common_options, &options)?;
380 let executor = Arc::new(executor);
381
382 let configured_app = {
383 let _sloth_guard = warn_if_wasm_build_slothful();
384 executor
385 .load_app(app, runtime_config.into(), loader, Some(T::TYPE))
386 .await?
387 };
388
389 Ok(configured_app)
390 }
391
392 pub async fn run(
394 mut self,
395 app: App,
396 common_options: FactorsConfig,
397 options: B::CliArgs,
398 loader: &impl ComponentLoader<B::Factors, T::InstanceState>,
399 ) -> anyhow::Result<impl Future<Output = anyhow::Result<()>>> {
400 let configured_app = self.build(app, common_options, options, loader).await?;
401 Ok(self.trigger.run(configured_app))
402 }
403}
404
405pub trait RuntimeFactorsBuilder {
407 type Factors: RuntimeFactors;
409 type CliArgs: clap::Args;
411 type RuntimeConfig: Into<<Self::Factors as RuntimeFactors>::RuntimeConfig>;
413
414 fn build(
416 config: &FactorsConfig,
417 args: &Self::CliArgs,
418 ) -> anyhow::Result<(Self::Factors, Self::RuntimeConfig)>;
419
420 fn configure_app<U: Send + 'static>(
422 executor: &mut FactorsExecutor<Self::Factors, U>,
423 runtime_config: &Self::RuntimeConfig,
424 config: &FactorsConfig,
425 args: &Self::CliArgs,
426 ) -> anyhow::Result<()> {
427 let _ = (executor, runtime_config, config, args);
428 Ok(())
429 }
430}
431
432pub mod help {
433 use super::*;
434
435 pub struct HelpArgsOnlyTrigger;
438
439 impl<F: RuntimeFactors> Trigger<F> for HelpArgsOnlyTrigger {
440 const TYPE: &'static str = "help-args-only";
441 type CliArgs = NoCliArgs;
442 type InstanceState = ();
443
444 fn new(_cli_args: Self::CliArgs, _app: &App) -> anyhow::Result<Self> {
445 Ok(Self)
446 }
447
448 async fn run(self, _configured_app: TriggerApp<Self, F>) -> anyhow::Result<()> {
449 Ok(())
450 }
451 }
452}
453
454#[derive(Clone, Debug, Default)]
456pub enum UserProvidedPath {
457 Provided(PathBuf),
459 #[default]
461 Default,
462 Unset,
464}