use async_trait::async_trait;
use crate::result::SpokeResult;
use crate::history::HistoryPruneResult;
use serde_json::Value;
use spoke_schemas::{
ComputeRequest, ComputeResponse, ExtractRequest, Finding, HostCapabilityManifest,
KnowledgeAdoptRequest, KnowledgeAdoptResponse, KnowledgeEntry, MemoryCandidatesDismissRequest,
MemoryCandidatesDismissResponse,
MemoryCandidatesGetRequest, MemoryCandidatesGetResponse, MemoryCandidatesListRequest,
MemoryCandidatesListResponse, MemoryCandidatesReviewRequest, MemoryCandidatesReviewResponse,
MemoryCaptureRequest, MemoryCaptureResponse, MemoryDescribeRequest, MemoryDescribeResponse,
MemoryExportsCreateRequest, MemoryExportsCreateResponse, MemoryExportsGetRequest,
MemoryExportsGetResponse, MemoryGrantsGrantRequest, MemoryGrantsGrantResponse,
MemoryGrantsListRequest, MemoryGrantsListResponse, MemoryGrantsRevokeRequest,
MemoryGrantsRevokeResponse, MemoryImportsActivateRequest, MemoryImportsActivateResponse,
MemoryImportsDiscardRequest, MemoryImportsDiscardResponse, MemoryImportsStageRequest,
MemoryImportsStageResponse, MemoryProfileGetRequest, MemoryProfileGetResponse,
MemoryProfileUpdateRequest, MemoryProfileUpdateResponse, MemoryRecallRequest,
MemoryRecallResponse, MemoryReceiptsGetRequest, MemoryReceiptsGetResponse,
MemoryRecordsCreateRequest, MemoryRecordsCreateResponse, MemoryRecordsDeleteRequest,
MemoryRecordsDeleteResponse, MemoryRecordsGetRequest, MemoryRecordsGetResponse,
MemoryRecordsListRequest, MemoryRecordsListResponse, MemoryRecordsPromoteRequest,
MemoryRecordsPromoteResponse, MemoryRecordsUpdateRequest, MemoryRecordsUpdateResponse,
MemoryReflectionsGenerateRequest, MemoryReflectionsGenerateResponse,
MemoryReflectionsListRequest, MemoryReflectionsListResponse, MemoryReflectionsStateRequest,
MemoryReflectionsStateResponse, MemorySpacesFreezeRequest, MemorySpacesFreezeResponse,
MemorySpacesListRequest, MemorySpacesListResponse, MemorySpacesUnfreezeRequest,
MemorySpacesUnfreezeResponse, MemorySubjectsEnsureRequest, MemorySubjectsEnsureResponse,
MemorySubjectsFenceRequest, MemorySubjectsFenceResponse, MemorySubjectsGetRequest,
MemorySubjectsGetResponse, Principal, ProjectRequest, ProjectResponse, Relation,
RevisionSnapshot, Rule, Scope, TimelineEvent,
};
#[async_trait]
pub trait KnowledgeEntryPort {
async fn get_knowledge_entry(&self, entry_id: &str) -> SpokeResult<KnowledgeEntry>;
async fn put_knowledge_entry(
&self,
entry: KnowledgeEntry,
expected_base_revision: Option<u64>,
) -> SpokeResult<KnowledgeEntry>;
}
#[async_trait]
pub trait RelationPort {
async fn get_relation(&self, relation_id: &str) -> SpokeResult<Relation>;
async fn put_relation(
&self,
relation: Relation,
expected_base_revision: Option<u64>,
) -> SpokeResult<Relation>;
}
#[async_trait]
pub trait ScopeQueryPort {
async fn list_timeline_events(&self, scope: &Scope) -> SpokeResult<Vec<TimelineEvent>>;
}
#[async_trait]
pub trait KnowledgeQueryPort: Send + Sync {
async fn list_knowledge_entries(&self, scope: &Scope) -> SpokeResult<Vec<KnowledgeEntry>>;
}
#[async_trait]
pub trait ScopedKnowledgePort: Send + Sync {
async fn get_scoped_knowledge_entry(
&self,
scope: &Scope,
entry_id: &str,
) -> SpokeResult<KnowledgeEntry>;
async fn put_scoped_knowledge_entry(
&self,
scope: &Scope,
entry: KnowledgeEntry,
expected_base_revision: Option<u64>,
) -> SpokeResult<KnowledgeEntry>;
async fn list_scoped_knowledge_entries(
&self,
scope: &Scope,
) -> SpokeResult<Vec<KnowledgeEntry>>;
}
#[async_trait]
pub trait FindingPort {
async fn put_findings(&self, findings: Vec<Finding>) -> SpokeResult<Vec<Finding>>;
}
#[async_trait]
pub trait RuleQueryPort {
async fn list_rules(&self, rule_refs: &[String]) -> SpokeResult<Vec<Rule>>;
}
#[async_trait]
pub trait HostManifestPort {
async fn get_host_capability_manifest(&self) -> SpokeResult<HostCapabilityManifest>;
async fn list_peer_host_capability_manifests(&self) -> SpokeResult<Vec<HostCapabilityManifest>>;
}
#[async_trait]
pub trait ComputablePort {
async fn project(&self, request: ProjectRequest) -> SpokeResult<ProjectResponse>;
async fn compute(&self, request: ComputeRequest) -> SpokeResult<ComputeResponse>;
}
#[async_trait]
pub trait ForkTimelineQueryPort {
async fn list_fork_timeline_events(&self, scope: &Scope) -> SpokeResult<Vec<TimelineEvent>>;
}
pub trait BaselinePorts:
KnowledgeEntryPort
+ KnowledgeQueryPort
+ RelationPort
+ ScopeQueryPort
+ FindingPort
+ RuleQueryPort
+ HostManifestPort
{
}
impl<T> BaselinePorts for T where
T: KnowledgeEntryPort
+ KnowledgeQueryPort
+ RelationPort
+ ScopeQueryPort
+ FindingPort
+ RuleQueryPort
+ HostManifestPort
{
}
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)
}
}
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)
}
}
pub trait FullPorts: ComputablePorts + ForkPorts {}
impl<T> FullPorts for T where T: ComputablePorts + ForkPorts {}
pub trait BaselineAdapter: BaselinePorts {}
impl<T: BaselinePorts> BaselineAdapter for T {}
pub trait ComputableAdapter: ComputablePorts {}
impl<T: ComputablePorts> ComputableAdapter for T {}
pub trait ForkAdapter: ForkPorts {}
impl<T: ForkPorts> ForkAdapter for T {}
pub trait FullAdapter: FullPorts {}
impl<T: FullPorts> FullAdapter for T {}
#[async_trait]
pub trait ExtractionPort {
async fn load_extraction_input(&self, request: &ExtractRequest) -> SpokeResult<Value>;
}
#[derive(Debug, Clone)]
pub struct ExtractRunInput {
pub request: ExtractRequest,
pub input: Value,
}
#[derive(Debug, Clone)]
pub struct ExtractionResult {
pub candidates: Vec<KnowledgeEntry>,
pub method: Option<String>,
pub coverage_hint: Option<Value>,
}
#[async_trait]
pub trait MemoryPort {
async fn describe(
&self,
principal: &Principal,
request: MemoryDescribeRequest,
) -> SpokeResult<MemoryDescribeResponse>;
async fn list_spaces(
&self,
principal: &Principal,
request: MemorySpacesListRequest,
) -> SpokeResult<MemorySpacesListResponse>;
async fn freeze_space(
&self,
principal: &Principal,
request: MemorySpacesFreezeRequest,
) -> SpokeResult<MemorySpacesFreezeResponse>;
async fn unfreeze_space(
&self,
principal: &Principal,
request: MemorySpacesUnfreezeRequest,
) -> SpokeResult<MemorySpacesUnfreezeResponse>;
async fn ensure_subject(
&self,
principal: &Principal,
request: MemorySubjectsEnsureRequest,
) -> SpokeResult<MemorySubjectsEnsureResponse>;
async fn get_subject(
&self,
principal: &Principal,
request: MemorySubjectsGetRequest,
) -> SpokeResult<MemorySubjectsGetResponse>;
async fn fence_subject(
&self,
principal: &Principal,
request: MemorySubjectsFenceRequest,
) -> SpokeResult<MemorySubjectsFenceResponse>;
async fn list_grants(
&self,
principal: &Principal,
request: MemoryGrantsListRequest,
) -> SpokeResult<MemoryGrantsListResponse>;
async fn grant(
&self,
principal: &Principal,
request: MemoryGrantsGrantRequest,
) -> SpokeResult<MemoryGrantsGrantResponse>;
async fn revoke_grant(
&self,
principal: &Principal,
request: MemoryGrantsRevokeRequest,
) -> SpokeResult<MemoryGrantsRevokeResponse>;
async fn capture(
&self,
principal: &Principal,
request: MemoryCaptureRequest,
) -> SpokeResult<MemoryCaptureResponse>;
async fn list_candidates(
&self,
principal: &Principal,
request: MemoryCandidatesListRequest,
) -> SpokeResult<MemoryCandidatesListResponse>;
async fn get_candidate(
&self,
principal: &Principal,
request: MemoryCandidatesGetRequest,
) -> SpokeResult<MemoryCandidatesGetResponse>;
async fn dismiss_candidate(
&self,
principal: &Principal,
request: MemoryCandidatesDismissRequest,
) -> SpokeResult<MemoryCandidatesDismissResponse>;
async fn review_candidate(
&self,
principal: &Principal,
request: MemoryCandidatesReviewRequest,
) -> SpokeResult<MemoryCandidatesReviewResponse>;
async fn create_record(
&self,
principal: &Principal,
request: MemoryRecordsCreateRequest,
) -> SpokeResult<MemoryRecordsCreateResponse>;
async fn get_record(
&self,
principal: &Principal,
request: MemoryRecordsGetRequest,
) -> SpokeResult<MemoryRecordsGetResponse>;
async fn update_record(
&self,
principal: &Principal,
request: MemoryRecordsUpdateRequest,
) -> SpokeResult<MemoryRecordsUpdateResponse>;
async fn delete_record(
&self,
principal: &Principal,
request: MemoryRecordsDeleteRequest,
) -> SpokeResult<MemoryRecordsDeleteResponse>;
async fn list_records(
&self,
principal: &Principal,
request: MemoryRecordsListRequest,
) -> SpokeResult<MemoryRecordsListResponse>;
async fn promote_record(
&self,
principal: &Principal,
request: MemoryRecordsPromoteRequest,
) -> SpokeResult<MemoryRecordsPromoteResponse>;
async fn recall(
&self,
principal: &Principal,
request: MemoryRecallRequest,
) -> SpokeResult<MemoryRecallResponse>;
async fn get_profile(
&self,
principal: &Principal,
request: MemoryProfileGetRequest,
) -> SpokeResult<MemoryProfileGetResponse>;
async fn update_profile(
&self,
principal: &Principal,
request: MemoryProfileUpdateRequest,
) -> SpokeResult<MemoryProfileUpdateResponse>;
async fn get_reflection_state(
&self,
principal: &Principal,
request: MemoryReflectionsStateRequest,
) -> SpokeResult<MemoryReflectionsStateResponse>;
async fn list_reflections(
&self,
principal: &Principal,
request: MemoryReflectionsListRequest,
) -> SpokeResult<MemoryReflectionsListResponse>;
async fn generate_reflection(
&self,
principal: &Principal,
request: MemoryReflectionsGenerateRequest,
) -> SpokeResult<MemoryReflectionsGenerateResponse>;
async fn get_receipt(
&self,
principal: &Principal,
request: MemoryReceiptsGetRequest,
) -> SpokeResult<MemoryReceiptsGetResponse>;
async fn create_export(
&self,
principal: &Principal,
request: MemoryExportsCreateRequest,
) -> SpokeResult<MemoryExportsCreateResponse>;
async fn get_export(
&self,
principal: &Principal,
request: MemoryExportsGetRequest,
) -> SpokeResult<MemoryExportsGetResponse>;
async fn stage_import(
&self,
principal: &Principal,
request: MemoryImportsStageRequest,
) -> SpokeResult<MemoryImportsStageResponse>;
async fn activate_import(
&self,
principal: &Principal,
request: MemoryImportsActivateRequest,
) -> SpokeResult<MemoryImportsActivateResponse>;
async fn discard_import(
&self,
principal: &Principal,
request: MemoryImportsDiscardRequest,
) -> SpokeResult<MemoryImportsDiscardResponse>;
}
pub trait MemoryPorts {
fn as_memory(&self) -> Option<&dyn MemoryPort> {
None
}
}
impl<T> MemoryPorts for T
where
T: MemoryPort,
{
fn as_memory(&self) -> Option<&dyn MemoryPort> {
Some(self)
}
}
#[async_trait]
pub trait HistoryPort: Send + Sync {
async fn get_history_snapshot(
&self,
principal: &Principal,
scope: &Scope,
entity_kind: &str,
entity_id: &str,
revision: u64,
) -> SpokeResult<RevisionSnapshot>;
async fn prune_history(
&self,
principal: &Principal,
scope: &Scope,
entity_kind: &str,
entity_id: &str,
keep: u64,
) -> SpokeResult<HistoryPruneResult>;
}
pub trait HistoryPorts {
fn as_history(&self) -> Option<&dyn HistoryPort> {
None
}
}
impl<T> HistoryPorts for T
where
T: HistoryPort,
{
fn as_history(&self) -> Option<&dyn HistoryPort> {
Some(self)
}
}
#[async_trait]
pub trait AdoptionPort: Send + Sync {
async fn adopt_knowledge_entry(
&self,
principal: &Principal,
scope: &Scope,
request: &KnowledgeAdoptRequest,
) -> SpokeResult<KnowledgeAdoptResponse>;
}
pub trait AdoptionPorts {
fn as_adoption(&self) -> Option<&dyn AdoptionPort> {
None
}
}
impl<T> AdoptionPorts for T
where
T: AdoptionPort,
{
fn as_adoption(&self) -> Option<&dyn AdoptionPort> {
Some(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{spoke_ok, SpokeRejectCode};
use serde_json::json;
use std::collections::HashMap;
#[test]
fn knowledge_port_objects_are_send_sync() {
fn assert_send_sync<T: Send + Sync + ?Sized>() {}
assert_send_sync::<dyn KnowledgeQueryPort>();
assert_send_sync::<dyn ScopedKnowledgePort>();
}
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,
}
}
}
#[async_trait]
impl HostManifestPort for HostManifestPortMock {
async fn get_host_capability_manifest(&self) -> SpokeResult<HostCapabilityManifest> {
spoke_ok(self.self_manifest.clone())
}
async 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 }
}
}
#[async_trait]
impl KnowledgeEntryPort for BaselinePortStub {
async fn get_knowledge_entry(&self, _entry_id: &str) -> SpokeResult<KnowledgeEntry> {
unreachable!("baseline port stub")
}
async fn put_knowledge_entry(
&self,
entry: KnowledgeEntry,
_expected_base_revision: Option<u64>,
) -> SpokeResult<KnowledgeEntry> {
spoke_ok(entry)
}
}
#[async_trait]
impl RelationPort for BaselinePortStub {
async fn get_relation(&self, _relation_id: &str) -> SpokeResult<Relation> {
unreachable!("baseline port stub")
}
async fn put_relation(
&self,
relation: Relation,
_expected_base_revision: Option<u64>,
) -> SpokeResult<Relation> {
spoke_ok(relation)
}
}
#[async_trait]
impl KnowledgeQueryPort for BaselinePortStub {
async fn list_knowledge_entries(&self, _scope: &Scope) -> SpokeResult<Vec<KnowledgeEntry>> {
spoke_ok(Vec::new())
}
}
#[async_trait]
impl ScopeQueryPort for BaselinePortStub {
async fn list_timeline_events(&self, _scope: &Scope) -> SpokeResult<Vec<TimelineEvent>> {
spoke_ok(Vec::new())
}
}
#[async_trait]
impl FindingPort for BaselinePortStub {
async fn put_findings(&self, findings: Vec<Finding>) -> SpokeResult<Vec<Finding>> {
spoke_ok(findings)
}
}
#[async_trait]
impl RuleQueryPort for BaselinePortStub {
async fn list_rules(&self, _rule_refs: &[String]) -> SpokeResult<Vec<Rule>> {
spoke_ok(Vec::new())
}
}
#[async_trait]
impl HostManifestPort for BaselinePortStub {
async fn get_host_capability_manifest(&self) -> SpokeResult<HostCapabilityManifest> {
self.host_manifest.get_host_capability_manifest().await
}
async fn list_peer_host_capability_manifests(&self) -> SpokeResult<Vec<HostCapabilityManifest>> {
self.host_manifest
.list_peer_host_capability_manifests()
.await
}
}
#[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_seven_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 KnowledgeQueryPort = &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 = pollster::block_on(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 = pollster::block_on(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 = pollster::block_on(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 = pollster::block_on(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"),
}
}
}