use std::{collections::BTreeMap, sync::Arc};
use rho_protocol::{ClientEnvironment, ErrorCode, RpcError, SessionGrant, SessionSetup};
use super::open::{session_environment, OpenWith};
use crate::{
caller_context::{CallerContext, ENV_NAMES},
session_environment::Ambient,
};
pub(super) fn asked(
named: Option<SessionGrant>,
environment: &ClientEnvironment,
) -> Result<CallerContext, RpcError> {
match named {
Some(grant) => Ok(grant.into()),
None => CallerContext::from_env(|name| {
environment
.iter()
.find(|(variable, _)| *variable == name)
.map(|(_, value)| value.into())
})
.map_err(|error| RpcError::new(ErrorCode::InvalidParams, format!("{error:#}"))),
}
}
pub(super) fn opening(asked: CallerContext, parents: Option<&CallerContext>) -> CallerContext {
match parents {
Some(parents) => asked.within(&parents.child()),
None => asked,
}
}
pub(super) fn carrying(grant: &CallerContext, environment: &Ambient) -> Ambient {
let mut variables = match environment {
Ambient::Client(variables) => BTreeMap::clone(variables),
Ambient::ThisProcess => return Ambient::ThisProcess,
};
for name in ENV_NAMES {
variables.remove(name);
}
if !grant.is_root() {
variables.extend(
grant
.env()
.into_iter()
.map(|(name, value)| (name.to_owned(), value)),
);
}
Ambient::Client(Arc::new(variables))
}
impl OpenWith {
pub(super) fn under(
grant: CallerContext,
environment: &ClientEnvironment,
setup: SessionSetup,
) -> Result<Self, RpcError> {
Ok(Self {
environment: carrying(&grant, &session_environment(environment)?),
setup,
grant,
})
}
pub(super) fn granted(&self, grant: CallerContext) -> Self {
Self {
environment: carrying(&grant, &self.environment),
setup: self.setup.clone(),
grant,
}
}
}
#[cfg(test)]
#[path = "grant_tests.rs"]
mod tests;