1use std::cell::Cell;
15use std::fmt;
16use std::sync::atomic::{AtomicI32, Ordering};
17use std::time::Duration;
18
19use crate::pi::sync_scope::{SYNC_WITH_TARGET, SYNC_WITH_TRANSPORT};
20use crate::poa::{
21 Bidirectional, IdAssignment, IdUniqueness, ImplicitActivation, Lifespan, Policy,
22 RequestProcessing, ServantRetention, ThreadPolicy,
23};
24use crate::timeout::{duration_to_time_t, time_t_to_duration};
25use crate::typecode::TCKind;
26use crate::{
27 Any, CompletionStatus, ObjectRef, Orb, SystemException, SystemExceptionKind, Value, minor,
28 set_thread_call_timeout, thread_call_timeout,
29};
30
31pub type PolicyType = u32;
33
34pub const THREAD_POLICY_ID: PolicyType = 16;
37pub const LIFESPAN_POLICY_ID: PolicyType = 17;
39pub const ID_UNIQUENESS_POLICY_ID: PolicyType = 18;
41pub const ID_ASSIGNMENT_POLICY_ID: PolicyType = 19;
43pub const IMPLICIT_ACTIVATION_POLICY_ID: PolicyType = 20;
45pub const SERVANT_RETENTION_POLICY_ID: PolicyType = 21;
47pub const REQUEST_PROCESSING_POLICY_ID: PolicyType = 22;
49pub const SYNC_SCOPE_POLICY_TYPE: PolicyType = 24;
51pub const RELATIVE_RT_TIMEOUT_POLICY_TYPE: PolicyType = 32;
53pub const BIDIRECTIONAL_POLICY_TYPE: PolicyType = 37;
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum PolicyValue {
61 Poa(Policy),
63 RelativeRoundtripTimeout(u64),
66 SyncScope(i16),
71}
72
73impl PolicyValue {
74 pub fn policy_type(&self) -> PolicyType {
76 match self {
77 PolicyValue::Poa(p) => match p {
78 Policy::Thread(_) => THREAD_POLICY_ID,
79 Policy::Lifespan(_) => LIFESPAN_POLICY_ID,
80 Policy::IdUniqueness(_) => ID_UNIQUENESS_POLICY_ID,
81 Policy::IdAssignment(_) => ID_ASSIGNMENT_POLICY_ID,
82 Policy::ImplicitActivation(_) => IMPLICIT_ACTIVATION_POLICY_ID,
83 Policy::ServantRetention(_) => SERVANT_RETENTION_POLICY_ID,
84 Policy::RequestProcessing(_) => REQUEST_PROCESSING_POLICY_ID,
85 Policy::Bidirectional(_) => BIDIRECTIONAL_POLICY_TYPE,
86 },
87 PolicyValue::RelativeRoundtripTimeout(_) => RELATIVE_RT_TIMEOUT_POLICY_TYPE,
88 PolicyValue::SyncScope(_) => SYNC_SCOPE_POLICY_TYPE,
89 }
90 }
91
92 pub fn raw_value(&self) -> u64 {
97 match *self {
98 PolicyValue::Poa(p) => u64::from(match p {
99 Policy::Thread(v) => v as u32,
100 Policy::Lifespan(v) => v as u32,
101 Policy::IdUniqueness(v) => v as u32,
102 Policy::IdAssignment(v) => v as u32,
103 Policy::ImplicitActivation(v) => v as u32,
104 Policy::ServantRetention(v) => v as u32,
105 Policy::RequestProcessing(v) => v as u32,
106 Policy::Bidirectional(v) => v as u32,
107 }),
108 PolicyValue::RelativeRoundtripTimeout(t) => t,
109 PolicyValue::SyncScope(v) => v as u64,
110 }
111 }
112
113 pub fn from_raw(policy_type: PolicyType, value: u64) -> Option<PolicyValue> {
117 if policy_type == RELATIVE_RT_TIMEOUT_POLICY_TYPE {
118 return Some(PolicyValue::RelativeRoundtripTimeout(value));
119 }
120 if policy_type == SYNC_SCOPE_POLICY_TYPE {
121 return (value <= SYNC_WITH_TARGET as u64)
122 .then_some(PolicyValue::SyncScope(value as i16));
123 }
124 let v = u32::try_from(value).ok()?;
125 let p = match policy_type {
126 THREAD_POLICY_ID => Policy::Thread(match v {
127 0 => ThreadPolicy::OrbCtrl,
128 1 => ThreadPolicy::SingleThread,
129 2 => ThreadPolicy::MainThread,
130 _ => return None,
131 }),
132 LIFESPAN_POLICY_ID => Policy::Lifespan(match v {
133 0 => Lifespan::Transient,
134 1 => Lifespan::Persistent,
135 _ => return None,
136 }),
137 ID_UNIQUENESS_POLICY_ID => Policy::IdUniqueness(match v {
138 0 => IdUniqueness::Unique,
139 1 => IdUniqueness::Multiple,
140 _ => return None,
141 }),
142 ID_ASSIGNMENT_POLICY_ID => Policy::IdAssignment(match v {
143 0 => IdAssignment::User,
144 1 => IdAssignment::System,
145 _ => return None,
146 }),
147 IMPLICIT_ACTIVATION_POLICY_ID => Policy::ImplicitActivation(match v {
148 0 => ImplicitActivation::Implicit,
149 1 => ImplicitActivation::NoImplicit,
150 _ => return None,
151 }),
152 SERVANT_RETENTION_POLICY_ID => Policy::ServantRetention(match v {
153 0 => ServantRetention::Retain,
154 1 => ServantRetention::NonRetain,
155 _ => return None,
156 }),
157 REQUEST_PROCESSING_POLICY_ID => Policy::RequestProcessing(match v {
158 0 => RequestProcessing::ActiveObjectMapOnly,
159 1 => RequestProcessing::UseDefaultServant,
160 2 => RequestProcessing::UseServantManager,
161 _ => return None,
162 }),
163 BIDIRECTIONAL_POLICY_TYPE => Policy::Bidirectional(match v {
164 0 => Bidirectional::Normal,
165 1 => Bidirectional::Both,
166 _ => return None,
167 }),
168 _ => return None,
169 };
170 Some(PolicyValue::Poa(p))
171 }
172
173 pub fn relative_expiry(&self) -> Option<Duration> {
175 match *self {
176 PolicyValue::RelativeRoundtripTimeout(t) => Some(time_t_to_duration(t)),
177 _ => None,
178 }
179 }
180
181 pub fn synchronization(&self) -> Option<i16> {
183 match *self {
184 PolicyValue::SyncScope(v) => Some(v),
185 _ => None,
186 }
187 }
188
189 pub fn repository_id(&self) -> &'static str {
191 match self.policy_type() {
192 THREAD_POLICY_ID => "IDL:omg.org/PortableServer/ThreadPolicy:2.3",
193 LIFESPAN_POLICY_ID => "IDL:omg.org/PortableServer/LifespanPolicy:2.3",
194 ID_UNIQUENESS_POLICY_ID => "IDL:omg.org/PortableServer/IdUniquenessPolicy:2.3",
195 ID_ASSIGNMENT_POLICY_ID => "IDL:omg.org/PortableServer/IdAssignmentPolicy:2.3",
196 IMPLICIT_ACTIVATION_POLICY_ID => {
197 "IDL:omg.org/PortableServer/ImplicitActivationPolicy:2.3"
198 }
199 SERVANT_RETENTION_POLICY_ID => "IDL:omg.org/PortableServer/ServantRetentionPolicy:2.3",
200 REQUEST_PROCESSING_POLICY_ID => {
201 "IDL:omg.org/PortableServer/RequestProcessingPolicy:2.3"
202 }
203 BIDIRECTIONAL_POLICY_TYPE => "IDL:omg.org/BiDirPolicy/BidirectionalPolicy:1.0",
204 SYNC_SCOPE_POLICY_TYPE => "IDL:omg.org/Messaging/SyncScopePolicy:1.0",
205 _ => "IDL:omg.org/Messaging/RelativeRoundtripTimeoutPolicy:1.0",
206 }
207 }
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub struct PolicyError {
214 pub reason: i16,
216}
217
218impl PolicyError {
219 pub const BAD_POLICY: i16 = 0;
221 pub const UNSUPPORTED_POLICY: i16 = 1;
224 pub const BAD_POLICY_TYPE: i16 = 2;
226 pub const BAD_POLICY_VALUE: i16 = 3;
228 pub const UNSUPPORTED_POLICY_VALUE: i16 = 4;
230}
231
232impl fmt::Display for PolicyError {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 write!(f, "CORBA::PolicyError (reason {})", self.reason)
235 }
236}
237
238impl std::error::Error for PolicyError {}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
242pub enum SetOverrideType {
243 Set,
245 Add,
248}
249
250fn poa_value_id(policy_type: PolicyType) -> Option<&'static str> {
252 Some(match policy_type {
253 THREAD_POLICY_ID => "IDL:omg.org/PortableServer/ThreadPolicyValue:2.3",
254 LIFESPAN_POLICY_ID => "IDL:omg.org/PortableServer/LifespanPolicyValue:2.3",
255 ID_UNIQUENESS_POLICY_ID => "IDL:omg.org/PortableServer/IdUniquenessPolicyValue:2.3",
256 ID_ASSIGNMENT_POLICY_ID => "IDL:omg.org/PortableServer/IdAssignmentPolicyValue:2.3",
257 IMPLICIT_ACTIVATION_POLICY_ID => {
258 "IDL:omg.org/PortableServer/ImplicitActivationPolicyValue:2.3"
259 }
260 SERVANT_RETENTION_POLICY_ID => "IDL:omg.org/PortableServer/ServantRetentionPolicyValue:2.3",
261 REQUEST_PROCESSING_POLICY_ID => {
262 "IDL:omg.org/PortableServer/RequestProcessingPolicyValue:2.3"
263 }
264 _ => return None,
265 })
266}
267
268pub fn create_policy(policy_type: PolicyType, value: &Any) -> Result<PolicyValue, PolicyError> {
270 let tc = value.typecode().unaliased();
271 let raw = if policy_type == RELATIVE_RT_TIMEOUT_POLICY_TYPE {
272 match (tc.kind(), value.value()) {
274 (TCKind::ULongLong, Value::ULongLong(t)) => *t,
275 _ => {
276 return Err(PolicyError {
277 reason: PolicyError::BAD_POLICY_TYPE,
278 });
279 }
280 }
281 } else if policy_type == SYNC_SCOPE_POLICY_TYPE {
282 match (tc.kind(), value.value()) {
284 (TCKind::Short, Value::Short(v)) => match u64::try_from(*v) {
285 Ok(v) => v,
286 Err(_) => {
287 return Err(PolicyError {
288 reason: PolicyError::BAD_POLICY_VALUE,
289 });
290 }
291 },
292 _ => {
293 return Err(PolicyError {
294 reason: PolicyError::BAD_POLICY_TYPE,
295 });
296 }
297 }
298 } else if policy_type == BIDIRECTIONAL_POLICY_TYPE {
299 match (tc.kind(), value.value()) {
302 (TCKind::UShort, Value::UShort(v)) => u64::from(*v),
303 _ => {
304 return Err(PolicyError {
305 reason: PolicyError::BAD_POLICY_TYPE,
306 });
307 }
308 }
309 } else if let Some(id) = poa_value_id(policy_type) {
310 let base = |s: &str| {
314 s.rsplit_once(':')
315 .map_or(s.to_owned(), |(b, _)| b.to_owned())
316 };
317 match (tc.kind(), value.value()) {
318 (TCKind::Enum, Value::Enum(v)) if tc.id().is_ok_and(|i| base(i) == base(id)) => {
319 u64::from(*v)
320 }
321 _ => {
322 return Err(PolicyError {
323 reason: PolicyError::BAD_POLICY_TYPE,
324 });
325 }
326 }
327 } else {
328 return Err(PolicyError {
329 reason: PolicyError::BAD_POLICY,
330 });
331 };
332 PolicyValue::from_raw(policy_type, raw).ok_or(PolicyError {
333 reason: PolicyError::BAD_POLICY_VALUE,
334 })
335}
336
337fn no_permission() -> SystemException {
340 SystemException::new(SystemExceptionKind::NO_PERMISSION, 0, CompletionStatus::No)
341}
342
343#[derive(Debug, Clone, Copy, Default)]
347struct Scope {
348 timeout: Option<u64>,
349 sync_scope: Option<i16>,
350}
351
352fn apply_overrides(
355 current: Scope,
356 policies: &[PolicyValue],
357 set_add: SetOverrideType,
358) -> Result<Scope, SystemException> {
359 check_duplicates(policies)?;
360 let mut scope = match set_add {
361 SetOverrideType::Set => Scope::default(),
362 SetOverrideType::Add => current,
363 };
364 for p in policies {
365 match p {
366 PolicyValue::RelativeRoundtripTimeout(t) => scope.timeout = Some(*t),
367 PolicyValue::SyncScope(v) => scope.sync_scope = Some(*v),
368 PolicyValue::Poa(_) => return Err(no_permission()),
369 }
370 }
371 Ok(scope)
372}
373
374fn check_duplicates(policies: &[PolicyValue]) -> Result<(), SystemException> {
376 for (i, p) in policies.iter().enumerate() {
377 if policies[..i]
378 .iter()
379 .any(|q| q.policy_type() == p.policy_type())
380 {
381 return Err(SystemException::new(
382 SystemExceptionKind::BAD_PARAM,
383 minor::DUPLICATE_POLICY,
384 CompletionStatus::No,
385 ));
386 }
387 }
388 Ok(())
389}
390
391fn bidirectional(p: &PolicyValue) -> Option<Bidirectional> {
393 match p {
394 PolicyValue::Poa(Policy::Bidirectional(v)) => Some(*v),
395 _ => None,
396 }
397}
398
399fn overrides(scope: Scope, types: &[PolicyType]) -> Vec<PolicyValue> {
401 let wanted = |t: PolicyType| types.is_empty() || types.contains(&t);
402 let mut out = Vec::new();
403 if let Some(t) = scope
404 .timeout
405 .filter(|_| wanted(RELATIVE_RT_TIMEOUT_POLICY_TYPE))
406 {
407 out.push(PolicyValue::RelativeRoundtripTimeout(t));
408 }
409 if let Some(v) = scope.sync_scope.filter(|_| wanted(SYNC_SCOPE_POLICY_TYPE)) {
410 out.push(PolicyValue::SyncScope(v));
411 }
412 out
413}
414
415fn as_time_t(timeout: Option<Option<Duration>>) -> Option<u64> {
418 timeout.flatten().map(duration_to_time_t)
419}
420
421const SYNC_SCOPE_UNSET: i32 = -1;
423
424pub(crate) fn new_sync_scope_cell(v: Option<i16>) -> AtomicI32 {
426 AtomicI32::new(v.map_or(SYNC_SCOPE_UNSET, i32::from))
427}
428
429pub(crate) fn load_sync_scope(cell: &AtomicI32) -> Option<i16> {
431 i16::try_from(cell.load(Ordering::Relaxed))
432 .ok()
433 .filter(|v| *v >= 0)
434}
435
436pub(crate) fn store_sync_scope(cell: &AtomicI32, v: Option<i16>) {
438 cell.store(v.map_or(SYNC_SCOPE_UNSET, i32::from), Ordering::Relaxed);
439}
440
441thread_local! {
442 static THREAD_SYNC_SCOPE: Cell<Option<i16>> = const { Cell::new(None) };
443}
444
445pub(crate) fn thread_sync_scope() -> Option<i16> {
447 THREAD_SYNC_SCOPE.with(Cell::get)
448}
449
450fn thread_scope() -> Scope {
452 Scope {
453 timeout: as_time_t(thread_call_timeout()),
454 sync_scope: thread_sync_scope(),
455 }
456}
457
458pub fn set_thread_policy_overrides(
464 policies: &[PolicyValue],
465 set_add: SetOverrideType,
466) -> Result<(), SystemException> {
467 let scope = apply_overrides(thread_scope(), policies, set_add)?;
468 set_thread_call_timeout(scope.timeout.map(|t| Some(time_t_to_duration(t))));
469 THREAD_SYNC_SCOPE.with(|c| c.set(scope.sync_scope));
470 Ok(())
471}
472
473pub fn thread_policy_overrides(types: &[PolicyType]) -> Vec<PolicyValue> {
476 overrides(thread_scope(), types)
477}
478
479impl Orb {
480 pub fn create_policy(
489 &self,
490 policy_type: PolicyType,
491 value: &Any,
492 ) -> Result<PolicyValue, PolicyError> {
493 create_policy(policy_type, value)
494 }
495
496 fn scope(&self) -> Scope {
498 Scope {
499 timeout: self.call_timeout().map(duration_to_time_t),
500 sync_scope: load_sync_scope(&self.inner.sync_scope),
501 }
502 }
503
504 pub fn set_policy_overrides(
515 &self,
516 policies: &[PolicyValue],
517 set_add: SetOverrideType,
518 ) -> Result<(), SystemException> {
519 check_duplicates(policies)?;
520 let others: Vec<PolicyValue> = policies
521 .iter()
522 .filter(|p| bidirectional(p).is_none())
523 .copied()
524 .collect();
525 let scope = apply_overrides(self.scope(), &others, set_add)?;
526 self.set_call_timeout(scope.timeout.map(time_t_to_duration));
527 store_sync_scope(&self.inner.sync_scope, scope.sync_scope);
528 let bidir = policies.iter().find_map(bidirectional);
529 let mut stored = self.inner.bidir_override.lock().unwrap();
530 match (bidir, set_add) {
531 (Some(v), _) => *stored = Some(v),
532 (None, SetOverrideType::Set) => *stored = None,
533 (None, SetOverrideType::Add) => {}
534 }
535 Ok(())
536 }
537
538 pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
540 let mut out = overrides(self.scope(), types);
541 if types.is_empty() || types.contains(&BIDIRECTIONAL_POLICY_TYPE) {
542 if let Some(v) = *self.inner.bidir_override.lock().unwrap() {
543 out.push(PolicyValue::Poa(Policy::Bidirectional(v)));
544 }
545 }
546 out
547 }
548}
549
550impl ObjectRef {
551 fn scope(&self) -> Scope {
553 Scope {
554 timeout: as_time_t(self.call_timeout()),
555 sync_scope: self.sync_scope_override(),
556 }
557 }
558
559 pub fn set_policy_overrides(
566 &self,
567 policies: &[PolicyValue],
568 set_add: SetOverrideType,
569 ) -> Result<ObjectRef, SystemException> {
570 let scope = apply_overrides(self.scope(), policies, set_add)?;
571 let obj = self.with_own_settings();
572 obj.set_call_timeout(scope.timeout.map(|t| Some(time_t_to_duration(t))));
573 obj.set_sync_scope_override(scope.sync_scope);
574 Ok(obj)
575 }
576
577 pub fn policy_overrides(&self, types: &[PolicyType]) -> Vec<PolicyValue> {
581 overrides(self.scope(), types)
582 }
583
584 pub fn client_policy(&self, policy_type: PolicyType) -> Option<PolicyValue> {
592 match policy_type {
593 RELATIVE_RT_TIMEOUT_POLICY_TYPE => self
594 .call_timeout()
595 .or_else(thread_call_timeout)
596 .unwrap_or_else(|| self.orb().call_timeout())
597 .map(|t| PolicyValue::RelativeRoundtripTimeout(duration_to_time_t(t))),
598 SYNC_SCOPE_POLICY_TYPE => self
599 .sync_scope_override()
600 .or_else(thread_sync_scope)
601 .or_else(|| load_sync_scope(&self.orb().inner.sync_scope))
602 .map(PolicyValue::SyncScope),
603 _ => None,
604 }
605 }
606
607 pub(crate) fn effective_sync_scope(&self) -> i16 {
611 self.client_policy(SYNC_SCOPE_POLICY_TYPE)
612 .and_then(|p| p.synchronization())
613 .unwrap_or(SYNC_WITH_TRANSPORT)
614 }
615}