Skip to main content

harmos_protocol/schema/
callers.rs

1/* ***
2 *
3 * Harmos
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * ***
8 */
9
10//! Caller Options and Runtime Descriptor Projection.
11
12/* === Modules === */
13
14/* === Re-Exports === */
15
16/* === Imports === */
17
18// Standard Library Imports
19use std::collections::BTreeMap;
20
21// Third Party Imports
22use prost::Message;
23use prost_reflect::{DescriptorPool, DynamicMessage, ExtensionDescriptor, MethodDescriptor, ReflectMessage, Value};
24use prost_types::FileDescriptorSet;
25
26// Local Imports
27use super::{Error, Executor, operation_identity};
28use crate::host::TimeGetRequest;
29use crate::model::Callers;
30
31/* === Constants === */
32
33/* === Macros === */
34
35/* === Type Aliases === */
36
37/* === Structs === */
38
39/* === Enums === */
40
41/* === Traits === */
42
43/* === Implementations === */
44
45/* === Public Functions === */
46
47/// Read The Mandatory Caller Option Without Dropping Unknown Descriptor Fields.
48pub fn method_callers(method: &MethodDescriptor) -> Result<Callers, Error> {
49    let id = format!("{}/{}", method.parent_service().full_name(), method.name());
50    let extension = method
51        .parent_pool()
52        .get_extension_by_name("harmos.model.v1.callers")
53        .ok_or_else(|| Error(format!("Declare {id}: Missing Callers Option Definition")))?;
54    let options = method.options();
55    if !options.has_extension(&extension) {
56        return Err(Error(format!("Declare {id}: Missing Callers Option")));
57    }
58    let value = options.get_extension(&extension);
59    let Value::EnumNumber(value) = value.as_ref() else {
60        return Err(Error(format!("Declare {id}: Invalid Callers Option")));
61    };
62    match Callers::try_from(*value) {
63        Ok(Callers::Clients) => Ok(Callers::Clients),
64        Ok(Callers::Plugins) => Ok(Callers::Plugins),
65        Ok(Callers::All) => Ok(Callers::All),
66        _ => Err(Error(format!("Declare {id}: Invalid Callers Option"))),
67    }
68}
69
70/// Attach Effective Caller Options To Runtime-Projected Service Descriptors.
71pub fn with_method_callers(mut types: FileDescriptorSet, callers: &BTreeMap<String, Callers>) -> Result<DescriptorPool, Error> {
72    let authority = TimeGetRequest::default().descriptor();
73    let authority = authority.parent_pool();
74    for name in ["google/protobuf/descriptor.proto", "harmos/model/v1/callers.proto"] {
75        let declared = authority.get_file_by_name(name).expect("protocol caller option dependency");
76        let declared = declared.file_descriptor_proto().clone();
77        match types.file.iter_mut().find(|file| file.name.as_deref() == Some(name)) {
78            Some(file) => *file = declared,
79            None => types.file.push(declared),
80        }
81    }
82    for file in &mut types.file {
83        let host = file.package.as_deref().is_some_and(|package| package.split('.').any(|segment| segment == "host"));
84        let projected = file.service.iter().any(|service| {
85            service.method.iter().any(|method| {
86                let id = format!(
87                    "{}.{}/{}",
88                    file.package.as_deref().unwrap_or_default(),
89                    service.name.as_deref().unwrap_or_default(),
90                    method.name.as_deref().unwrap_or_default()
91                );
92                callers.contains_key(&id)
93            })
94        });
95        if (host || projected) && !file.service.is_empty() && !file.dependency.iter().any(|name| name == "harmos/model/v1/callers.proto") {
96            file.dependency.push("harmos/model/v1/callers.proto".into());
97        }
98    }
99    let meta = authority.get_message_by_name("google.protobuf.FileDescriptorSet").expect("descriptor set schema");
100    let extension = authority.get_extension_by_name("harmos.model.v1.callers").expect("protocol caller option");
101    let mut descriptors = DynamicMessage::decode(meta, types.encode_to_vec().as_slice()).map_err(|error| Error(error.to_string()))?;
102    let files = descriptors.get_field_by_name_mut("file").and_then(Value::as_list_mut).expect("descriptor files");
103    for file in files {
104        let file = file.as_message_mut().expect("file descriptor");
105        let package = file.get_field_by_name("package").expect("package field").as_str().unwrap_or_default().to_owned();
106        let services = file.get_field_by_name_mut("service").and_then(Value::as_list_mut).expect("descriptor services");
107        for service in services {
108            let service = service.as_message_mut().expect("service descriptor");
109            project_service(service, &package, callers, &extension)?;
110        }
111    }
112    DescriptorPool::decode(descriptors.encode_to_vec().as_slice()).map_err(|error| Error(error.to_string()))
113}
114
115/* === Private Functions === */
116
117// Dynamic Options Preserve Custom Fields That prost_types Does Not Model.
118fn project_service(
119    service: &mut DynamicMessage, package: &str, callers: &BTreeMap<String, Callers>, extension: &ExtensionDescriptor,
120) -> Result<(), Error> {
121    let service_name = service.get_field_by_name("name").expect("service name").as_str().unwrap_or_default().to_owned();
122    let methods = service.get_field_by_name_mut("method").and_then(Value::as_list_mut).expect("descriptor methods");
123    for method in methods {
124        let method = method.as_message_mut().expect("method descriptor");
125        let name = method.get_field_by_name("name").expect("method name").as_str().unwrap_or_default().to_owned();
126        let id = format!("{package}.{service_name}/{name}");
127        if operation_identity(&id)? == Executor::Plugin && !callers.contains_key(&id) {
128            continue;
129        }
130
131        let caller = callers.get(&id).copied().ok_or_else(|| Error(format!("Declare {id}: Supply a Caller Projection")))?;
132        if !matches!(caller, Callers::Clients | Callers::Plugins | Callers::All) {
133            return Err(Error(format!("Declare {id}: Select Clients, Plugins or All for the Caller Projection")));
134        }
135
136        let options = method.get_field_by_name_mut("options").and_then(Value::as_message_mut).expect("method options");
137        options.set_extension(extension, Value::EnumNumber(caller as i32));
138    }
139    Ok(())
140}
141
142/* === Tests === */