1use 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
26pub type PolicyType = u32;
28
29pub const THREAD_POLICY_ID: PolicyType = 16;
32pub const LIFESPAN_POLICY_ID: PolicyType = 17;
34pub const ID_UNIQUENESS_POLICY_ID: PolicyType = 18;
36pub const ID_ASSIGNMENT_POLICY_ID: PolicyType = 19;
38pub const IMPLICIT_ACTIVATION_POLICY_ID: PolicyType = 20;
40pub const SERVANT_RETENTION_POLICY_ID: PolicyType = 21;
42pub const REQUEST_PROCESSING_POLICY_ID: PolicyType = 22;
44pub const RELATIVE_RT_TIMEOUT_POLICY_TYPE: PolicyType = 32;
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum PolicyValue {
52 Poa(Policy),
54 RelativeRoundtripTimeout(u64),
57}
58
59impl PolicyValue {
60 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct PolicyError {
176 pub reason: i16,
178}
179
180impl PolicyError {
181 pub const BAD_POLICY: i16 = 0;
183 pub const UNSUPPORTED_POLICY: i16 = 1;
186 pub const BAD_POLICY_TYPE: i16 = 2;
188 pub const BAD_POLICY_VALUE: i16 = 3;
190 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
204pub enum SetOverrideType {
205 Set,
207 Add,
210}
211
212fn 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
230pub 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 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 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
271fn no_permission() -> SystemException {
274 SystemException::new(SystemExceptionKind::NO_PERMISSION, 0, CompletionStatus::No)
275}
276
277fn 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
309fn 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
320fn as_time_t(timeout: Option<Option<Duration>>) -> Option<u64> {
323 timeout.flatten().map(duration_to_time_t)
324}
325
326pub 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
339pub fn thread_policy_overrides(types: &[PolicyType]) -> Vec<PolicyValue> {
342 overrides(as_time_t(thread_call_timeout()), types)
343}
344
345impl Orb {
346 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 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 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 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 pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
404 overrides(as_time_t(self.call_timeout()), types)
405 }
406
407 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}