greentic-operator 0.4.34

Greentic operator CLI for local dev and demo orchestration.
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
use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::Context;
use greentic_types::{ExtensionInline, decode_pack_manifest};
use serde::Deserialize;
use zip::ZipArchive;

use crate::domains::Domain;

pub const EXT_CAPABILITIES_V1: &str = "greentic.ext.capabilities.v1";
pub const CAP_OP_HOOK_PRE: &str = "greentic.cap.op_hook.pre";
pub const CAP_OP_HOOK_POST: &str = "greentic.cap.op_hook.post";

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HookStage {
    Pre,
    Post,
}

impl HookStage {
    fn cap_id(&self) -> &'static str {
        match self {
            HookStage::Pre => CAP_OP_HOOK_PRE,
            HookStage::Post => CAP_OP_HOOK_POST,
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ResolveScope {
    pub env: Option<String>,
    pub tenant: Option<String>,
    pub team: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CapabilityPackRecord {
    pub pack_id: String,
    pub domain: Domain,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CapabilityBinding {
    pub cap_id: String,
    pub stable_id: String,
    pub pack_id: String,
    pub domain: Domain,
    pub pack_path: PathBuf,
    pub provider_component_ref: String,
    pub provider_op: String,
    pub version: String,
    pub requires_setup: bool,
    pub setup_qa_ref: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CapabilityOfferRecord {
    pub stable_id: String,
    pub pack_id: String,
    pub domain: Domain,
    pub pack_path: PathBuf,
    pub cap_id: String,
    pub version: String,
    pub provider_component_ref: String,
    pub provider_op: String,
    pub priority: i32,
    pub requires_setup: bool,
    pub setup_qa_ref: Option<String>,
    scope: CapabilityScopeV1,
    pub applies_to_ops: Vec<String>,
}

#[derive(Clone, Debug, Default)]
pub struct CapabilityRegistry {
    by_cap_id: BTreeMap<String, Vec<CapabilityOfferRecord>>,
}

impl CapabilityRegistry {
    pub fn build_from_pack_index(
        pack_index: &BTreeMap<PathBuf, CapabilityPackRecord>,
    ) -> anyhow::Result<Self> {
        let mut by_cap_id: BTreeMap<String, Vec<CapabilityOfferRecord>> = BTreeMap::new();

        for (pack_path, pack_record) in pack_index {
            let Some(ext) = read_capabilities_extension(pack_path)? else {
                continue;
            };

            for (idx, offer) in ext.offers.into_iter().enumerate() {
                let stable_id = match offer.offer_id {
                    Some(id) if !id.trim().is_empty() => id,
                    _ => format!(
                        "{}::{}::{}::{}::{}",
                        pack_record.pack_id,
                        offer.cap_id,
                        offer.provider.component_ref,
                        offer.provider.op,
                        idx
                    ),
                };
                let applies_to_ops = offer
                    .applies_to
                    .map(|value| value.op_names)
                    .unwrap_or_default();
                let setup_qa_ref = offer.setup.map(|value| value.qa_ref);
                by_cap_id
                    .entry(offer.cap_id.clone())
                    .or_default()
                    .push(CapabilityOfferRecord {
                        stable_id,
                        pack_id: pack_record.pack_id.clone(),
                        domain: pack_record.domain,
                        pack_path: pack_path.clone(),
                        cap_id: offer.cap_id,
                        version: offer.version,
                        provider_component_ref: offer.provider.component_ref,
                        provider_op: offer.provider.op,
                        priority: offer.priority,
                        requires_setup: offer.requires_setup,
                        setup_qa_ref,
                        scope: offer.scope.unwrap_or_default(),
                        applies_to_ops,
                    });
            }
        }

        for offers in by_cap_id.values_mut() {
            offers.sort_by(|a, b| {
                a.priority
                    .cmp(&b.priority)
                    .then_with(|| a.stable_id.cmp(&b.stable_id))
            });
        }

        Ok(Self { by_cap_id })
    }

    pub fn offers_for_capability(&self, cap_id: &str) -> &[CapabilityOfferRecord] {
        self.by_cap_id
            .get(cap_id)
            .map(Vec::as_slice)
            .unwrap_or_default()
    }

    pub fn resolve(
        &self,
        cap_id: &str,
        min_version: Option<&str>,
        scope: &ResolveScope,
    ) -> Option<CapabilityBinding> {
        let offers = self.by_cap_id.get(cap_id)?;
        let selected = offers.iter().find(|offer| {
            version_matches(&offer.version, min_version) && scope_matches(&offer.scope, scope)
        })?;
        Some(CapabilityBinding {
            cap_id: selected.cap_id.clone(),
            stable_id: selected.stable_id.clone(),
            pack_id: selected.pack_id.clone(),
            domain: selected.domain,
            pack_path: selected.pack_path.clone(),
            provider_component_ref: selected.provider_component_ref.clone(),
            provider_op: selected.provider_op.clone(),
            version: selected.version.clone(),
            requires_setup: selected.requires_setup,
            setup_qa_ref: selected.setup_qa_ref.clone(),
        })
    }

    pub fn resolve_hook_chain(&self, stage: HookStage, op_name: &str) -> Vec<CapabilityBinding> {
        self.by_cap_id
            .get(stage.cap_id())
            .map(|offers| {
                offers
                    .iter()
                    .filter(|offer| {
                        offer.applies_to_ops.is_empty()
                            || offer.applies_to_ops.iter().any(|entry| entry == op_name)
                    })
                    .map(|selected| CapabilityBinding {
                        cap_id: selected.cap_id.clone(),
                        stable_id: selected.stable_id.clone(),
                        pack_id: selected.pack_id.clone(),
                        domain: selected.domain,
                        pack_path: selected.pack_path.clone(),
                        provider_component_ref: selected.provider_component_ref.clone(),
                        provider_op: selected.provider_op.clone(),
                        version: selected.version.clone(),
                        requires_setup: selected.requires_setup,
                        setup_qa_ref: selected.setup_qa_ref.clone(),
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default()
    }

    pub fn offers_requiring_setup(&self, scope: &ResolveScope) -> Vec<CapabilityOfferRecord> {
        let mut selected = Vec::new();
        for offers in self.by_cap_id.values() {
            for offer in offers {
                if !offer.requires_setup {
                    continue;
                }
                if !scope_matches(&offer.scope, scope) {
                    continue;
                }
                selected.push(offer.clone());
            }
        }
        selected.sort_by(|a, b| {
            a.priority
                .cmp(&b.priority)
                .then_with(|| a.stable_id.cmp(&b.stable_id))
        });
        selected
    }
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct CapabilityInstallRecord {
    pub cap_id: String,
    pub stable_id: String,
    pub pack_id: String,
    pub status: String,
    pub config_state_keys: Vec<String>,
    pub timestamp_unix_sec: u64,
}

impl CapabilityInstallRecord {
    pub fn ready(cap_id: &str, stable_id: &str, pack_id: &str) -> Self {
        Self {
            cap_id: cap_id.to_string(),
            stable_id: stable_id.to_string(),
            pack_id: pack_id.to_string(),
            status: "ready".to_string(),
            config_state_keys: Vec::new(),
            timestamp_unix_sec: now_unix_sec(),
        }
    }

    pub fn failed(cap_id: &str, stable_id: &str, pack_id: &str, key: &str) -> Self {
        Self {
            cap_id: cap_id.to_string(),
            stable_id: stable_id.to_string(),
            pack_id: pack_id.to_string(),
            status: "failed".to_string(),
            config_state_keys: vec![key.to_string()],
            timestamp_unix_sec: now_unix_sec(),
        }
    }
}

pub fn install_record_path(
    bundle_root: &Path,
    tenant: &str,
    team: Option<&str>,
    stable_id: &str,
) -> PathBuf {
    let team = team.unwrap_or("default");
    bundle_root
        .join("state")
        .join("runtime")
        .join(tenant)
        .join(team)
        .join("capabilities")
        .join(format!("{stable_id}.install.json"))
}

pub fn write_install_record(
    bundle_root: &Path,
    tenant: &str,
    team: Option<&str>,
    record: &CapabilityInstallRecord,
) -> anyhow::Result<PathBuf> {
    let path = install_record_path(bundle_root, tenant, team, &record.stable_id);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let bytes = serde_json::to_vec_pretty(record)?;
    std::fs::write(&path, bytes)?;
    Ok(path)
}

pub fn read_install_record(
    bundle_root: &Path,
    tenant: &str,
    team: Option<&str>,
    stable_id: &str,
) -> anyhow::Result<Option<CapabilityInstallRecord>> {
    let path = install_record_path(bundle_root, tenant, team, stable_id);
    if !path.exists() {
        return Ok(None);
    }
    let bytes = std::fs::read(path)?;
    let record: CapabilityInstallRecord = serde_json::from_slice(&bytes)?;
    Ok(Some(record))
}

pub fn is_binding_ready(
    bundle_root: &Path,
    tenant: &str,
    team: Option<&str>,
    binding: &CapabilityBinding,
) -> anyhow::Result<bool> {
    if !binding.requires_setup {
        return Ok(true);
    }
    let Some(record) = read_install_record(bundle_root, tenant, team, &binding.stable_id)? else {
        return Ok(false);
    };
    Ok(record.status.eq_ignore_ascii_case("ready"))
}

fn read_capabilities_extension(path: &Path) -> anyhow::Result<Option<CapabilitiesExtensionV1>> {
    let file = std::fs::File::open(path)?;
    let mut archive = ZipArchive::new(file)?;
    let mut manifest_entry = archive.by_name("manifest.cbor").map_err(|err| {
        anyhow::anyhow!("failed to open manifest.cbor in {}: {err}", path.display())
    })?;
    let mut bytes = Vec::new();
    manifest_entry.read_to_end(&mut bytes)?;
    let manifest = decode_pack_manifest(&bytes)
        .with_context(|| format!("failed to decode pack manifest in {}", path.display()))?;
    let Some(extension) = manifest
        .extensions
        .as_ref()
        .and_then(|extensions| extensions.get(EXT_CAPABILITIES_V1))
    else {
        return Ok(None);
    };
    let inline = extension
        .inline
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("capabilities extension inline payload missing"))?;
    let ExtensionInline::Other(value) = inline else {
        anyhow::bail!("capabilities extension inline payload has unexpected type");
    };
    let decoded: CapabilitiesExtensionV1 = serde_json::from_value(value.clone())
        .with_context(|| "failed to parse greentic.ext.capabilities.v1 payload")?;
    if decoded.schema_version != 1 {
        anyhow::bail!(
            "unsupported capabilities extension schema_version={}",
            decoded.schema_version
        );
    }
    Ok(Some(decoded))
}

fn version_matches(version: &str, min_version: Option<&str>) -> bool {
    match min_version {
        None => true,
        Some(requested) => version == requested,
    }
}

fn scope_matches(offer_scope: &CapabilityScopeV1, scope: &ResolveScope) -> bool {
    value_matches(&offer_scope.envs, scope.env.as_deref())
        && value_matches(&offer_scope.tenants, scope.tenant.as_deref())
        && value_matches(&offer_scope.teams, scope.team.as_deref())
}

fn value_matches(values: &[String], current: Option<&str>) -> bool {
    if values.is_empty() {
        return true;
    }
    let Some(current) = current else {
        return false;
    };
    values.iter().any(|value| value == current)
}

#[derive(Debug, Deserialize)]
struct CapabilitiesExtensionV1 {
    #[serde(default = "default_schema_version")]
    schema_version: u32,
    #[serde(default)]
    offers: Vec<CapabilityOfferV1>,
}

#[derive(Debug, Deserialize)]
struct CapabilityOfferV1 {
    #[serde(default)]
    offer_id: Option<String>,
    cap_id: String,
    version: String,
    provider: CapabilityProviderRefV1,
    #[serde(default)]
    scope: Option<CapabilityScopeV1>,
    #[serde(default)]
    priority: i32,
    #[serde(default)]
    requires_setup: bool,
    #[serde(default)]
    setup: Option<CapabilitySetupV1>,
    #[serde(default)]
    applies_to: Option<HookAppliesToV1>,
}

#[derive(Debug, Deserialize)]
struct CapabilityProviderRefV1 {
    component_ref: String,
    op: String,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
struct CapabilityScopeV1 {
    #[serde(default)]
    envs: Vec<String>,
    #[serde(default)]
    tenants: Vec<String>,
    #[serde(default)]
    teams: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct CapabilitySetupV1 {
    qa_ref: String,
}

#[derive(Debug, Deserialize)]
struct HookAppliesToV1 {
    #[serde(default)]
    op_names: Vec<String>,
}

const fn default_schema_version() -> u32 {
    1
}

fn now_unix_sec() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|value| value.as_secs())
        .unwrap_or(0)
}

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

    #[test]
    fn scope_matching_accepts_unrestricted_scope() {
        let offer_scope = CapabilityScopeV1::default();
        let scope = ResolveScope::default();
        assert!(scope_matches(&offer_scope, &scope));
    }

    #[test]
    fn scope_matching_rejects_missing_restricted_value() {
        let offer_scope = CapabilityScopeV1 {
            envs: vec!["prod".to_string()],
            tenants: Vec::new(),
            teams: Vec::new(),
        };
        let scope = ResolveScope::default();
        assert!(!scope_matches(&offer_scope, &scope));
    }

    #[test]
    fn value_matching_handles_lists() {
        assert!(value_matches(&[], None));
        assert!(value_matches(&["demo".to_string()], Some("demo")));
        assert!(!value_matches(&["demo".to_string()], Some("prod")));
    }

    #[test]
    fn install_record_roundtrip() {
        let tmp = tempdir().expect("tempdir");
        let record =
            CapabilityInstallRecord::ready("greentic.cap.test", "offer.test.01", "pack-test");
        let path = write_install_record(tmp.path(), "tenant-a", Some("team-b"), &record)
            .expect("write install record");
        assert!(path.exists());
        let loaded = read_install_record(tmp.path(), "tenant-a", Some("team-b"), "offer.test.01")
            .expect("read install record")
            .expect("record should exist");
        assert_eq!(loaded.cap_id, record.cap_id);
        assert_eq!(loaded.status, "ready");
    }

    #[test]
    fn setup_required_binding_reports_not_ready_without_record() {
        let tmp = tempdir().expect("tempdir");
        let binding = CapabilityBinding {
            cap_id: "greentic.cap.test".to_string(),
            stable_id: "offer.setup.01".to_string(),
            pack_id: "pack-test".to_string(),
            domain: Domain::Messaging,
            pack_path: tmp.path().join("dummy.gtpack"),
            provider_component_ref: "component".to_string(),
            provider_op: "invoke".to_string(),
            version: "v1".to_string(),
            requires_setup: true,
            setup_qa_ref: Some("qa/setup.cbor".to_string()),
        };
        let ready = is_binding_ready(tmp.path(), "tenant-a", Some("team-b"), &binding)
            .expect("ready check");
        assert!(!ready);
    }
}