asimov-module 25.1.0

ASIMOV Software Development Kit (SDK) for Rust
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
// This is free and unencumbered software released into the public domain.

use alloc::{collections::BTreeMap, string::String, vec::Vec};

/// See: https://asimov-specs.github.io/module-manifest/
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct ModuleManifest {
    /// See: https://asimov-specs.github.io/module-manifest/#name-field
    pub name: String,

    /// See: https://asimov-specs.github.io/module-manifest/#label-field
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub label: Option<String>,

    /// See: https://asimov-specs.github.io/module-manifest/#title-field
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub title: Option<String>,

    /// See: https://asimov-specs.github.io/module-manifest/#summary-field
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub summary: Option<String>,

    /// See: https://asimov-specs.github.io/module-manifest/#links-field
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub links: Vec<String>,

    /// See: https://asimov-specs.github.io/module-manifest/#tags-field
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub tags: Vec<String>,

    /// See: https://asimov-specs.github.io/module-manifest/#requires-section
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Requires::is_empty")
    )]
    pub requires: Requires,

    /// See: https://asimov-specs.github.io/module-manifest/#provides-section
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Provides::is_empty")
    )]
    pub provides: Provides,

    /// See: https://asimov-specs.github.io/module-manifest/#handles-section
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Handles::is_empty")
    )]
    pub handles: Handles,

    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            alias = "configuration",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub config: Option<Configuration>,
}

#[cfg(feature = "std")]
#[derive(Debug, thiserror::Error)]
pub enum ReadVarError {
    #[error("variable named `{0}` not found in module manifest")]
    UnknownVar(String),

    #[error("a value for variable `{0}` was not configured")]
    UnconfiguredVar(String),

    #[error("failed to read variable `{name}`: {source}")]
    Io {
        name: String,
        #[source]
        source: std::io::Error,
    },
}

impl ModuleManifest {
    #[cfg(all(feature = "std", feature = "serde"))]
    pub fn read_manifest(module_name: &str) -> std::io::Result<Self> {
        let directory = asimov_env::paths::asimov_root().join("modules");
        let search_paths = [
            ("installed", "json"),
            ("installed", "yaml"), // legacy, new installs are converted to JSON
            ("", "yaml"),          // legacy, new installs go to `installed/`
        ];

        for (sub_dir, ext) in search_paths {
            let file = std::path::PathBuf::from(sub_dir)
                .join(module_name)
                .with_extension(ext);

            match std::fs::read(directory.join(&file)) {
                Ok(content) if ext == "json" => {
                    return serde_json::from_slice(&content).map_err(std::io::Error::other);
                },
                Ok(content) if ext == "yaml" => {
                    return serde_yaml_ng::from_slice(&content).map_err(std::io::Error::other);
                },
                Ok(_) => unreachable!(),

                Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
                Err(err) => return Err(err),
            }
        }

        Err(std::io::ErrorKind::NotFound.into())
    }

    #[cfg(feature = "std")]
    pub fn read_variables(
        &self,
        profile: Option<&str>,
    ) -> Result<std::collections::BTreeMap<String, String>, ReadVarError> {
        self.config
            .as_ref()
            .map(|c| c.variables.as_slice())
            .unwrap_or_default()
            .iter()
            .map(|var| Ok((var.name.clone(), self.variable(&var.name, profile)?)))
            .collect()
    }

    #[cfg(feature = "std")]
    pub fn variable(&self, key: &str, profile: Option<&str>) -> Result<String, ReadVarError> {
        let Some(var) = self
            .config
            .as_ref()
            .and_then(|conf| conf.variables.iter().find(|var| var.name == key))
        else {
            return Err(ReadVarError::UnknownVar(key.into()));
        };

        if let Some(value) = var
            .environment
            .as_deref()
            .and_then(|env_name| std::env::var(env_name).ok())
        {
            return Ok(value);
        }

        let profile = profile.unwrap_or("default");
        let path = asimov_env::paths::asimov_root()
            .join("configs")
            .join(profile)
            .join(&self.name)
            .join(key);

        std::fs::read_to_string(&path).or_else(|err| {
            if err.kind() == std::io::ErrorKind::NotFound {
                var.default_value
                    .clone()
                    .ok_or_else(|| ReadVarError::UnconfiguredVar(key.into()))
            } else {
                Err(ReadVarError::Io {
                    name: key.into(),
                    source: err,
                })
            }
        })
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Requires {
    /// The set of modules that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub modules: Vec<String>,

    /// The set of platforms that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub platforms: Vec<String>,

    /// The set of programs that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub programs: Vec<String>,

    /// The set of libraries that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub libraries: Vec<String>,

    /// The set of models that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "BTreeMap::is_empty")
    )]
    pub models: BTreeMap<String, RequiredModel>,

    /// The set of datasets that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub datasets: Vec<String>,

    /// The set of ontologies that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub ontologies: Vec<String>,

    /// The set of classes that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub classes: Vec<String>,

    /// The set of datatypes that this module depends on.
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub datatypes: Vec<String>,
}

impl Requires {
    pub fn is_empty(&self) -> bool {
        self.modules.is_empty() && self.models.is_empty()
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(untagged)
)]
pub enum RequiredModel {
    /// Just a direct URL string:
    /// ```yaml
    /// hf:first/model: model_file.bin
    /// ```
    Url(String),

    /// Multiple variants:
    /// ```yaml
    /// hf:second/model:
    ///   small: model_small.bin
    ///   medium: model_medium.bin
    ///   large: model_large.bin
    /// ```
    #[cfg_attr(
        feature = "serde",
        serde(deserialize_with = "ordered::deserialize_ordered")
    )]
    Choices(Vec<(String, String)>),
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Provides {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub programs: Vec<String>,
}

impl Provides {
    pub fn is_empty(&self) -> bool {
        self.programs.is_empty()
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Handles {
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub url_protocols: Vec<String>,

    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub url_prefixes: Vec<String>,

    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub url_patterns: Vec<String>,

    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub file_extensions: Vec<String>,

    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            deserialize_with = "empty_vec_if_null",
            skip_serializing_if = "Vec::is_empty"
        )
    )]
    pub content_types: Vec<String>,
}

impl Handles {
    pub fn is_empty(&self) -> bool {
        self.url_protocols.is_empty()
            && self.url_prefixes.is_empty()
            && self.url_patterns.is_empty()
            && self.file_extensions.is_empty()
            && self.content_types.is_empty()
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Configuration {
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub variables: Vec<ConfigurationVariable>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct ConfigurationVariable {
    /// The name of the variable. Configured variables are by default saved in
    /// `~/.asimov/configs/$profile/$module/$name`.
    pub name: String,

    /// Optional description to provide information about the variable.
    #[cfg_attr(
        feature = "serde",
        serde(default, alias = "desc", skip_serializing_if = "Option::is_none")
    )]
    pub description: Option<String>,

    /// Optional name of an environment variable to check for a value before checking for a
    /// configured or a default value.
    #[cfg_attr(
        feature = "serde",
        serde(default, alias = "env", skip_serializing_if = "Option::is_none")
    )]
    pub environment: Option<String>,

    /// Optional default value to use as a fallback. If a default value is present the user
    /// configuration of the value is not required.
    #[cfg_attr(
        feature = "serde",
        serde(default, alias = "default", skip_serializing_if = "Option::is_none")
    )]
    pub default_value: Option<String>,
}

#[cfg(feature = "serde")]
fn empty_vec_if_null<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: serde::Deserialize<'de>,
{
    use serde::Deserialize;
    Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
}

#[cfg(feature = "serde")]
mod ordered {
    use super::*;
    use serde::{
        Deserializer,
        de::{MapAccess, Visitor},
    };
    use std::fmt;

    pub fn deserialize_ordered<'de, D>(deserializer: D) -> Result<Vec<(String, String)>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct OrderedVisitor;

        impl<'de> Visitor<'de> for OrderedVisitor {
            type Value = Vec<(String, String)>;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a map of string keys to string values (preserving order)")
            }

            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut items = Vec::with_capacity(access.size_hint().unwrap_or(0));
                while let Some((k, v)) = access.next_entry::<String, String>()? {
                    items.push((k, v));
                }
                Ok(items)
            }
        }

        deserializer.deserialize_map(OrderedVisitor)
    }
}

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

    #[test]
    fn test_deser() {
        let yaml = r#"
name: example
label: Example
summary: Example Module
links:
  - https://github.com/asimov-platform/asimov.rs/tree/master/lib/asimov-module

requires:
    modules:
      - other
    models:
      hf:first/model: first_url
      hf:second/model:
        small: small_url
        medium: medium_url
        large: large_url

provides:
  programs:
    - asimov-example-module

handles:
  content_types:
    - content_type
  file_extensions:
    - file_extension
  url_patterns:
    - pattern
  url_prefixes:
    - prefix
  url_protocols:
    - protocol

config:
  variables:
    - name: api_key
      description: "api key to authorize requests"
      default_value: "foobar"
      environment: API_KEY

"#;

        let dec: ModuleManifest = serde_yaml_ng::from_str(yaml).expect("deser should succeed");

        assert_eq!(dec.name, "example");
        assert_eq!(dec.label.as_deref(), Some("Example"));
        assert_eq!(dec.summary.as_deref(), Some("Example Module"));

        assert_eq!(
            dec.links,
            vec!["https://github.com/asimov-platform/asimov.rs/tree/master/lib/asimov-module"],
        );

        assert_eq!(dec.provides.programs.len(), 1);
        assert_eq!(
            dec.provides.programs.first().unwrap(),
            "asimov-example-module",
        );

        assert_eq!(
            dec.handles
                .content_types
                .first()
                .expect("should have content_types"),
            "content_type",
        );

        assert_eq!(
            dec.handles
                .file_extensions
                .first()
                .expect("should have file_extensions"),
            "file_extension",
        );

        assert_eq!(
            dec.handles
                .url_patterns
                .first()
                .expect("should have url_patterns"),
            "pattern",
        );

        assert_eq!(
            dec.handles
                .url_prefixes
                .first()
                .expect("should have url_prefixes"),
            "prefix",
        );

        assert_eq!(
            dec.handles
                .url_protocols
                .first()
                .expect("should have url_protocols"),
            "protocol",
        );

        assert_eq!(
            dec.config.expect("should have config").variables.first(),
            Some(&ConfigurationVariable {
                name: "api_key".into(),
                description: Some("api key to authorize requests".into()),
                environment: Some("API_KEY".into()),
                default_value: Some("foobar".into())
            }),
        );

        let requires = dec.requires;

        assert_eq!(requires.modules.len(), 1);
        assert_eq!(requires.modules.first().unwrap(), "other");

        assert_eq!(requires.models.len(), 2);

        assert_eq!(
            requires.models["hf:first/model"],
            RequiredModel::Url("first_url".into()),
        );

        assert_eq!(
            requires.models["hf:second/model"],
            RequiredModel::Choices(vec![
                ("small".into(), "small_url".into()),
                ("medium".into(), "medium_url".into()),
                ("large".into(), "large_url".into())
            ]),
        );
    }
}