Skip to main content

rustorb_core/
policy.rs

1//! `CORBA::ORB::create_policy` and the client side policy overrides of
2//! the Messaging specification: `Object::set_policy_overrides`, the ORB's
3//! `PolicyManager` and the thread's `PolicyCurrent`.
4//!
5//! The one client side policy rustorb has is
6//! `Messaging::RelativeRoundtripTimeoutPolicy`, the standard form of the
7//! call timeouts: overriding it on an object reference, on the calling
8//! thread or on the ORB sets the same timeout as
9//! [`ObjectRef::set_call_timeout`], [`set_thread_call_timeout`] and
10//! [`Orb::set_call_timeout`] (see `docs/orb-operations.md`).
11
12use std::fmt;
13use std::time::Duration;
14
15use crate::poa::{
16    IdAssignment, IdUniqueness, ImplicitActivation, Lifespan, Policy, RequestProcessing,
17    ServantRetention, ThreadPolicy,
18};
19use crate::timeout::{duration_to_time_t, time_t_to_duration};
20use crate::typecode::TCKind;
21use crate::{
22    Any, CompletionStatus, ObjectRef, Orb, SystemException, SystemExceptionKind, Value, minor,
23    set_thread_call_timeout, thread_call_timeout,
24};
25
26/// `CORBA::PolicyType`.
27pub type PolicyType = u32;
28
29/// `PortableServer::THREAD_POLICY_ID`; the other POA policies follow it,
30/// up to `REQUEST_PROCESSING_POLICY_ID` (22).
31pub const THREAD_POLICY_ID: PolicyType = 16;
32/// `PortableServer::LIFESPAN_POLICY_ID`.
33pub const LIFESPAN_POLICY_ID: PolicyType = 17;
34/// `PortableServer::ID_UNIQUENESS_POLICY_ID`.
35pub const ID_UNIQUENESS_POLICY_ID: PolicyType = 18;
36/// `PortableServer::ID_ASSIGNMENT_POLICY_ID`.
37pub const ID_ASSIGNMENT_POLICY_ID: PolicyType = 19;
38/// `PortableServer::IMPLICIT_ACTIVATION_POLICY_ID`.
39pub const IMPLICIT_ACTIVATION_POLICY_ID: PolicyType = 20;
40/// `PortableServer::SERVANT_RETENTION_POLICY_ID`.
41pub const SERVANT_RETENTION_POLICY_ID: PolicyType = 21;
42/// `PortableServer::REQUEST_PROCESSING_POLICY_ID`.
43pub const REQUEST_PROCESSING_POLICY_ID: PolicyType = 22;
44/// `Messaging::RELATIVE_RT_TIMEOUT_POLICY_TYPE`.
45pub const RELATIVE_RT_TIMEOUT_POLICY_TYPE: PolicyType = 32;
46
47/// A policy that [`Orb::create_policy`] makes: a POA policy, or a client
48/// side policy that can override the defaults of a reference, a thread or
49/// the ORB.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum PolicyValue {
52    /// One of the seven POA policies, for `create_POA`.
53    Poa(Policy),
54    /// `Messaging::RelativeRoundtripTimeoutPolicy`: how long a call may
55    /// take, as a `TimeBase::TimeT` (units of 100 nanoseconds).
56    RelativeRoundtripTimeout(u64),
57}
58
59impl PolicyValue {
60    /// The policy type (`policy_type`).
61    pub fn policy_type(&self) -> PolicyType {
62        match self {
63            PolicyValue::Poa(p) => match p {
64                Policy::Thread(_) => THREAD_POLICY_ID,
65                Policy::Lifespan(_) => LIFESPAN_POLICY_ID,
66                Policy::IdUniqueness(_) => ID_UNIQUENESS_POLICY_ID,
67                Policy::IdAssignment(_) => ID_ASSIGNMENT_POLICY_ID,
68                Policy::ImplicitActivation(_) => IMPLICIT_ACTIVATION_POLICY_ID,
69                Policy::ServantRetention(_) => SERVANT_RETENTION_POLICY_ID,
70                Policy::RequestProcessing(_) => REQUEST_PROCESSING_POLICY_ID,
71            },
72            PolicyValue::RelativeRoundtripTimeout(_) => RELATIVE_RT_TIMEOUT_POLICY_TYPE,
73        }
74    }
75
76    /// The value as a number: the enumerator of a POA policy, the
77    /// `relative_expiry` of a timeout. The bindings pass policies as this
78    /// pair; [`from_raw`](PolicyValue::from_raw) is the inverse.
79    pub fn raw_value(&self) -> u64 {
80        match *self {
81            PolicyValue::Poa(p) => u64::from(match p {
82                Policy::Thread(v) => v as u32,
83                Policy::Lifespan(v) => v as u32,
84                Policy::IdUniqueness(v) => v as u32,
85                Policy::IdAssignment(v) => v as u32,
86                Policy::ImplicitActivation(v) => v as u32,
87                Policy::ServantRetention(v) => v as u32,
88                Policy::RequestProcessing(v) => v as u32,
89            }),
90            PolicyValue::RelativeRoundtripTimeout(t) => t,
91        }
92    }
93
94    /// The policy of type `policy_type` with the value `value` (see
95    /// [`raw_value`](PolicyValue::raw_value)), or `None` if rustorb does
96    /// not know the type or the value.
97    pub fn from_raw(policy_type: PolicyType, value: u64) -> Option<PolicyValue> {
98        if policy_type == RELATIVE_RT_TIMEOUT_POLICY_TYPE {
99            return Some(PolicyValue::RelativeRoundtripTimeout(value));
100        }
101        let v = u32::try_from(value).ok()?;
102        let p = match policy_type {
103            THREAD_POLICY_ID => Policy::Thread(match v {
104                0 => ThreadPolicy::OrbCtrl,
105                1 => ThreadPolicy::SingleThread,
106                2 => ThreadPolicy::MainThread,
107                _ => return None,
108            }),
109            LIFESPAN_POLICY_ID => Policy::Lifespan(match v {
110                0 => Lifespan::Transient,
111                1 => Lifespan::Persistent,
112                _ => return None,
113            }),
114            ID_UNIQUENESS_POLICY_ID => Policy::IdUniqueness(match v {
115                0 => IdUniqueness::Unique,
116                1 => IdUniqueness::Multiple,
117                _ => return None,
118            }),
119            ID_ASSIGNMENT_POLICY_ID => Policy::IdAssignment(match v {
120                0 => IdAssignment::User,
121                1 => IdAssignment::System,
122                _ => return None,
123            }),
124            IMPLICIT_ACTIVATION_POLICY_ID => Policy::ImplicitActivation(match v {
125                0 => ImplicitActivation::Implicit,
126                1 => ImplicitActivation::NoImplicit,
127                _ => return None,
128            }),
129            SERVANT_RETENTION_POLICY_ID => Policy::ServantRetention(match v {
130                0 => ServantRetention::Retain,
131                1 => ServantRetention::NonRetain,
132                _ => return None,
133            }),
134            REQUEST_PROCESSING_POLICY_ID => Policy::RequestProcessing(match v {
135                0 => RequestProcessing::ActiveObjectMapOnly,
136                1 => RequestProcessing::UseDefaultServant,
137                2 => RequestProcessing::UseServantManager,
138                _ => return None,
139            }),
140            _ => return None,
141        };
142        Some(PolicyValue::Poa(p))
143    }
144
145    /// The timeout of a `RelativeRoundtripTimeoutPolicy`.
146    pub fn relative_expiry(&self) -> Option<Duration> {
147        match *self {
148            PolicyValue::RelativeRoundtripTimeout(t) => Some(time_t_to_duration(t)),
149            PolicyValue::Poa(_) => None,
150        }
151    }
152
153    /// The repository id of the policy's interface.
154    pub fn repository_id(&self) -> &'static str {
155        match self.policy_type() {
156            THREAD_POLICY_ID => "IDL:omg.org/PortableServer/ThreadPolicy:2.3",
157            LIFESPAN_POLICY_ID => "IDL:omg.org/PortableServer/LifespanPolicy:2.3",
158            ID_UNIQUENESS_POLICY_ID => "IDL:omg.org/PortableServer/IdUniquenessPolicy:2.3",
159            ID_ASSIGNMENT_POLICY_ID => "IDL:omg.org/PortableServer/IdAssignmentPolicy:2.3",
160            IMPLICIT_ACTIVATION_POLICY_ID => {
161                "IDL:omg.org/PortableServer/ImplicitActivationPolicy:2.3"
162            }
163            SERVANT_RETENTION_POLICY_ID => "IDL:omg.org/PortableServer/ServantRetentionPolicy:2.3",
164            REQUEST_PROCESSING_POLICY_ID => {
165                "IDL:omg.org/PortableServer/RequestProcessingPolicy:2.3"
166            }
167            _ => "IDL:omg.org/Messaging/RelativeRoundtripTimeoutPolicy:1.0",
168        }
169    }
170}
171
172/// `CORBA::PolicyError`, raised by [`Orb::create_policy`]: the
173/// `PolicyErrorCode` in `reason`.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct PolicyError {
176    /// One of the `*_POLICY*` constants of this type.
177    pub reason: i16,
178}
179
180impl PolicyError {
181    /// `BAD_POLICY`: the ORB does not know the policy type.
182    pub const BAD_POLICY: i16 = 0;
183    /// `UNSUPPORTED_POLICY`: the ORB knows the type but does not support
184    /// it.
185    pub const UNSUPPORTED_POLICY: i16 = 1;
186    /// `BAD_POLICY_TYPE`: the any has the wrong type for the policy.
187    pub const BAD_POLICY_TYPE: i16 = 2;
188    /// `BAD_POLICY_VALUE`: the value is not one of the policy's values.
189    pub const BAD_POLICY_VALUE: i16 = 3;
190    /// `UNSUPPORTED_POLICY_VALUE`: the ORB does not support the value.
191    pub const UNSUPPORTED_POLICY_VALUE: i16 = 4;
192}
193
194impl fmt::Display for PolicyError {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        write!(f, "CORBA::PolicyError (reason {})", self.reason)
197    }
198}
199
200impl std::error::Error for PolicyError {}
201
202/// `CORBA::SetOverrideType`.
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
204pub enum SetOverrideType {
205    /// `SET_OVERRIDE`: the policies replace every override.
206    Set,
207    /// `ADD_OVERRIDE`: the policies replace the overrides of their types
208    /// and keep the others.
209    Add,
210}
211
212/// The repository id of the enum a POA policy's value has.
213fn poa_value_id(policy_type: PolicyType) -> Option<&'static str> {
214    Some(match policy_type {
215        THREAD_POLICY_ID => "IDL:omg.org/PortableServer/ThreadPolicyValue:2.3",
216        LIFESPAN_POLICY_ID => "IDL:omg.org/PortableServer/LifespanPolicyValue:2.3",
217        ID_UNIQUENESS_POLICY_ID => "IDL:omg.org/PortableServer/IdUniquenessPolicyValue:2.3",
218        ID_ASSIGNMENT_POLICY_ID => "IDL:omg.org/PortableServer/IdAssignmentPolicyValue:2.3",
219        IMPLICIT_ACTIVATION_POLICY_ID => {
220            "IDL:omg.org/PortableServer/ImplicitActivationPolicyValue:2.3"
221        }
222        SERVANT_RETENTION_POLICY_ID => "IDL:omg.org/PortableServer/ServantRetentionPolicyValue:2.3",
223        REQUEST_PROCESSING_POLICY_ID => {
224            "IDL:omg.org/PortableServer/RequestProcessingPolicyValue:2.3"
225        }
226        _ => return None,
227    })
228}
229
230/// `create_policy` without the ORB: see [`Orb::create_policy`].
231pub fn create_policy(policy_type: PolicyType, value: &Any) -> Result<PolicyValue, PolicyError> {
232    let tc = value.typecode().unaliased();
233    let raw = if policy_type == RELATIVE_RT_TIMEOUT_POLICY_TYPE {
234        // TimeBase::TimeT, an alias of unsigned long long.
235        match (tc.kind(), value.value()) {
236            (TCKind::ULongLong, Value::ULongLong(t)) => *t,
237            _ => {
238                return Err(PolicyError {
239                    reason: PolicyError::BAD_POLICY_TYPE,
240                });
241            }
242        }
243    } else if let Some(id) = poa_value_id(policy_type) {
244        // The enum of the policy; its version differs between the IDL
245        // of CORBA 2.3 and later (and between ORBs), so it is compared
246        // without the version.
247        let base = |s: &str| {
248            s.rsplit_once(':')
249                .map_or(s.to_owned(), |(b, _)| b.to_owned())
250        };
251        match (tc.kind(), value.value()) {
252            (TCKind::Enum, Value::Enum(v)) if tc.id().is_ok_and(|i| base(i) == base(id)) => {
253                u64::from(*v)
254            }
255            _ => {
256                return Err(PolicyError {
257                    reason: PolicyError::BAD_POLICY_TYPE,
258                });
259            }
260        }
261    } else {
262        return Err(PolicyError {
263            reason: PolicyError::BAD_POLICY,
264        });
265    };
266    PolicyValue::from_raw(policy_type, raw).ok_or(PolicyError {
267        reason: PolicyError::BAD_POLICY_VALUE,
268    })
269}
270
271/// `NO_PERMISSION`, for a policy that cannot override at the scope (CORBA
272/// 3.0, 4.9.3.1).
273fn no_permission() -> SystemException {
274    SystemException::new(SystemExceptionKind::NO_PERMISSION, 0, CompletionStatus::No)
275}
276
277/// The timeout the overrides `policies` set on top of `current` (the
278/// timeout of the scope; `None` when it has none).
279fn apply_overrides(
280    current: Option<u64>,
281    policies: &[PolicyValue],
282    set_add: SetOverrideType,
283) -> Result<Option<u64>, SystemException> {
284    for (i, p) in policies.iter().enumerate() {
285        if policies[..i]
286            .iter()
287            .any(|q| q.policy_type() == p.policy_type())
288        {
289            return Err(SystemException::new(
290                SystemExceptionKind::BAD_PARAM,
291                minor::DUPLICATE_POLICY,
292                CompletionStatus::No,
293            ));
294        }
295    }
296    let mut timeout = match set_add {
297        SetOverrideType::Set => None,
298        SetOverrideType::Add => current,
299    };
300    for p in policies {
301        match p {
302            PolicyValue::RelativeRoundtripTimeout(t) => timeout = Some(*t),
303            PolicyValue::Poa(_) => return Err(no_permission()),
304        }
305    }
306    Ok(timeout)
307}
308
309/// The overrides of the types `types` (every type when empty) at a scope
310/// whose timeout is `timeout`.
311fn overrides(timeout: Option<u64>, types: &[PolicyType]) -> Vec<PolicyValue> {
312    let wanted = types.is_empty() || types.contains(&RELATIVE_RT_TIMEOUT_POLICY_TYPE);
313    timeout
314        .filter(|_| wanted)
315        .map(PolicyValue::RelativeRoundtripTimeout)
316        .into_iter()
317        .collect()
318}
319
320/// A stored timeout (`Some(None)` is "no limit") as a `relative_expiry`,
321/// if it is one a policy can say.
322fn as_time_t(timeout: Option<Option<Duration>>) -> Option<u64> {
323    timeout.flatten().map(duration_to_time_t)
324}
325
326/// `PolicyCurrent::set_policy_overrides`: the overrides of the calling
327/// thread, for every ORB. A `RelativeRoundtripTimeoutPolicy` sets the
328/// thread's call timeout ([`set_thread_call_timeout`]); without one (after
329/// `SET_OVERRIDE`) the thread has none. `NO_PERMISSION` for a POA policy.
330pub fn set_thread_policy_overrides(
331    policies: &[PolicyValue],
332    set_add: SetOverrideType,
333) -> Result<(), SystemException> {
334    let t = apply_overrides(as_time_t(thread_call_timeout()), policies, set_add)?;
335    set_thread_call_timeout(t.map(|t| Some(time_t_to_duration(t))));
336    Ok(())
337}
338
339/// `PolicyCurrent::get_policy_overrides`: the overrides of the calling
340/// thread of the types `types`, or all of them when `types` is empty.
341pub fn thread_policy_overrides(types: &[PolicyType]) -> Vec<PolicyValue> {
342    overrides(as_time_t(thread_call_timeout()), types)
343}
344
345impl Orb {
346    /// `CORBA::ORB::create_policy`: a POA policy from its enumerator, or a
347    /// `RelativeRoundtripTimeoutPolicy` from a `TimeBase::TimeT` (an
348    /// `unsigned long long`, in units of 100 nanoseconds).
349    ///
350    /// `PolicyError` with `BAD_POLICY` for a type rustorb does not know,
351    /// `BAD_POLICY_TYPE` when the any does not hold the policy's type, and
352    /// `BAD_POLICY_VALUE` for an enumerator out of range.
353    pub fn create_policy(
354        &self,
355        policy_type: PolicyType,
356        value: &Any,
357    ) -> Result<PolicyValue, PolicyError> {
358        create_policy(policy_type, value)
359    }
360
361    /// `PolicyManager::set_policy_overrides` of the ORB (the initial
362    /// reference `ORBPolicyManager`): a `RelativeRoundtripTimeoutPolicy`
363    /// sets [`call_timeout`](Orb::call_timeout); without one (after
364    /// `SET_OVERRIDE`) calls have no limit. `NO_PERMISSION` for a POA
365    /// policy.
366    pub fn set_policy_overrides(
367        &self,
368        policies: &[PolicyValue],
369        set_add: SetOverrideType,
370    ) -> Result<(), SystemException> {
371        let current = self.call_timeout().map(duration_to_time_t);
372        let t = apply_overrides(current, policies, set_add)?;
373        self.set_call_timeout(t.map(time_t_to_duration));
374        Ok(())
375    }
376
377    /// `PolicyManager::get_policy_overrides` of the ORB.
378    pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
379        overrides(self.call_timeout().map(duration_to_time_t), types)
380    }
381}
382
383impl ObjectRef {
384    /// `CORBA::Object::set_policy_overrides`: a new reference to the same
385    /// object with these overrides, whose call timeout is its own (this
386    /// reference is unchanged). A `RelativeRoundtripTimeoutPolicy` sets
387    /// the new reference's [`call_timeout`](ObjectRef::set_call_timeout).
388    /// `NO_PERMISSION` for a POA policy.
389    pub fn set_policy_overrides(
390        &self,
391        policies: &[PolicyValue],
392        set_add: SetOverrideType,
393    ) -> Result<ObjectRef, SystemException> {
394        let t = apply_overrides(as_time_t(self.call_timeout()), policies, set_add)?;
395        let obj = self.with_own_settings();
396        obj.set_call_timeout(t.map(|t| Some(time_t_to_duration(t))));
397        Ok(obj)
398    }
399
400    /// `CORBA::Object::get_policy_overrides`: the overrides of this
401    /// reference of the types `types`, or all of them when `types` is
402    /// empty.
403    pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
404        overrides(as_time_t(self.call_timeout()), types)
405    }
406
407    /// `CORBA::Object::get_client_policy`, and `get_policy` (rustorb reads
408    /// no policies from IORs): the policy of type `policy_type` that
409    /// applies to calls from this thread, from the reference's overrides,
410    /// else the thread's, else the ORB's. `None` when no scope has one,
411    /// which for the timeout means calls have no limit.
412    pub fn client_policy(&self, policy_type: PolicyType) -> Option<PolicyValue> {
413        if policy_type != RELATIVE_RT_TIMEOUT_POLICY_TYPE {
414            return None;
415        }
416        self.call_timeout()
417            .or_else(thread_call_timeout)
418            .unwrap_or_else(|| self.orb().call_timeout())
419            .map(|t| PolicyValue::RelativeRoundtripTimeout(duration_to_time_t(t)))
420    }
421}