drasi-plugin-sdk 0.4.2

SDK for building Drasi plugins (sources, reactions, bootstrappers)
Documentation
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
416
417
418
419
420
421
422
423
// Copyright 2025 The Drasi Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! DTO-to-domain model mapping service with value resolution.
//!
//! The [`DtoMapper`] is the main mapping service that plugins use to convert their
//! DTO configuration structs into domain model values. It resolves [`ConfigValue`]
//! references (environment variables, secrets) into their actual values.
//!
//! # Usage in Plugin Descriptors
//!
//! ```rust,ignore
//! use drasi_plugin_sdk::prelude::*;
//!
//! struct MySourceDescriptor;
//!
//! #[async_trait]
//! impl SourcePluginDescriptor for MySourceDescriptor {
//!     // ... other methods ...
//!
//!     async fn create_source(
//!         &self,
//!         id: &str,
//!         config_json: &serde_json::Value,
//!         auto_start: bool,
//!     ) -> anyhow::Result<Box<dyn drasi_lib::Source>> {
//!         // Deserialize the JSON into the plugin's DTO
//!         let dto: MySourceConfigDto = serde_json::from_value(config_json.clone())?;
//!
//!         // Create a mapper to resolve config values
//!         let mapper = DtoMapper::new();
//!
//!         // Resolve individual fields
//!         let host = mapper.resolve_string(&dto.host)?;
//!         let port = mapper.resolve_typed(&dto.port)?;
//!
//!         // Build the source using resolved values
//!         Ok(Box::new(MySource::new(id, host, port, auto_start)))
//!     }
//! }
//! ```
//!
//! # The ConfigMapper Pattern
//!
//! For complex mappings, implement the [`ConfigMapper`] trait to encapsulate the
//! conversion logic:
//!
//! ```rust,ignore
//! use drasi_plugin_sdk::prelude::*;
//!
//! struct MyConfigMapper;
//!
//! impl ConfigMapper<MySourceConfigDto, MySourceConfig> for MyConfigMapper {
//!     fn map(&self, dto: &MySourceConfigDto, resolver: &DtoMapper) -> Result<MySourceConfig, MappingError> {
//!         Ok(MySourceConfig {
//!             host: resolver.resolve_string(&dto.host)?,
//!             port: resolver.resolve_typed(&dto.port)?,
//!             timeout: resolver.resolve_optional(&dto.timeout_ms)?,
//!         })
//!     }
//! }
//! ```

use crate::config_value::ConfigValue;
use crate::resolver::{
    get_secret_resolver, EnvironmentVariableResolver, ResolverError, SecretResolver, ValueResolver,
};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
use thiserror::Error;

/// Errors that can occur during DTO-to-domain mapping.
#[derive(Debug, Error)]
pub enum MappingError {
    /// A [`ConfigValue`] reference could not be resolved.
    #[error("Failed to resolve config value: {0}")]
    ResolutionError(#[from] ResolverError),

    /// No mapper was found for the given config type.
    #[error("No mapper found for config type: {0}")]
    NoMapperFound(String),

    /// The mapper received a DTO type it doesn't handle.
    #[error("Mapper type mismatch")]
    MapperTypeMismatch,

    /// Source creation failed.
    #[error("Failed to create source: {0}")]
    SourceCreationError(String),

    /// Reaction creation failed.
    #[error("Failed to create reaction: {0}")]
    ReactionCreationError(String),

    /// A configuration value was invalid.
    #[error("Invalid value: {0}")]
    InvalidValue(String),
}

/// Trait for converting a specific DTO config type to its domain model.
///
/// Implement this trait when you have a complex mapping between a DTO and its
/// corresponding domain type. The `resolver` parameter provides access to
/// [`DtoMapper`] for resolving [`ConfigValue`] references.
///
/// # Type Parameters
///
/// - `TDto` — The DTO (Data Transfer Object) type from the API layer.
/// - `TDomain` — The domain model type used internally by the plugin.
pub trait ConfigMapper<TDto, TDomain>: Send + Sync {
    /// Convert a DTO to its domain model, resolving any config value references.
    fn map(&self, dto: &TDto, resolver: &DtoMapper) -> Result<TDomain, MappingError>;
}

/// Main mapping service that resolves [`ConfigValue`] references in plugin DTOs.
///
/// Provides methods to resolve `ConfigValue<T>` fields into their actual values
/// by dispatching to the appropriate [`ValueResolver`] based on the variant.
///
/// # Default Resolvers
///
/// - `"EnvironmentVariable"` → [`EnvironmentVariableResolver`]
/// - `"Secret"` → [`SecretResolver`] (currently returns `NotImplemented`)
pub struct DtoMapper {
    resolvers: HashMap<&'static str, Arc<dyn ValueResolver>>,
}

impl DtoMapper {
    /// Create a new mapper with the default resolvers (environment variable + secret).
    ///
    /// If a global secret resolver has been registered via
    /// [`register_secret_resolver`](crate::resolver::register_secret_resolver),
    /// it will be used automatically. Otherwise, the default [`SecretResolver`]
    /// stub is used (which returns `NotImplemented`).
    pub fn new() -> Self {
        let mut resolvers: HashMap<&'static str, Arc<dyn ValueResolver>> = HashMap::new();
        resolvers.insert("EnvironmentVariable", Arc::new(EnvironmentVariableResolver));

        let secret_resolver = get_secret_resolver().unwrap_or_else(|| Arc::new(SecretResolver));
        resolvers.insert("Secret", secret_resolver);

        Self { resolvers }
    }

    /// Register a custom [`ValueResolver`] for a given reference kind.
    ///
    /// This replaces any previously registered resolver for the same kind.
    pub fn with_resolver(mut self, kind: &'static str, resolver: Arc<dyn ValueResolver>) -> Self {
        self.resolvers.insert(kind, resolver);
        self
    }

    /// Resolve a `ConfigValue<String>` to its actual string value.
    pub fn resolve_string(&self, value: &ConfigValue<String>) -> Result<String, ResolverError> {
        match value {
            ConfigValue::Static(s) => Ok(s.clone()),

            ConfigValue::Secret { .. } => {
                let resolver = self
                    .resolvers
                    .get("Secret")
                    .ok_or_else(|| ResolverError::NoResolverFound("Secret".to_string()))?;
                resolver.resolve_to_string(value)
            }

            ConfigValue::EnvironmentVariable { .. } => {
                let resolver = self.resolvers.get("EnvironmentVariable").ok_or_else(|| {
                    ResolverError::NoResolverFound("EnvironmentVariable".to_string())
                })?;
                resolver.resolve_to_string(value)
            }
        }
    }

    /// Resolve a `ConfigValue<T>` to its typed value.
    ///
    /// For `Static` values, returns the value directly. For `EnvironmentVariable` and
    /// `Secret` references, resolves to a string first, then parses to `T` via [`FromStr`].
    pub fn resolve_typed<T>(&self, value: &ConfigValue<T>) -> Result<T, ResolverError>
    where
        T: FromStr + Clone + serde::Serialize + serde::de::DeserializeOwned,
        T::Err: std::fmt::Display,
    {
        match value {
            ConfigValue::Static(v) => Ok(v.clone()),

            ConfigValue::Secret { name } => {
                let resolver = self
                    .resolvers
                    .get("Secret")
                    .ok_or_else(|| ResolverError::NoResolverFound("Secret".to_string()))?;
                let string_cv = ConfigValue::Secret { name: name.clone() };
                let string_val = resolver.resolve_to_string(&string_cv)?;
                string_val.parse::<T>().map_err(|e| {
                    ResolverError::ParseError(format!("Failed to parse secret '{name}': {e}"))
                })
            }

            ConfigValue::EnvironmentVariable { name, default } => {
                let string_val = std::env::var(name).or_else(|_| {
                    default
                        .clone()
                        .ok_or_else(|| ResolverError::EnvVarNotFound(name.clone()))
                })?;

                string_val.parse::<T>().map_err(|e| {
                    ResolverError::ParseError(format!("Failed to parse env var '{name}': {e}"))
                })
            }
        }
    }

    /// Resolve an optional `ConfigValue<T>`. Returns `Ok(None)` if the value is `None`.
    pub fn resolve_optional<T>(
        &self,
        value: &Option<ConfigValue<T>>,
    ) -> Result<Option<T>, ResolverError>
    where
        T: FromStr + Clone + serde::Serialize + serde::de::DeserializeOwned,
        T::Err: std::fmt::Display,
    {
        value.as_ref().map(|v| self.resolve_typed(v)).transpose()
    }

    /// Resolve an optional `ConfigValue<String>` to `Option<String>`.
    pub fn resolve_optional_string(
        &self,
        value: &Option<ConfigValue<String>>,
    ) -> Result<Option<String>, ResolverError> {
        value.as_ref().map(|v| self.resolve_string(v)).transpose()
    }

    /// Resolve a slice of `ConfigValue<String>` to `Vec<String>`.
    pub fn resolve_string_vec(
        &self,
        values: &[ConfigValue<String>],
    ) -> Result<Vec<String>, ResolverError> {
        values.iter().map(|v| self.resolve_string(v)).collect()
    }

    /// Map a DTO using a [`ConfigMapper`] implementation.
    pub fn map_with<TDto, TDomain>(
        &self,
        dto: &TDto,
        mapper: &impl ConfigMapper<TDto, TDomain>,
    ) -> Result<TDomain, MappingError> {
        mapper.map(dto, self)
    }
}

impl Default for DtoMapper {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_resolve_string_static() {
        let mapper = DtoMapper::new();
        let value = ConfigValue::Static("hello".to_string());

        let result = mapper.resolve_string(&value).expect("resolve");
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_resolve_string_env_var() {
        std::env::set_var("TEST_SDK_MAPPER_VAR", "mapped_value");

        let mapper = DtoMapper::new();
        let value = ConfigValue::EnvironmentVariable {
            name: "TEST_SDK_MAPPER_VAR".to_string(),
            default: None,
        };

        let result = mapper.resolve_string(&value).expect("resolve");
        assert_eq!(result, "mapped_value");

        std::env::remove_var("TEST_SDK_MAPPER_VAR");
    }

    #[test]
    fn test_resolve_typed_u16() {
        let mapper = DtoMapper::new();
        let value = ConfigValue::Static(5432u16);

        let result = mapper.resolve_typed(&value).expect("resolve");
        assert_eq!(result, 5432u16);
    }

    #[test]
    fn test_resolve_typed_u16_from_env() {
        std::env::set_var("TEST_SDK_PORT", "8080");

        let mapper = DtoMapper::new();
        let value: ConfigValue<u16> = ConfigValue::EnvironmentVariable {
            name: "TEST_SDK_PORT".to_string(),
            default: None,
        };

        let result = mapper.resolve_typed(&value).expect("resolve");
        assert_eq!(result, 8080u16);

        std::env::remove_var("TEST_SDK_PORT");
    }

    #[test]
    fn test_resolve_typed_parse_error() {
        std::env::set_var("TEST_SDK_INVALID_PORT", "not_a_number");

        let mapper = DtoMapper::new();
        let value: ConfigValue<u16> = ConfigValue::EnvironmentVariable {
            name: "TEST_SDK_INVALID_PORT".to_string(),
            default: None,
        };

        let result = mapper.resolve_typed(&value);
        assert!(result.is_err());
        assert!(matches!(
            result.expect_err("should fail"),
            ResolverError::ParseError(_)
        ));

        std::env::remove_var("TEST_SDK_INVALID_PORT");
    }

    #[test]
    fn test_resolve_optional_some() {
        let mapper = DtoMapper::new();
        let value = Some(ConfigValue::Static("test".to_string()));

        let result = mapper.resolve_optional(&value).expect("resolve");
        assert_eq!(result, Some("test".to_string()));
    }

    #[test]
    fn test_resolve_optional_none() {
        let mapper = DtoMapper::new();
        let value: Option<ConfigValue<String>> = None;

        let result = mapper.resolve_optional(&value).expect("resolve");
        assert_eq!(result, None);
    }

    #[test]
    fn test_resolve_string_vec() {
        let mapper = DtoMapper::new();
        let values = vec![
            ConfigValue::Static("a".to_string()),
            ConfigValue::Static("b".to_string()),
        ];

        let result = mapper.resolve_string_vec(&values).expect("resolve");
        assert_eq!(result, vec!["a", "b"]);
    }

    #[test]
    fn test_config_mapper_trait() {
        struct TestMapper;

        #[derive(Debug)]
        struct TestDto {
            host: ConfigValue<String>,
        }

        struct TestDomain {
            host: String,
        }

        impl ConfigMapper<TestDto, TestDomain> for TestMapper {
            fn map(&self, dto: &TestDto, resolver: &DtoMapper) -> Result<TestDomain, MappingError> {
                Ok(TestDomain {
                    host: resolver.resolve_string(&dto.host)?,
                })
            }
        }

        let mapper = DtoMapper::new();
        let dto = TestDto {
            host: ConfigValue::Static("localhost".to_string()),
        };

        let domain = mapper.map_with(&dto, &TestMapper).expect("map");
        assert_eq!(domain.host, "localhost");
    }

    #[test]
    fn test_custom_resolver() {
        struct AlwaysResolver;
        impl ValueResolver for AlwaysResolver {
            fn resolve_to_string(
                &self,
                _value: &ConfigValue<String>,
            ) -> Result<String, ResolverError> {
                Ok("custom-resolved".to_string())
            }
        }

        let mapper = DtoMapper::new().with_resolver("Secret", Arc::new(AlwaysResolver));
        let value = ConfigValue::Secret {
            name: "test".to_string(),
        };

        let result = mapper.resolve_string(&value).expect("resolve");
        assert_eq!(result, "custom-resolved");
    }
}