use std::cell::Cell;
use std::fmt;
use std::sync::atomic::{AtomicI32, Ordering};
use std::time::Duration;
use crate::pi::sync_scope::{SYNC_WITH_TARGET, SYNC_WITH_TRANSPORT};
use crate::poa::{
Bidirectional, IdAssignment, IdUniqueness, ImplicitActivation, Lifespan, Policy,
RequestProcessing, ServantRetention, ThreadPolicy,
};
use crate::timeout::{duration_to_time_t, time_t_to_duration};
use crate::typecode::TCKind;
use crate::{
Any, CompletionStatus, ObjectRef, Orb, SystemException, SystemExceptionKind, Value, minor,
set_thread_call_timeout, thread_call_timeout,
};
pub type PolicyType = u32;
pub const THREAD_POLICY_ID: PolicyType = 16;
pub const LIFESPAN_POLICY_ID: PolicyType = 17;
pub const ID_UNIQUENESS_POLICY_ID: PolicyType = 18;
pub const ID_ASSIGNMENT_POLICY_ID: PolicyType = 19;
pub const IMPLICIT_ACTIVATION_POLICY_ID: PolicyType = 20;
pub const SERVANT_RETENTION_POLICY_ID: PolicyType = 21;
pub const REQUEST_PROCESSING_POLICY_ID: PolicyType = 22;
pub const SYNC_SCOPE_POLICY_TYPE: PolicyType = 24;
pub const RELATIVE_RT_TIMEOUT_POLICY_TYPE: PolicyType = 32;
pub const BIDIRECTIONAL_POLICY_TYPE: PolicyType = 37;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PolicyValue {
Poa(Policy),
RelativeRoundtripTimeout(u64),
SyncScope(i16),
}
impl PolicyValue {
pub fn policy_type(&self) -> PolicyType {
match self {
PolicyValue::Poa(p) => match p {
Policy::Thread(_) => THREAD_POLICY_ID,
Policy::Lifespan(_) => LIFESPAN_POLICY_ID,
Policy::IdUniqueness(_) => ID_UNIQUENESS_POLICY_ID,
Policy::IdAssignment(_) => ID_ASSIGNMENT_POLICY_ID,
Policy::ImplicitActivation(_) => IMPLICIT_ACTIVATION_POLICY_ID,
Policy::ServantRetention(_) => SERVANT_RETENTION_POLICY_ID,
Policy::RequestProcessing(_) => REQUEST_PROCESSING_POLICY_ID,
Policy::Bidirectional(_) => BIDIRECTIONAL_POLICY_TYPE,
},
PolicyValue::RelativeRoundtripTimeout(_) => RELATIVE_RT_TIMEOUT_POLICY_TYPE,
PolicyValue::SyncScope(_) => SYNC_SCOPE_POLICY_TYPE,
}
}
pub fn raw_value(&self) -> u64 {
match *self {
PolicyValue::Poa(p) => u64::from(match p {
Policy::Thread(v) => v as u32,
Policy::Lifespan(v) => v as u32,
Policy::IdUniqueness(v) => v as u32,
Policy::IdAssignment(v) => v as u32,
Policy::ImplicitActivation(v) => v as u32,
Policy::ServantRetention(v) => v as u32,
Policy::RequestProcessing(v) => v as u32,
Policy::Bidirectional(v) => v as u32,
}),
PolicyValue::RelativeRoundtripTimeout(t) => t,
PolicyValue::SyncScope(v) => v as u64,
}
}
pub fn from_raw(policy_type: PolicyType, value: u64) -> Option<PolicyValue> {
if policy_type == RELATIVE_RT_TIMEOUT_POLICY_TYPE {
return Some(PolicyValue::RelativeRoundtripTimeout(value));
}
if policy_type == SYNC_SCOPE_POLICY_TYPE {
return (value <= SYNC_WITH_TARGET as u64)
.then_some(PolicyValue::SyncScope(value as i16));
}
let v = u32::try_from(value).ok()?;
let p = match policy_type {
THREAD_POLICY_ID => Policy::Thread(match v {
0 => ThreadPolicy::OrbCtrl,
1 => ThreadPolicy::SingleThread,
2 => ThreadPolicy::MainThread,
_ => return None,
}),
LIFESPAN_POLICY_ID => Policy::Lifespan(match v {
0 => Lifespan::Transient,
1 => Lifespan::Persistent,
_ => return None,
}),
ID_UNIQUENESS_POLICY_ID => Policy::IdUniqueness(match v {
0 => IdUniqueness::Unique,
1 => IdUniqueness::Multiple,
_ => return None,
}),
ID_ASSIGNMENT_POLICY_ID => Policy::IdAssignment(match v {
0 => IdAssignment::User,
1 => IdAssignment::System,
_ => return None,
}),
IMPLICIT_ACTIVATION_POLICY_ID => Policy::ImplicitActivation(match v {
0 => ImplicitActivation::Implicit,
1 => ImplicitActivation::NoImplicit,
_ => return None,
}),
SERVANT_RETENTION_POLICY_ID => Policy::ServantRetention(match v {
0 => ServantRetention::Retain,
1 => ServantRetention::NonRetain,
_ => return None,
}),
REQUEST_PROCESSING_POLICY_ID => Policy::RequestProcessing(match v {
0 => RequestProcessing::ActiveObjectMapOnly,
1 => RequestProcessing::UseDefaultServant,
2 => RequestProcessing::UseServantManager,
_ => return None,
}),
BIDIRECTIONAL_POLICY_TYPE => Policy::Bidirectional(match v {
0 => Bidirectional::Normal,
1 => Bidirectional::Both,
_ => return None,
}),
_ => return None,
};
Some(PolicyValue::Poa(p))
}
pub fn relative_expiry(&self) -> Option<Duration> {
match *self {
PolicyValue::RelativeRoundtripTimeout(t) => Some(time_t_to_duration(t)),
_ => None,
}
}
pub fn synchronization(&self) -> Option<i16> {
match *self {
PolicyValue::SyncScope(v) => Some(v),
_ => None,
}
}
pub fn repository_id(&self) -> &'static str {
match self.policy_type() {
THREAD_POLICY_ID => "IDL:omg.org/PortableServer/ThreadPolicy:2.3",
LIFESPAN_POLICY_ID => "IDL:omg.org/PortableServer/LifespanPolicy:2.3",
ID_UNIQUENESS_POLICY_ID => "IDL:omg.org/PortableServer/IdUniquenessPolicy:2.3",
ID_ASSIGNMENT_POLICY_ID => "IDL:omg.org/PortableServer/IdAssignmentPolicy:2.3",
IMPLICIT_ACTIVATION_POLICY_ID => {
"IDL:omg.org/PortableServer/ImplicitActivationPolicy:2.3"
}
SERVANT_RETENTION_POLICY_ID => "IDL:omg.org/PortableServer/ServantRetentionPolicy:2.3",
REQUEST_PROCESSING_POLICY_ID => {
"IDL:omg.org/PortableServer/RequestProcessingPolicy:2.3"
}
BIDIRECTIONAL_POLICY_TYPE => "IDL:omg.org/BiDirPolicy/BidirectionalPolicy:1.0",
SYNC_SCOPE_POLICY_TYPE => "IDL:omg.org/Messaging/SyncScopePolicy:1.0",
_ => "IDL:omg.org/Messaging/RelativeRoundtripTimeoutPolicy:1.0",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PolicyError {
pub reason: i16,
}
impl PolicyError {
pub const BAD_POLICY: i16 = 0;
pub const UNSUPPORTED_POLICY: i16 = 1;
pub const BAD_POLICY_TYPE: i16 = 2;
pub const BAD_POLICY_VALUE: i16 = 3;
pub const UNSUPPORTED_POLICY_VALUE: i16 = 4;
}
impl fmt::Display for PolicyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CORBA::PolicyError (reason {})", self.reason)
}
}
impl std::error::Error for PolicyError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SetOverrideType {
Set,
Add,
}
fn poa_value_id(policy_type: PolicyType) -> Option<&'static str> {
Some(match policy_type {
THREAD_POLICY_ID => "IDL:omg.org/PortableServer/ThreadPolicyValue:2.3",
LIFESPAN_POLICY_ID => "IDL:omg.org/PortableServer/LifespanPolicyValue:2.3",
ID_UNIQUENESS_POLICY_ID => "IDL:omg.org/PortableServer/IdUniquenessPolicyValue:2.3",
ID_ASSIGNMENT_POLICY_ID => "IDL:omg.org/PortableServer/IdAssignmentPolicyValue:2.3",
IMPLICIT_ACTIVATION_POLICY_ID => {
"IDL:omg.org/PortableServer/ImplicitActivationPolicyValue:2.3"
}
SERVANT_RETENTION_POLICY_ID => "IDL:omg.org/PortableServer/ServantRetentionPolicyValue:2.3",
REQUEST_PROCESSING_POLICY_ID => {
"IDL:omg.org/PortableServer/RequestProcessingPolicyValue:2.3"
}
_ => return None,
})
}
pub fn create_policy(policy_type: PolicyType, value: &Any) -> Result<PolicyValue, PolicyError> {
let tc = value.typecode().unaliased();
let raw = if policy_type == RELATIVE_RT_TIMEOUT_POLICY_TYPE {
match (tc.kind(), value.value()) {
(TCKind::ULongLong, Value::ULongLong(t)) => *t,
_ => {
return Err(PolicyError {
reason: PolicyError::BAD_POLICY_TYPE,
});
}
}
} else if policy_type == SYNC_SCOPE_POLICY_TYPE {
match (tc.kind(), value.value()) {
(TCKind::Short, Value::Short(v)) => match u64::try_from(*v) {
Ok(v) => v,
Err(_) => {
return Err(PolicyError {
reason: PolicyError::BAD_POLICY_VALUE,
});
}
},
_ => {
return Err(PolicyError {
reason: PolicyError::BAD_POLICY_TYPE,
});
}
}
} else if policy_type == BIDIRECTIONAL_POLICY_TYPE {
match (tc.kind(), value.value()) {
(TCKind::UShort, Value::UShort(v)) => u64::from(*v),
_ => {
return Err(PolicyError {
reason: PolicyError::BAD_POLICY_TYPE,
});
}
}
} else if let Some(id) = poa_value_id(policy_type) {
let base = |s: &str| {
s.rsplit_once(':')
.map_or(s.to_owned(), |(b, _)| b.to_owned())
};
match (tc.kind(), value.value()) {
(TCKind::Enum, Value::Enum(v)) if tc.id().is_ok_and(|i| base(i) == base(id)) => {
u64::from(*v)
}
_ => {
return Err(PolicyError {
reason: PolicyError::BAD_POLICY_TYPE,
});
}
}
} else {
return Err(PolicyError {
reason: PolicyError::BAD_POLICY,
});
};
PolicyValue::from_raw(policy_type, raw).ok_or(PolicyError {
reason: PolicyError::BAD_POLICY_VALUE,
})
}
fn no_permission() -> SystemException {
SystemException::new(SystemExceptionKind::NO_PERMISSION, 0, CompletionStatus::No)
}
#[derive(Debug, Clone, Copy, Default)]
struct Scope {
timeout: Option<u64>,
sync_scope: Option<i16>,
}
fn apply_overrides(
current: Scope,
policies: &[PolicyValue],
set_add: SetOverrideType,
) -> Result<Scope, SystemException> {
check_duplicates(policies)?;
let mut scope = match set_add {
SetOverrideType::Set => Scope::default(),
SetOverrideType::Add => current,
};
for p in policies {
match p {
PolicyValue::RelativeRoundtripTimeout(t) => scope.timeout = Some(*t),
PolicyValue::SyncScope(v) => scope.sync_scope = Some(*v),
PolicyValue::Poa(_) => return Err(no_permission()),
}
}
Ok(scope)
}
fn check_duplicates(policies: &[PolicyValue]) -> Result<(), SystemException> {
for (i, p) in policies.iter().enumerate() {
if policies[..i]
.iter()
.any(|q| q.policy_type() == p.policy_type())
{
return Err(SystemException::new(
SystemExceptionKind::BAD_PARAM,
minor::DUPLICATE_POLICY,
CompletionStatus::No,
));
}
}
Ok(())
}
fn bidirectional(p: &PolicyValue) -> Option<Bidirectional> {
match p {
PolicyValue::Poa(Policy::Bidirectional(v)) => Some(*v),
_ => None,
}
}
fn overrides(scope: Scope, types: &[PolicyType]) -> Vec<PolicyValue> {
let wanted = |t: PolicyType| types.is_empty() || types.contains(&t);
let mut out = Vec::new();
if let Some(t) = scope
.timeout
.filter(|_| wanted(RELATIVE_RT_TIMEOUT_POLICY_TYPE))
{
out.push(PolicyValue::RelativeRoundtripTimeout(t));
}
if let Some(v) = scope.sync_scope.filter(|_| wanted(SYNC_SCOPE_POLICY_TYPE)) {
out.push(PolicyValue::SyncScope(v));
}
out
}
fn as_time_t(timeout: Option<Option<Duration>>) -> Option<u64> {
timeout.flatten().map(duration_to_time_t)
}
const SYNC_SCOPE_UNSET: i32 = -1;
pub(crate) fn new_sync_scope_cell(v: Option<i16>) -> AtomicI32 {
AtomicI32::new(v.map_or(SYNC_SCOPE_UNSET, i32::from))
}
pub(crate) fn load_sync_scope(cell: &AtomicI32) -> Option<i16> {
i16::try_from(cell.load(Ordering::Relaxed))
.ok()
.filter(|v| *v >= 0)
}
pub(crate) fn store_sync_scope(cell: &AtomicI32, v: Option<i16>) {
cell.store(v.map_or(SYNC_SCOPE_UNSET, i32::from), Ordering::Relaxed);
}
thread_local! {
static THREAD_SYNC_SCOPE: Cell<Option<i16>> = const { Cell::new(None) };
}
pub(crate) fn thread_sync_scope() -> Option<i16> {
THREAD_SYNC_SCOPE.with(Cell::get)
}
fn thread_scope() -> Scope {
Scope {
timeout: as_time_t(thread_call_timeout()),
sync_scope: thread_sync_scope(),
}
}
pub fn set_thread_policy_overrides(
policies: &[PolicyValue],
set_add: SetOverrideType,
) -> Result<(), SystemException> {
let scope = apply_overrides(thread_scope(), policies, set_add)?;
set_thread_call_timeout(scope.timeout.map(|t| Some(time_t_to_duration(t))));
THREAD_SYNC_SCOPE.with(|c| c.set(scope.sync_scope));
Ok(())
}
pub fn thread_policy_overrides(types: &[PolicyType]) -> Vec<PolicyValue> {
overrides(thread_scope(), types)
}
impl Orb {
pub fn create_policy(
&self,
policy_type: PolicyType,
value: &Any,
) -> Result<PolicyValue, PolicyError> {
create_policy(policy_type, value)
}
fn scope(&self) -> Scope {
Scope {
timeout: self.call_timeout().map(duration_to_time_t),
sync_scope: load_sync_scope(&self.inner.sync_scope),
}
}
pub fn set_policy_overrides(
&self,
policies: &[PolicyValue],
set_add: SetOverrideType,
) -> Result<(), SystemException> {
check_duplicates(policies)?;
let others: Vec<PolicyValue> = policies
.iter()
.filter(|p| bidirectional(p).is_none())
.copied()
.collect();
let scope = apply_overrides(self.scope(), &others, set_add)?;
self.set_call_timeout(scope.timeout.map(time_t_to_duration));
store_sync_scope(&self.inner.sync_scope, scope.sync_scope);
let bidir = policies.iter().find_map(bidirectional);
let mut stored = self.inner.bidir_override.lock().unwrap();
match (bidir, set_add) {
(Some(v), _) => *stored = Some(v),
(None, SetOverrideType::Set) => *stored = None,
(None, SetOverrideType::Add) => {}
}
Ok(())
}
pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
let mut out = overrides(self.scope(), types);
if types.is_empty() || types.contains(&BIDIRECTIONAL_POLICY_TYPE) {
if let Some(v) = *self.inner.bidir_override.lock().unwrap() {
out.push(PolicyValue::Poa(Policy::Bidirectional(v)));
}
}
out
}
}
impl ObjectRef {
fn scope(&self) -> Scope {
Scope {
timeout: as_time_t(self.call_timeout()),
sync_scope: self.sync_scope_override(),
}
}
pub fn set_policy_overrides(
&self,
policies: &[PolicyValue],
set_add: SetOverrideType,
) -> Result<ObjectRef, SystemException> {
let scope = apply_overrides(self.scope(), policies, set_add)?;
let obj = self.with_own_settings();
obj.set_call_timeout(scope.timeout.map(|t| Some(time_t_to_duration(t))));
obj.set_sync_scope_override(scope.sync_scope);
Ok(obj)
}
pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
overrides(self.scope(), types)
}
pub fn client_policy(&self, policy_type: PolicyType) -> Option<PolicyValue> {
match policy_type {
RELATIVE_RT_TIMEOUT_POLICY_TYPE => self
.call_timeout()
.or_else(thread_call_timeout)
.unwrap_or_else(|| self.orb().call_timeout())
.map(|t| PolicyValue::RelativeRoundtripTimeout(duration_to_time_t(t))),
SYNC_SCOPE_POLICY_TYPE => self
.sync_scope_override()
.or_else(thread_sync_scope)
.or_else(|| load_sync_scope(&self.orb().inner.sync_scope))
.map(PolicyValue::SyncScope),
_ => None,
}
}
pub(crate) fn effective_sync_scope(&self) -> i16 {
self.client_policy(SYNC_SCOPE_POLICY_TYPE)
.and_then(|p| p.synchronization())
.unwrap_or(SYNC_WITH_TRANSPORT)
}
}