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
#![allow(missing_docs, deprecated)]
use std::collections::HashMap;
use std::path::Path;

// delete when we move away from the `property` crate.
use serde::de::{IgnoredAny, SeqAccess, Visitor};
use serde::Deserializer;
use wick_interface_types::OperationSignatures;
use wick_packet::{Entity, RuntimeConfig};

use super::template_config::Renderable;
use super::Binding;
use crate::config::{self, ExecutionSettings, ImportDefinition, LiquidJsonConfig};
use crate::error::ManifestError;

/// A reference to an operation.
#[derive(
  Debug,
  Clone,
  PartialEq,
  derive_asset_container::AssetManager,
  property::Property,
  serde::Serialize,
  derive_builder::Builder,
)]
#[builder(setter(into))]
#[property(get(public), set(public), mut(public, suffix = "_mut"))]
#[asset(asset(config::AssetReference))]

pub struct ComponentOperationExpression {
  /// The operation ID.
  #[asset(skip)]
  pub(crate) name: String,
  /// The component referenced by identifier or anonymously.
  pub(crate) component: ComponentDefinition,
  /// Configuration to associate with this operation.
  #[asset(skip)]
  #[builder(default)]
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) config: Option<LiquidJsonConfig>,
  /// Per-operation settings that override global execution settings.
  #[asset(skip)]
  #[builder(default)]
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) settings: Option<ExecutionSettings>,
}

impl ComponentOperationExpression {
  /// Create a new [ComponentOperationExpression] with specified operation and component.
  pub fn new_default<T: Into<String>>(operation: T, component: ComponentDefinition) -> Self {
    Self {
      name: operation.into(),
      component,
      config: Default::default(),
      settings: Default::default(),
    }
  }

  /// Create a new [ComponentOperationExpression] with specified operation and component.
  pub fn new<T: Into<String>>(
    operation: T,
    component: ComponentDefinition,
    config: Option<LiquidJsonConfig>,
    settings: Option<ExecutionSettings>,
  ) -> Self {
    Self {
      name: operation.into(),
      component,
      config,
      settings,
    }
  }

  pub fn maybe_import(&mut self, import_name: &str, bindings: &mut Vec<Binding<ImportDefinition>>) {
    if self.component.is_reference() {
      return;
    }

    tracing::Span::current().in_scope(|| {
      tracing::debug!("importing inline component as {}", import_name);
      let def = std::mem::replace(
        &mut self.component,
        ComponentDefinition::Reference(config::components::ComponentReference::new(import_name)),
      );
      bindings.push(Binding::new(import_name, config::ImportDefinition::Component(def)));
    });
  }

  /// Get the operation as an [Entity] if the component definition is a referencable instance.
  #[must_use]
  pub fn as_entity(&self) -> Option<Entity> {
    if let ComponentDefinition::Reference(r) = &self.component {
      Some(Entity::operation(&r.id, &self.name))
    } else {
      None
    }
  }
}

impl Renderable for ComponentOperationExpression {
  fn render_config(
    &mut self,
    source: Option<&Path>,
    root_config: Option<&RuntimeConfig>,
    env: Option<&HashMap<String, String>>,
  ) -> Result<(), ManifestError> {
    if let Some(config) = self.config.as_mut() {
      config.set_value(Some(config.render(source, root_config, None, env, None)?));
    }
    Ok(())
  }
}

impl std::str::FromStr for ComponentOperationExpression {
  type Err = crate::Error;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    let mut parts = s.split("::");

    let operation = parts
      .next()
      .ok_or_else(|| crate::Error::InvalidOperationExpression(s.to_owned()))?
      .to_owned();
    let component = parts
      .next()
      .ok_or_else(|| crate::Error::InvalidOperationExpression(s.to_owned()))?
      .to_owned();

    Ok(Self {
      name: operation,
      component: ComponentDefinition::Reference(config::components::ComponentReference { id: component }),
      config: Default::default(),
      settings: Default::default(),
    })
  }
}

#[derive(Debug, Clone, PartialEq, derive_asset_container::AssetManager, serde::Serialize)]
#[asset(asset(config::AssetReference))]
/// A definition of a Wick Collection with its namespace, how to retrieve or access it and its configuration.
#[must_use]
#[serde(rename_all = "kebab-case")]
pub enum HighLevelComponent {
  /// A SQL Component.
  #[asset(skip)]
  Sql(config::components::SqlComponentConfig),
  #[asset(skip)]
  /// An HTTP Client Component.
  HttpClient(config::components::HttpClientComponentConfig),
}

impl OperationSignatures for HighLevelComponent {
  fn operation_signatures(&self) -> Vec<wick_interface_types::OperationSignature> {
    match self {
      HighLevelComponent::Sql(c) => c.operation_signatures(),
      HighLevelComponent::HttpClient(c) => c.operation_signatures(),
    }
  }
}

/// The kinds of collections that can operate in a flow.
#[derive(Debug, Clone, PartialEq, derive_asset_container::AssetManager, serde::Serialize)]
#[asset(asset(config::AssetReference))]
#[must_use]
#[serde(rename_all = "kebab-case")]
pub enum ComponentDefinition {
  #[doc(hidden)]
  #[asset(skip)]
  Native(config::components::NativeComponent),
  /// WebAssembly Collections.
  #[deprecated(note = "Use ManifestComponent instead")]
  Wasm(config::components::WasmComponent),
  /// A component reference.
  #[asset(skip)]
  Reference(config::components::ComponentReference),
  /// Separate microservices that Wick can connect to.
  #[asset(skip)]
  GrpcUrl(config::components::GrpcUrlComponent),
  /// External manifests.
  Manifest(config::components::ManifestComponent),
  /// Postgres Component.
  #[asset(skip)]
  HighLevelComponent(HighLevelComponent),
}

#[derive(Debug, Clone, Copy)]
pub enum ComponentDefinitionKind {
  Native,
  Wasm,
  Reference,
  GrpcUrl,
  Manifest,
  HighLevelComponent,
}

impl std::fmt::Display for ComponentDefinitionKind {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      ComponentDefinitionKind::Native => write!(f, "native"),
      ComponentDefinitionKind::Wasm => write!(f, "wasm"),
      ComponentDefinitionKind::Reference => write!(f, "reference"),
      ComponentDefinitionKind::GrpcUrl => write!(f, "grpc-url"),
      ComponentDefinitionKind::Manifest => write!(f, "manifest"),
      ComponentDefinitionKind::HighLevelComponent => write!(f, "high-level-component"),
    }
  }
}

impl ComponentDefinition {
  /// Returns true if the definition is a reference to another component.
  #[must_use]
  pub const fn is_reference(&self) -> bool {
    matches!(self, ComponentDefinition::Reference(_))
  }

  /// Returns the kind of the component definition.
  #[must_use]
  pub const fn kind(&self) -> ComponentDefinitionKind {
    match self {
      ComponentDefinition::Native(_) => ComponentDefinitionKind::Native,
      ComponentDefinition::Wasm(_) => ComponentDefinitionKind::Wasm,
      ComponentDefinition::Reference(_) => ComponentDefinitionKind::Reference,
      ComponentDefinition::GrpcUrl(_) => ComponentDefinitionKind::GrpcUrl,
      ComponentDefinition::Manifest(_) => ComponentDefinitionKind::Manifest,
      ComponentDefinition::HighLevelComponent(_) => ComponentDefinitionKind::HighLevelComponent,
    }
  }

  /// Returns the component config, if it exists
  #[must_use]
  pub const fn config(&self) -> Option<&LiquidJsonConfig> {
    match self {
      #[allow(deprecated)]
      ComponentDefinition::Wasm(c) => c.config.as_ref(),
      ComponentDefinition::GrpcUrl(c) => c.config.as_ref(),
      ComponentDefinition::Manifest(c) => c.config.as_ref(),
      ComponentDefinition::Native(_) => None,
      ComponentDefinition::Reference(_) => None,
      ComponentDefinition::HighLevelComponent(_) => None,
    }
  }

  /// Returns any components this configuration provides to the implementation.
  #[must_use]
  pub fn provide(&self) -> Option<&HashMap<String, String>> {
    match self {
      #[allow(deprecated)]
      ComponentDefinition::Wasm(c) => Some(c.provide()),
      ComponentDefinition::GrpcUrl(_) => None,
      ComponentDefinition::Manifest(c) => Some(c.provide()),
      ComponentDefinition::Native(_) => None,
      ComponentDefinition::Reference(_) => None,
      ComponentDefinition::HighLevelComponent(_) => None,
    }
  }

  /// Returns the component config, if it exists
  #[must_use]
  pub fn config_mut(&mut self) -> Option<&mut LiquidJsonConfig> {
    match self {
      #[allow(deprecated)]
      ComponentDefinition::Wasm(c) => c.config.as_mut(),
      ComponentDefinition::GrpcUrl(c) => c.config.as_mut(),
      ComponentDefinition::Manifest(c) => c.config.as_mut(),
      ComponentDefinition::Native(_) => None,
      ComponentDefinition::Reference(_) => None,
      ComponentDefinition::HighLevelComponent(_) => None,
    }
  }

  /// Returns the component config, if it exists
  pub fn set_config(&mut self, config: Option<RuntimeConfig>) {
    match self {
      #[allow(deprecated)]
      ComponentDefinition::Wasm(c) => c.config.as_mut().map(|c| c.set_value(config)),
      ComponentDefinition::GrpcUrl(c) => c.config.as_mut().map(|c| c.set_value(config)),
      ComponentDefinition::Manifest(c) => c.config.as_mut().map(|c| c.set_value(config)),
      ComponentDefinition::Native(_) => None,
      ComponentDefinition::Reference(_) => None,
      ComponentDefinition::HighLevelComponent(_) => None,
    };
  }
}

impl Renderable for ComponentDefinition {
  fn render_config(
    &mut self,
    source: Option<&Path>,
    root_config: Option<&RuntimeConfig>,
    env: Option<&HashMap<String, String>>,
  ) -> Result<(), ManifestError> {
    let val = if let Some(config) = self.config() {
      Some(config.render(source, root_config, None, env, None)?)
    } else {
      None
    };
    self.set_config(val);
    Ok(())
  }
}

impl OperationSignatures for &ComponentDefinition {
  fn operation_signatures(&self) -> Vec<wick_interface_types::OperationSignature> {
    match self {
      ComponentDefinition::Manifest(c) => c.operation_signatures(),
      ComponentDefinition::HighLevelComponent(c) => c.operation_signatures(),
      ComponentDefinition::Native(_) => unreachable!(),
      ComponentDefinition::Reference(_) => unreachable!(),
      ComponentDefinition::GrpcUrl(_) => unreachable!(),
      #[allow(deprecated)]
      ComponentDefinition::Wasm(_) => unreachable!(),
    }
  }
}

#[derive(Default, Debug)]
struct StringPair(String, String);

impl<'de> serde::Deserialize<'de> for StringPair {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: Deserializer<'de>,
  {
    struct StringPairVisitor;

    impl<'de> Visitor<'de> for StringPairVisitor {
      type Value = StringPair;

      fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a String pair")
      }

      fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
      where
        V: SeqAccess<'de>,
      {
        let s = seq
          .next_element()?
          .ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;
        let n = seq
          .next_element()?
          .ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;

        // This is very important!
        while matches!(seq.next_element()?, Some(IgnoredAny)) {
          // Ignore rest
        }

        Ok(StringPair(s, n))
      }
    }

    deserializer.deserialize_seq(StringPairVisitor)
  }
}