1use std::fmt;
17use std::sync::mpsc;
18use std::time::Duration;
19
20use crate::{
21 Any, CompletionStatus, Exception, InStream, ObjectRef, Orb, Reply, Servant, ServerReply,
22 SystemException, SystemExceptionKind, TCKind, TypeCode, UserException, Value,
23};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ArgMode {
28 In,
29 Out,
30 InOut,
31}
32
33impl ArgMode {
34 pub fn flags(self) -> u32 {
36 match self {
37 ArgMode::In => 1,
38 ArgMode::Out => 2,
39 ArgMode::InOut => 3,
40 }
41 }
42
43 pub fn from_flags(flags: u32) -> Option<ArgMode> {
45 match flags & 3 {
46 1 => Some(ArgMode::In),
47 2 => Some(ArgMode::Out),
48 3 => Some(ArgMode::InOut),
49 _ => None,
50 }
51 }
52
53 fn is_in(self) -> bool {
54 self != ArgMode::Out
55 }
56
57 fn is_out(self) -> bool {
58 self != ArgMode::In
59 }
60}
61
62#[derive(Debug, Clone, PartialEq)]
66pub struct NamedValue {
67 pub name: String,
68 pub value: Any,
69 pub mode: ArgMode,
70}
71
72impl NamedValue {
73 pub fn new(name: impl Into<String>, value: Any, mode: ArgMode) -> NamedValue {
74 NamedValue {
75 name: name.into(),
76 value,
77 mode,
78 }
79 }
80
81 pub fn out(name: impl Into<String>, tc: TypeCode) -> NamedValue {
83 NamedValue::new(name, Any::new(tc, Value::Void), ArgMode::Out)
84 }
85}
86
87fn sys(kind: SystemExceptionKind, completed: CompletionStatus) -> SystemException {
88 SystemException::new(kind, 0, completed)
89}
90
91fn bad_inv_order() -> SystemException {
92 sys(SystemExceptionKind::BAD_INV_ORDER, CompletionStatus::No)
93}
94
95type Pending = mpsc::Receiver<Result<Reply, Exception>>;
99
100pub struct DiiRequest {
109 target: ObjectRef,
110 operation: String,
111 arguments: Vec<NamedValue>,
112 result: Any,
113 exceptions: Vec<TypeCode>,
114 timeout: Option<Option<Duration>>,
115 pending: Option<Pending>,
116}
117
118impl fmt::Debug for DiiRequest {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 f.debug_struct("DiiRequest")
121 .field("operation", &self.operation)
122 .field("arguments", &self.arguments)
123 .field("result", &self.result)
124 .field("pending", &self.pending.is_some())
125 .finish_non_exhaustive()
126 }
127}
128
129impl ObjectRef {
130 pub fn create_request(&self, operation: &str) -> DiiRequest {
133 DiiRequest {
134 target: self.clone(),
135 operation: operation.to_owned(),
136 arguments: Vec::new(),
137 result: Any::new(TypeCode::void(), Value::Void),
138 exceptions: Vec::new(),
139 timeout: None,
140 pending: None,
141 }
142 }
143}
144
145impl DiiRequest {
146 pub fn target(&self) -> &ObjectRef {
147 &self.target
148 }
149
150 pub fn operation(&self) -> &str {
151 &self.operation
152 }
153
154 pub fn arguments(&self) -> &[NamedValue] {
156 &self.arguments
157 }
158
159 pub fn arguments_mut(&mut self) -> &mut Vec<NamedValue> {
161 &mut self.arguments
162 }
163
164 pub fn add_in_arg(&mut self, name: &str, value: Any) -> &mut DiiRequest {
165 self.arguments
166 .push(NamedValue::new(name, value, ArgMode::In));
167 self
168 }
169
170 pub fn add_inout_arg(&mut self, name: &str, value: Any) -> &mut DiiRequest {
171 self.arguments
172 .push(NamedValue::new(name, value, ArgMode::InOut));
173 self
174 }
175
176 pub fn add_out_arg(&mut self, name: &str, tc: TypeCode) -> &mut DiiRequest {
177 self.arguments.push(NamedValue::out(name, tc));
178 self
179 }
180
181 pub fn set_return_type(&mut self, tc: TypeCode) -> &mut DiiRequest {
183 self.result = Any::new(tc, Value::Void);
184 self
185 }
186
187 pub fn result(&self) -> &Any {
189 &self.result
190 }
191
192 pub fn add_exception(&mut self, tc: TypeCode) -> &mut DiiRequest {
194 self.exceptions.push(tc);
195 self
196 }
197
198 pub fn exceptions(&self) -> &[TypeCode] {
199 &self.exceptions
200 }
201
202 pub fn set_timeout(&mut self, timeout: Option<Duration>) -> &mut DiiRequest {
205 self.timeout = Some(timeout);
206 self
207 }
208
209 fn in_values(&self) -> Vec<(TypeCode, Value)> {
211 self.arguments
212 .iter()
213 .filter(|nv| nv.mode.is_in())
214 .map(|nv| (nv.value.typecode().clone(), nv.value.value().clone()))
215 .collect()
216 }
217
218 fn check_idle(&self) -> Result<(), SystemException> {
219 match self.pending {
220 Some(_) => Err(bad_inv_order()),
221 None => Ok(()),
222 }
223 }
224
225 pub fn invoke(&mut self) -> Result<(), Exception> {
227 self.check_idle()?;
228 let values = self.in_values();
229 let mut request = self
230 .target
231 .request(&self.operation)
232 .args(move |out| write_values(out, &values));
233 if let Some(t) = self.timeout {
234 request = request.timeout(t);
235 }
236 let reply = request.invoke()?;
237 self.take_reply(&reply)
238 }
239
240 pub async fn invoke_async(&mut self) -> Result<(), Exception> {
243 self.check_idle()?;
244 let values = self.in_values();
245 let mut request = self
246 .target
247 .request_async(&self.operation)
248 .args(move |out| write_values(out, &values));
249 if let Some(t) = self.timeout {
250 request = request.timeout(t);
251 }
252 let reply = request.invoke().await?;
253 self.take_reply(&reply)
254 }
255
256 pub fn send_oneway(&self) -> Result<(), SystemException> {
258 self.check_idle()?;
259 let values = self.in_values();
260 let mut request = self
261 .target
262 .request(&self.operation)
263 .args(move |out| write_values(out, &values));
264 if let Some(t) = self.timeout {
265 request = request.timeout(t);
266 }
267 request.send_oneway()
268 }
269
270 pub fn send_deferred(&mut self) -> Result<(), SystemException> {
276 self.check_idle()?;
277 let orb: Orb = self.target.orb().clone();
278 orb.check_running()?;
279 let values = self.in_values();
280 let target = self.target.clone();
281 let operation = self.operation.clone();
282 let timeout = self.timeout;
283 let (tx, rx) = mpsc::channel();
284 let timeout = timeout.unwrap_or_else(|| target.effective_timeout());
286 orb.runtime_handle().spawn(async move {
287 let result = target
288 .request_async(&operation)
289 .args(move |out| write_values(out, &values))
290 .timeout(timeout)
291 .invoke()
292 .await;
293 let _ = tx.send(result);
294 });
295 self.pending = Some(rx);
296 Ok(())
297 }
298
299 pub fn poll_response(&mut self) -> Result<bool, SystemException> {
302 let Some(rx) = &self.pending else {
303 return Err(bad_inv_order());
304 };
305 match rx.try_recv() {
306 Ok(result) => {
307 let (tx, ready) = mpsc::channel();
309 let _ = tx.send(result);
310 self.pending = Some(ready);
311 Ok(true)
312 }
313 Err(mpsc::TryRecvError::Empty) => Ok(false),
314 Err(mpsc::TryRecvError::Disconnected) => Ok(true),
315 }
316 }
317
318 pub fn get_response(&mut self) -> Result<(), Exception> {
322 let Some(rx) = self.pending.take() else {
323 return Err(bad_inv_order().into());
324 };
325 let result = rx.recv().unwrap_or_else(|_| {
327 Err(sys(SystemExceptionKind::COMM_FAILURE, CompletionStatus::Maybe).into())
328 });
329 self.take_reply(&result?)
330 }
331
332 fn take_reply(&mut self, reply: &Reply) -> Result<(), Exception> {
334 let mut input = reply.input();
335 let tc = self.result.typecode().clone();
336 let value = input.read_value(&tc)?;
337 self.result = Any::new(tc, value);
338 for nv in self.arguments.iter_mut().filter(|nv| nv.mode.is_out()) {
339 let tc = nv.value.typecode().clone();
340 let value = input.read_value(&tc)?;
341 nv.value = Any::new(tc, value);
342 }
343 Ok(())
344 }
345
346 pub fn exception_value(&self, e: &UserException) -> Result<Any, SystemException> {
351 let tc = self
352 .exceptions
353 .iter()
354 .find(|tc| tc.unaliased().id().ok() == Some(e.repository_id()))
355 .ok_or_else(|| sys(SystemExceptionKind::UNKNOWN, CompletionStatus::Yes))?;
356 let mut input = e.reply.input();
357 let value = input.read_value(tc)?;
358 Ok(Any::new(tc.clone(), value))
359 }
360}
361
362fn write_values(
363 out: &mut crate::OutStream<'_>,
364 values: &[(TypeCode, Value)],
365) -> Result<(), SystemException> {
366 for (tc, v) in values {
367 out.write_value(tc, v)?;
368 }
369 Ok(())
370}
371
372pub trait DynamicImplementation: Send + Sync {
378 fn primary_interface(&self) -> &str;
381
382 fn is_a(&self, repository_id: &str) -> bool {
385 repository_id == self.primary_interface()
386 }
387
388 fn invoke(&self, request: &mut ServerRequest) -> Result<(), SystemException>;
395}
396
397#[derive(Debug)]
399pub struct DynamicServant<T>(pub T);
400
401impl<T: DynamicImplementation> Servant for DynamicServant<T> {
402 fn repository_id(&self) -> &str {
403 self.0.primary_interface()
404 }
405
406 fn is_a(&self, repository_id: &str) -> bool {
407 self.0.is_a(repository_id)
408 }
409
410 fn dispatch(
411 &self,
412 operation: &str,
413 input: &mut InStream<'_>,
414 reply: &mut ServerReply,
415 ) -> Result<(), SystemException> {
416 let mut request = ServerRequest::new(operation, input)?;
417 self.0.invoke(&mut request)?;
418 request.write_reply(reply)
419 }
420}
421
422pub struct ServerRequest {
427 operation: String,
428 input: Option<crate::stream::DetachedInput>,
429 arguments: Option<Vec<NamedValue>>,
430 result: Option<Any>,
431 exception: Option<Any>,
432}
433
434impl fmt::Debug for ServerRequest {
435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436 f.debug_struct("ServerRequest")
437 .field("operation", &self.operation)
438 .field("arguments", &self.arguments)
439 .field("result", &self.result)
440 .field("exception", &self.exception)
441 .finish_non_exhaustive()
442 }
443}
444
445impl ServerRequest {
446 pub fn new(operation: &str, input: &InStream<'_>) -> Result<ServerRequest, SystemException> {
450 let input = input
451 .detach()
452 .ok_or_else(|| sys(SystemExceptionKind::INTERNAL, CompletionStatus::No))?;
453 Ok(ServerRequest {
454 operation: operation.to_owned(),
455 input: Some(input),
456 arguments: None,
457 result: None,
458 exception: None,
459 })
460 }
461
462 pub fn operation(&self) -> &str {
463 &self.operation
464 }
465
466 pub fn arguments(
474 &mut self,
475 mut parameters: Vec<NamedValue>,
476 ) -> Result<&mut [NamedValue], SystemException> {
477 let Some(input) = self.input.take() else {
478 return Err(bad_inv_order());
479 };
480 {
481 let mut stream = input.stream();
482 for nv in parameters.iter_mut().filter(|nv| nv.mode.is_in()) {
483 let tc = nv.value.typecode().clone();
484 let value = stream.read_value(&tc)?;
485 nv.value = Any::new(tc, value);
486 }
487 }
488 Ok(self.arguments.insert(parameters))
489 }
490
491 pub fn parameters_mut(&mut self) -> Option<&mut [NamedValue]> {
493 self.arguments.as_deref_mut()
494 }
495
496 pub fn set_result(&mut self, value: Any) -> Result<(), SystemException> {
501 if self.arguments.is_none() || self.exception.is_some() {
502 return Err(bad_inv_order());
503 }
504 self.result = Some(value);
505 Ok(())
506 }
507
508 pub fn set_exception(&mut self, value: Any) -> Result<(), SystemException> {
512 if value.typecode().unaliased().kind() != TCKind::Except {
513 return Err(sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::No));
514 }
515 self.exception = Some(value);
516 Ok(())
517 }
518
519 pub fn write_reply(self, reply: &mut ServerReply) -> Result<(), SystemException> {
523 if let Some(exception) = &self.exception {
524 let tc = exception.typecode().unaliased();
525 let id = tc.id().unwrap_or_default().to_owned();
526 let Value::List(members) = exception.value() else {
527 return Err(sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::Maybe));
528 };
529 let mut out = reply.user_exception(&id)?;
530 for (i, member) in members.iter().enumerate() {
531 let member_tc = tc
532 .member_type(i as u32)
533 .map_err(|_| sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::Maybe))?;
534 out.write_value(&member_tc, member)?;
535 }
536 return Ok(());
537 }
538 let mut out = reply.output();
539 if let Some(result) = &self.result {
540 out.write_value(result.typecode(), result.value())?;
541 }
542 for nv in self
543 .arguments
544 .iter()
545 .flatten()
546 .filter(|nv| nv.mode.is_out())
547 {
548 out.write_value(nv.value.typecode(), nv.value.value())?;
549 }
550 Ok(())
551 }
552}