1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#![allow(missing_docs)] // delete when we move away from the `property` crate.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
pub(super) mod triggers;

use asset_container::{AssetManager, Assets};
use tracing::trace;
use wick_asset_reference::{AssetReference, FetchOptions};
use wick_interface_types::TypeDefinition;
use wick_packet::{Entity, RuntimeConfig};

pub use self::triggers::*;
use super::common::component_definition::ComponentDefinition;
use super::common::package_definition::PackageConfig;
use super::components::TypesComponent;
use super::import_cache::{setup_cache, ImportCache};
use super::{Binding, ImportDefinition};
use crate::config::common::resources::*;
use crate::config::template_config::Renderable;
use crate::error::{ManifestError, ReferenceError};
use crate::lockdown::{validate_resource, FailureKind, Lockdown, LockdownError};
use crate::utils::{make_resolver, resolve, RwOption};
use crate::{config, ExpandImports, Resolver, Result};

#[derive(
  Debug,
  Clone,
  Default,
  derive_builder::Builder,
  derive_asset_container::AssetManager,
  property::Property,
  serde::Serialize,
)]
#[property(get(public), set(public), mut(public, suffix = "_mut"))]
#[asset(asset(AssetReference))]
#[builder(
  setter(into),
  build_fn(name = "build_internal", private, error = "crate::error::BuilderError")
)]
#[must_use]
/// A Wick application configuration.
///
/// An application configuration defines a wick application, its trigger, imported component, etc and can be executed
/// via `wick run`.
pub struct AppConfiguration {
  #[asset(skip)]
  /// The name of the application.
  pub(crate) name: String,

  #[asset(skip)]
  #[builder(setter(strip_option), default)]
  #[property(skip)]
  /// The source (i.e. url or file on disk) of the configuration.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) source: Option<PathBuf>,

  #[builder(setter(strip_option), default)]
  /// The metadata for the application.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) metadata: Option<config::Metadata>,

  #[builder(setter(strip_option), default)]
  /// The package configuration for this application.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) package: Option<PackageConfig>,

  #[builder(default)]
  /// The components that make up the application.
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub(crate) import: Vec<Binding<ImportDefinition>>,

  #[builder(default)]
  /// Any resources this application defines.
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub(crate) resources: Vec<Binding<ResourceDefinition>>,

  #[builder(default)]
  /// The triggers that initialize upon a `run` and make up the application.
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub(crate) triggers: Vec<TriggerDefinition>,

  #[asset(skip)]
  #[doc(hidden)]
  #[builder(default)]
  #[property(skip)]
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) root_config: Option<RuntimeConfig>,

  #[asset(skip)]
  #[builder(default)]
  #[property(skip)]
  /// The environment this configuration has access to.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) env: Option<HashMap<String, String>>,

  #[asset(skip)]
  #[builder(setter(skip))]
  #[property(skip)]
  #[doc(hidden)]
  #[serde(skip)]
  pub(crate) type_cache: ImportCache,

  #[asset(skip)]
  #[builder(default)]
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) options: Option<FetchOptions>,

  #[asset(skip)]
  #[builder(default)]
  #[property(skip)]
  #[doc(hidden)]
  #[serde(skip)]
  pub(crate) cached_types: RwOption<Vec<TypeDefinition>>,
}

impl AppConfiguration {
  /// Fetch/cache anything critical to the first use of this configuration.
  pub(crate) async fn setup_cache(&self, options: FetchOptions) -> Result<()> {
    setup_cache(
      &self.type_cache,
      self.import.iter(),
      &self.cached_types,
      vec![],
      options,
    )
    .await
  }

  /// Get the package files
  pub fn package_files(&self) -> Assets<AssetReference> {
    self.package.assets()
  }

  /// Resolve an imported type by name.
  #[must_use]
  pub fn resolve_type(&self, name: &str) -> Option<TypeDefinition> {
    self
      .cached_types
      .read()
      .as_ref()
      .and_then(|types| types.iter().find(|t| t.name() == name).cloned())
  }

  /// Get the configuration item a binding points to.

  pub fn resolve_binding(&self, name: &str) -> Result<OwnedConfigurationItem> {
    resolve(name, &self.import, &self.resources)
  }

  /// Returns a function that resolves a binding to a configuration item.
  #[must_use]
  pub fn resolver(&self) -> Box<Resolver> {
    make_resolver(self.import.clone(), self.resources.clone())
  }

  /// Return the underlying version of the source manifest.
  #[must_use]
  pub fn source(&self) -> Option<&Path> {
    self.source.as_deref()
  }

  /// Set the source location of the configuration.
  pub fn set_source(&mut self, source: &Path) {
    let source = source.to_path_buf();
    self.source = Some(source);
  }

  pub(super) fn update_baseurls(&self) {
    #[allow(clippy::expect_used)]
    let mut source = self.source.clone().expect("No source set for this configuration");
    // Source is (should be) a file, so pop the filename before setting the baseurl.
    if !source.is_dir() {
      source.pop();
    }
    self.set_baseurl(&source);
  }

  /// Return the version of the application.
  #[must_use]
  pub fn version(&self) -> Option<&str> {
    self.metadata.as_ref().map(|m| m.version.as_str())
  }

  /// Add a resource to the application configuration.
  pub fn add_resource<T: Into<String>>(&mut self, name: T, resource: ResourceDefinition) {
    self.resources.push(Binding::new(name, resource));
  }

  /// Generate V1 configuration yaml from this configuration.
  #[cfg(feature = "v1")]
  pub fn into_v1_yaml(self) -> Result<String> {
    let v1_manifest: crate::v1::AppConfiguration = self.try_into()?;
    Ok(serde_yaml::to_string(&v1_manifest).unwrap())
  }

  /// Initialize the configuration with the given environment variables.
  pub(super) fn initialize(&mut self) -> Result<&Self> {
    let root_config = self.root_config.as_ref();
    let source = self.source().map(std::path::Path::to_path_buf);

    trace!(
      source = ?source,
      num_resources = self.resources.len(),
      num_imports = self.import.len(),
      ?root_config,
      "initializing app resources"
    );
    let env = self.env.as_ref();

    let mut bindings = Vec::new();
    for (i, trigger) in self.triggers.iter_mut().enumerate() {
      trigger.expand_imports(&mut bindings, i)?;
    }
    self.import.extend(bindings);

    self.resources.render_config(source.as_deref(), root_config, env)?;
    self.import.render_config(source.as_deref(), root_config, env)?;
    self.triggers.render_config(source.as_deref(), root_config, env)?;

    Ok(self)
  }

  /// Validate this configuration is good.
  pub const fn validate(&self) -> Result<()> {
    /* placeholder */
    Ok(())
  }
}

impl Renderable for AppConfiguration {
  fn render_config(
    &mut self,
    source: Option<&Path>,
    root_config: Option<&RuntimeConfig>,
    env: Option<&HashMap<String, String>>,
  ) -> Result<()> {
    self.resources.render_config(source, root_config, env)?;
    self.import.render_config(source, root_config, env)?;
    self.triggers.render_config(source, root_config, env)?;
    Ok(())
  }
}

impl Lockdown for AppConfiguration {
  fn lockdown(
    &self,
    _id: Option<&str>,
    lockdown: &config::LockdownConfiguration,
  ) -> std::result::Result<(), LockdownError> {
    let mut errors = Vec::new();
    let id = Entity::LOCAL;

    for resource in &self.resources {
      if let Err(e) = validate_resource(id, &(resource.into()), lockdown) {
        errors.push(FailureKind::Failed(Box::new(e)));
      }
    }
    if errors.is_empty() {
      Ok(())
    } else {
      Err(LockdownError::new(errors))
    }
  }
}

/// A configuration item
#[derive(Debug, Clone, PartialEq)]
#[must_use]

pub enum ConfigurationItem<'a> {
  /// A component definition.
  Component(&'a ComponentDefinition),
  /// A component definition.
  Types(&'a TypesComponent),
  /// A resource definition.
  Resource(&'a ResourceDefinition),
}

impl<'a> ConfigurationItem<'a> {
  /// Get the component definition or return an error.
  pub const fn try_component(&self) -> std::result::Result<&'a ComponentDefinition, ReferenceError> {
    match self {
      Self::Component(c) => Ok(c),
      _ => Err(ReferenceError::Component),
    }
  }

  /// Get the types definition or return an error.
  pub const fn try_types(&self) -> std::result::Result<&'a TypesComponent, ReferenceError> {
    match self {
      Self::Types(c) => Ok(c),
      _ => Err(ReferenceError::Types),
    }
  }

  /// Get the resource definition or return an error.
  pub const fn try_resource(&self) -> std::result::Result<&'a ResourceDefinition, ReferenceError> {
    match self {
      Self::Resource(c) => Ok(c),
      _ => Err(ReferenceError::Resource),
    }
  }
}

/// A configuration item
#[derive(Debug, Clone, PartialEq)]
#[must_use]

pub enum OwnedConfigurationItem {
  /// A component definition.
  Component(ComponentDefinition),
  /// A resource definition.
  Resource(ResourceDefinition),
}

impl OwnedConfigurationItem {
  /// Get the component definition or return an error.
  #[allow(clippy::missing_const_for_fn)]
  pub fn try_component(self) -> Result<ComponentDefinition> {
    match self {
      Self::Component(c) => Ok(c),
      _ => Err(ManifestError::Reference(ReferenceError::Component)),
    }
  }
  /// Get the resource definition or return an error.
  #[allow(clippy::missing_const_for_fn)]
  pub fn try_resource(self) -> Result<ResourceDefinition> {
    match self {
      Self::Resource(c) => Ok(c),
      _ => Err(ManifestError::Reference(ReferenceError::Resource)),
    }
  }
}

impl AppConfigurationBuilder {
  /// Build the configuration.
  pub fn build(&self) -> Result<AppConfiguration> {
    let config = self.clone();
    let config = config.build_internal()?;
    config.validate()?;
    Ok(config)
  }
}

#[cfg(test)]
mod test {
  use anyhow::Result;
  use serde_json::json;

  use super::*;
  use crate::config::components::ManifestComponentBuilder;
  use crate::config::{Codec, ComponentOperationExpressionBuilder, LiquidJsonConfig, MiddlewareBuilder};

  #[test]
  fn test_trigger_render() -> Result<()> {
    let op = ComponentOperationExpressionBuilder::default()
      .component(ComponentDefinition::Manifest(
        ManifestComponentBuilder::default()
          .reference("this/that:0.0.1")
          .build()?,
      ))
      .config(LiquidJsonConfig::try_from(
        json!({"op_config_field": "{{ctx.env.CARGO_MANIFEST_DIR}}"}),
      )?)
      .name("test")
      .build()?;
    let trigger = HttpTriggerConfigBuilder::default()
      .resource("URL")
      .routers(vec![HttpRouterConfig::RawRouter(RawRouterConfig {
        path: "/".to_owned(),
        middleware: Some(
          MiddlewareBuilder::default()
            .request(vec![op.clone()])
            .response(vec![op.clone()])
            .build()?,
        ),
        codec: Some(Codec::Json),
        operation: op,
      })])
      .build()?;
    let mut config = AppConfigurationBuilder::default()
      .name("test")
      .resources(vec![Binding::new("PORT", TcpPort::new("0.0.0.0", 90))])
      .triggers(vec![TriggerDefinition::Http(trigger)])
      .build()?;

    config.env = Some(std::env::vars().collect());
    config.root_config = Some(json!({"config_val": "from_config"}).try_into()?);

    config.initialize()?;

    let TriggerDefinition::Http(mut trigger) = config.triggers.pop().unwrap() else {
      unreachable!();
    };

    let HttpRouterConfig::RawRouter(mut router) = trigger.routers.pop().unwrap() else {
      unreachable!();
    };

    let cargo_manifest_dir = json!(env!("CARGO_MANIFEST_DIR"));

    let config = router.operation.config.take().unwrap().value.unwrap();
    assert_eq!(config.get("op_config_field"), Some(&cargo_manifest_dir));

    let mut mw = router.middleware.take().unwrap();

    let mw_req_config = mw.request[0].config.take().unwrap().value.unwrap();
    assert_eq!(mw_req_config.get("op_config_field"), Some(&cargo_manifest_dir));

    let mw_res_config = mw.response[0].config.take().unwrap().value.unwrap();
    assert_eq!(mw_res_config.get("op_config_field"), Some(&cargo_manifest_dir));

    Ok(())
  }
}