spoke-operations 0.6.1

SPOKE lifecycle helpers — pure functions over spoke-schemas wire types
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
//! Capability-sliced adapter port contracts for injection orchestration.
//! Synchronous `SpokeResult` surface — adapters own async I/O behind this boundary.

use crate::result::SpokeResult;
use spoke_schemas::{
    ComputeRequest, ComputeResponse, Finding, HostCapabilityManifest, KnowledgeEntry,
    ProjectRequest, ProjectResponse, Relation, Rule, Scope, TimelineEvent,
};

/// Knowledge entry persistence — get / put by entry id.
pub trait KnowledgeEntryPort {
    fn get_knowledge_entry(&self, entry_id: &str) -> SpokeResult<KnowledgeEntry>;
    /// Persist a KnowledgeEntry with optimistic concurrency control.
    ///
    /// Adapters MUST treat `expected_base_revision` as the store’s required current
    /// revision before accepting the write (conditional put / OCC / CAS).
    /// `None` means the entry must be absent (create). A non-null value means the
    /// store’s current revision for `entry.entry_id` MUST equal
    /// `expected_base_revision`; otherwise reject with `STORED_REVISION_STALE` or
    /// `REVISION_CONFLICT`. True concurrent safety requires atomic compare-and-put
    /// in the adapter; the library stays I/O-free.
    fn put_knowledge_entry(
        &self,
        entry: KnowledgeEntry,
        expected_base_revision: Option<u64>,
    ) -> SpokeResult<KnowledgeEntry>;
}

/// Relation persistence — get / put by relation id.
pub trait RelationPort {
    fn get_relation(&self, relation_id: &str) -> SpokeResult<Relation>;
    /// Persist a Relation with optimistic concurrency control.
    ///
    /// Adapters MUST treat `expected_base_revision` as the store’s required current
    /// revision before accepting the write (conditional put / OCC / CAS).
    /// `None` means the relation must be absent (create). A non-null value means the
    /// store’s current revision for `relation.relation_id` MUST equal
    /// `expected_base_revision`; otherwise reject with `STORED_REVISION_STALE` or
    /// `REVISION_CONFLICT`. True concurrent safety requires atomic compare-and-put
    /// in the adapter; the library stays I/O-free.
    ///
    /// Revision assignment is adapter-owned: on create
    /// (`expected_base_revision` `None`) the adapter MUST seed `revision = 1`;
    /// on an accepted update it MUST persist `revision = stored + 1`. The
    /// returned Relation carries the assigned revision — callers must not set
    /// it themselves.
    fn put_relation(
        &self,
        relation: Relation,
        expected_base_revision: Option<u64>,
    ) -> SpokeResult<Relation>;
}

/// Scope query for check / assemble — knowledge entries and timeline events.
pub trait ScopeQueryPort {
    fn list_knowledge_entries(&self, scope: &Scope) -> SpokeResult<Vec<KnowledgeEntry>>;
    fn list_timeline_events(&self, scope: &Scope) -> SpokeResult<Vec<TimelineEvent>>;
}

/// Finding persistence.
pub trait FindingPort {
    fn put_findings(&self, findings: Vec<Finding>) -> SpokeResult<Vec<Finding>>;
}

/// Rule query by reference list.
pub trait RuleQueryPort {
    fn list_rules(&self, rule_refs: &[String]) -> SpokeResult<Vec<Rule>>;
}

/// Host collaboration metadata — self manifest and product-known peer manifests.
///
/// Integrators call explicitly; orchestrators do not auto-fetch manifests.
pub trait HostManifestPort {
    fn get_host_capability_manifest(&self) -> SpokeResult<HostCapabilityManifest>;
    fn list_peer_host_capability_manifests(&self) -> SpokeResult<Vec<HostCapabilityManifest>>;
}

/// Optional l2-computable session — project / compute.
pub trait ComputablePort {
    fn project(&self, request: ProjectRequest) -> SpokeResult<ProjectResponse>;
    fn compute(&self, request: ComputeRequest) -> SpokeResult<ComputeResponse>;
}

/// Optional l5-fork timeline query.
///
/// Capability-specific refinement of [`ScopeQueryPort`]; one type MAY satisfy both.
pub trait ForkTimelineQueryPort {
    fn list_fork_timeline_events(&self, scope: &Scope) -> SpokeResult<Vec<TimelineEvent>>;
}

/// Ports required for spoke-baseline orchestration.
pub trait BaselinePorts:
    KnowledgeEntryPort
    + RelationPort
    + ScopeQueryPort
    + FindingPort
    + RuleQueryPort
    + HostManifestPort
{
}

impl<T> BaselinePorts for T where
    T: KnowledgeEntryPort
        + RelationPort
        + ScopeQueryPort
        + FindingPort
        + RuleQueryPort
        + HostManifestPort
{
}

/// Baseline plus optional computable capability.
///
/// Types that implement [`ComputablePort`] get a blanket availability probe.
/// Baseline-only types MAY implement this trait returning `None` for dynamically
/// assembled boundaries (parity with TS `requirePortMethod`).
pub trait ComputablePorts: BaselinePorts {
    fn as_computable(&self) -> Option<&dyn ComputablePort>;
}

impl<T> ComputablePorts for T
where
    T: BaselinePorts + ComputablePort,
{
    fn as_computable(&self) -> Option<&dyn ComputablePort> {
        Some(self)
    }
}

/// Baseline plus optional fork timeline capability.
pub trait ForkPorts: BaselinePorts {
    fn as_fork_timeline(&self) -> Option<&dyn ForkTimelineQueryPort>;
}

impl<T> ForkPorts for T
where
    T: BaselinePorts + ForkTimelineQueryPort,
{
    fn as_fork_timeline(&self) -> Option<&dyn ForkTimelineQueryPort> {
        Some(self)
    }
}

/// Full composition of baseline, computable, and fork ports.
pub trait FullPorts: ComputablePorts + ForkPorts {}

impl<T> FullPorts for T where T: ComputablePorts + ForkPorts {}

/// Ergonomic marker for baseline adapter composition.
pub trait BaselineAdapter: BaselinePorts {}

impl<T: BaselinePorts> BaselineAdapter for T {}

/// Ergonomic marker for baseline plus computable adapter composition.
pub trait ComputableAdapter: ComputablePorts {}

impl<T: ComputablePorts> ComputableAdapter for T {}

/// Ergonomic marker for baseline plus fork adapter composition.
pub trait ForkAdapter: ForkPorts {}

impl<T: ForkPorts> ForkAdapter for T {}

/// Ergonomic marker for full adapter composition.
pub trait FullAdapter: FullPorts {}

impl<T: FullPorts> FullAdapter for T {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{spoke_ok, SpokeRejectCode};
    use serde_json::json;
    use std::collections::HashMap;

    fn make_manifest(
        host_id: &str,
        namespaces: &[&str],
        roles: &[&str],
    ) -> HostCapabilityManifest {
        serde_json::from_value(json!({
            "schema_version": 1,
            "host_id": host_id,
            "roles": roles,
            "capabilities": ["spoke-baseline"],
            "namespaces": namespaces,
            "extensions": {}
        }))
        .expect("valid HostCapabilityManifest")
    }

    fn normalize_peer_manifests(
        self_host_id: &str,
        peers: &[HostCapabilityManifest],
    ) -> Vec<HostCapabilityManifest> {
        let mut by_host_id: HashMap<String, HostCapabilityManifest> = HashMap::new();
        for peer in peers {
            if peer.host_id.as_str() == self_host_id {
                continue;
            }
            by_host_id.insert(peer.host_id.as_str().to_string(), peer.clone());
        }
        let mut normalized: Vec<HostCapabilityManifest> = by_host_id.into_values().collect();
        normalized.sort_by(|left, right| left.host_id.as_str().cmp(right.host_id.as_str()));
        normalized
    }

    struct HostManifestPortMock {
        self_manifest: HostCapabilityManifest,
        raw_peers: Vec<HostCapabilityManifest>,
    }

    impl HostManifestPortMock {
        fn new(
            self_manifest: HostCapabilityManifest,
            raw_peers: Vec<HostCapabilityManifest>,
        ) -> Self {
            Self {
                self_manifest,
                raw_peers,
            }
        }
    }

    impl HostManifestPort for HostManifestPortMock {
        fn get_host_capability_manifest(&self) -> SpokeResult<HostCapabilityManifest> {
            spoke_ok(self.self_manifest.clone())
        }

        fn list_peer_host_capability_manifests(&self) -> SpokeResult<Vec<HostCapabilityManifest>> {
            spoke_ok(normalize_peer_manifests(
                self.self_manifest.host_id.as_str(),
                &self.raw_peers,
            ))
        }
    }

    struct BaselinePortStub {
        host_manifest: HostManifestPortMock,
    }

    impl BaselinePortStub {
        fn new(host_manifest: HostManifestPortMock) -> Self {
            Self { host_manifest }
        }
    }

    impl KnowledgeEntryPort for BaselinePortStub {
        fn get_knowledge_entry(&self, _entry_id: &str) -> SpokeResult<KnowledgeEntry> {
            unreachable!("baseline port stub")
        }

        fn put_knowledge_entry(
            &self,
            entry: KnowledgeEntry,
            _expected_base_revision: Option<u64>,
        ) -> SpokeResult<KnowledgeEntry> {
            spoke_ok(entry)
        }
    }

    impl RelationPort for BaselinePortStub {
        fn get_relation(&self, _relation_id: &str) -> SpokeResult<Relation> {
            unreachable!("baseline port stub")
        }

        fn put_relation(
            &self,
            relation: Relation,
            _expected_base_revision: Option<u64>,
        ) -> SpokeResult<Relation> {
            spoke_ok(relation)
        }
    }

    impl ScopeQueryPort for BaselinePortStub {
        fn list_knowledge_entries(&self, _scope: &Scope) -> SpokeResult<Vec<KnowledgeEntry>> {
            spoke_ok(Vec::new())
        }

        fn list_timeline_events(&self, _scope: &Scope) -> SpokeResult<Vec<TimelineEvent>> {
            spoke_ok(Vec::new())
        }
    }

    impl FindingPort for BaselinePortStub {
        fn put_findings(&self, findings: Vec<Finding>) -> SpokeResult<Vec<Finding>> {
            spoke_ok(findings)
        }
    }

    impl RuleQueryPort for BaselinePortStub {
        fn list_rules(&self, _rule_refs: &[String]) -> SpokeResult<Vec<Rule>> {
            spoke_ok(Vec::new())
        }
    }

    impl HostManifestPort for BaselinePortStub {
        fn get_host_capability_manifest(&self) -> SpokeResult<HostCapabilityManifest> {
            self.host_manifest.get_host_capability_manifest()
        }

        fn list_peer_host_capability_manifests(&self) -> SpokeResult<Vec<HostCapabilityManifest>> {
            self.host_manifest.list_peer_host_capability_manifests()
        }
    }

    #[test]
    fn capability_port_missing_is_twentieth_spoke_reject_code() {
        assert_eq!(
            SpokeRejectCode::CapabilityPortMissing.as_str(),
            "CAPABILITY_PORT_MISSING"
        );
        assert_eq!(
            SpokeRejectCode::try_from_str("CAPABILITY_PORT_MISSING"),
            Some(SpokeRejectCode::CapabilityPortMissing)
        );
    }

    #[test]
    fn baseline_ports_accepts_all_six_baseline_families() {
        let ports = BaselinePortStub::new(HostManifestPortMock::new(
            make_manifest("self-host", &["self-ns"], &["data-store"]),
            Vec::new(),
        ));

        let _: &dyn BaselinePorts = &ports;
        let _: &dyn KnowledgeEntryPort = &ports;
        let _: &dyn RelationPort = &ports;
        let _: &dyn ScopeQueryPort = &ports;
        let _: &dyn FindingPort = &ports;
        let _: &dyn RuleQueryPort = &ports;
        let _: &dyn HostManifestPort = &ports;
    }

    #[test]
    fn host_manifest_port_returns_self_manifest() {
        let self_manifest = make_manifest(
            "adapter-self",
            &["alpha"],
            &["data-store", "checker"],
        );
        let ports = HostManifestPortMock::new(self_manifest.clone(), Vec::new());

        let result = ports.get_host_capability_manifest();

        match result {
            SpokeResult::Ok(value) => assert_eq!(value.host_id.as_str(), "adapter-self"),
            SpokeResult::Reject(_) => panic!("expected ok"),
        }
    }

    #[test]
    fn host_manifest_port_accepts_empty_peer_list() {
        let ports = HostManifestPortMock::new(
            make_manifest("self-host", &["default"], &["data-store"]),
            Vec::new(),
        );

        let result = ports.list_peer_host_capability_manifests();

        match result {
            SpokeResult::Ok(value) => assert!(value.is_empty()),
            SpokeResult::Reject(_) => panic!("expected ok"),
        }
    }

    #[test]
    fn host_manifest_port_returns_seeded_peers_with_disjoint_namespaces() {
        let self_manifest = make_manifest("self-host", &["self-ns"], &["data-store"]);
        let peer_a = make_manifest("peer-a", &["peer-a-ns"], &["checker"]);
        let peer_b = make_manifest("peer-b", &["peer-b-ns"], &["assembler"]);
        let ports = HostManifestPortMock::new(self_manifest, vec![peer_b.clone(), peer_a.clone()]);

        let result = ports.list_peer_host_capability_manifests();

        match result {
            SpokeResult::Ok(value) => {
                assert_eq!(value.len(), 2);
                assert_eq!(value[0].host_id.as_str(), "peer-a");
                assert_eq!(value[1].host_id.as_str(), "peer-b");
                let namespaces: Vec<&str> = value
                    .iter()
                    .flat_map(|manifest| manifest.namespaces.iter().map(|ns| ns.as_str()))
                    .collect();
                let unique: std::collections::HashSet<_> = namespaces.iter().copied().collect();
                assert_eq!(namespaces.len(), unique.len());
                assert!(!namespaces.contains(&"self-ns"));
            }
            SpokeResult::Reject(_) => panic!("expected ok"),
        }
    }

    #[test]
    fn host_manifest_port_excludes_self_dedupes_and_sorts_peers() {
        let self_manifest = make_manifest("self-host", &["self-ns"], &["data-store"]);
        let peer_z = make_manifest("peer-z", &["z-ns"], &["data-store"]);
        let peer_a_dupe = make_manifest("peer-a", &["a-ns-dup"], &["checker"]);
        let peer_a = make_manifest("peer-a", &["a-ns"], &["assembler"]);
        let ports = HostManifestPortMock::new(
            self_manifest.clone(),
            vec![peer_z.clone(), self_manifest, peer_a_dupe, peer_a.clone()],
        );

        let result = ports.list_peer_host_capability_manifests();

        match result {
            SpokeResult::Ok(value) => {
                let host_ids: Vec<&str> = value.iter().map(|m| m.host_id.as_str()).collect();
                assert_eq!(host_ids, vec!["peer-a", "peer-z"]);
                assert_eq!(value[0].roles, peer_a.roles);
            }
            SpokeResult::Reject(_) => panic!("expected ok"),
        }
    }
}