use std::any::Any;
use std::fmt;
use std::sync::Arc;
use rustorb_cdr::{ByteOrder, CdrEncode};
use rustorb_giop::{
Ior, MessageEncoder, OutMessage, ReplyHeader, ReplyStatus, ServiceContext, SystemExceptionBody,
Version,
};
use crate::stream::{InStream, OutStream};
use crate::{CodeSets, CompletionStatus, ObjectRef, Poa, SystemException, SystemExceptionKind};
pub(crate) const OBJECT_ID: &str = "IDL:omg.org/CORBA/Object:1.0";
pub trait Servant: Send + Sync {
fn repository_id(&self) -> &str;
fn is_a(&self, repository_id: &str) -> bool {
repository_id == self.repository_id()
}
fn dispatch(
&self,
operation: &str,
input: &mut InStream<'_>,
reply: &mut ServerReply,
) -> Result<(), SystemException>;
}
#[derive(Debug, Clone)]
pub enum ServantManagerError {
ForwardRequest(ObjectRef),
System(SystemException),
}
impl From<SystemException> for ServantManagerError {
fn from(e: SystemException) -> Self {
ServantManagerError::System(e)
}
}
impl fmt::Display for ServantManagerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ServantManagerError::ForwardRequest(_) => f.write_str("PortableServer::ForwardRequest"),
ServantManagerError::System(e) => e.fmt(f),
}
}
}
impl std::error::Error for ServantManagerError {}
pub trait ServantActivator: Send + Sync {
fn incarnate(&self, id: &[u8], adapter: &Poa) -> Result<Arc<dyn Servant>, ServantManagerError>;
fn etherealize(
&self,
id: &[u8],
adapter: &Poa,
servant: Arc<dyn Servant>,
cleanup_in_progress: bool,
remaining_activations: bool,
) {
let _ = (
id,
adapter,
servant,
cleanup_in_progress,
remaining_activations,
);
}
}
pub type Cookie = Box<dyn Any + Send>;
pub trait ServantLocator: Send + Sync {
fn preinvoke(
&self,
id: &[u8],
adapter: &Poa,
operation: &str,
) -> Result<(Arc<dyn Servant>, Cookie), ServantManagerError>;
fn postinvoke(
&self,
id: &[u8],
adapter: &Poa,
operation: &str,
cookie: Cookie,
servant: Arc<dyn Servant>,
) {
let _ = (id, adapter, operation, cookie, servant);
}
}
#[derive(Clone)]
pub enum ServantManager {
Activator(Arc<dyn ServantActivator>),
Locator(Arc<dyn ServantLocator>),
}
impl fmt::Debug for ServantManager {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ServantManager::Activator(_) => f.write_str("ServantManager::Activator"),
ServantManager::Locator(_) => f.write_str("ServantManager::Locator"),
}
}
}
pub trait AdapterActivator: Send + Sync {
fn unknown_adapter(&self, parent: &Poa, name: &str) -> bool;
}
#[derive(Debug)]
pub struct ServerReply {
version: Version,
order: ByteOrder,
request_id: u32,
code_sets: CodeSets,
msg: MessageEncoder,
status: ReplyStatus,
contexts: Vec<ServiceContext>,
exception_id: Option<String>,
}
impl ServerReply {
pub(crate) fn new(
version: Version,
order: ByteOrder,
request_id: u32,
code_sets: CodeSets,
) -> Result<ServerReply, SystemException> {
ServerReply::with_contexts(version, order, request_id, code_sets, Vec::new())
}
pub(crate) fn with_contexts(
version: Version,
order: ByteOrder,
request_id: u32,
code_sets: CodeSets,
contexts: Vec<ServiceContext>,
) -> Result<ServerReply, SystemException> {
Ok(ServerReply {
version,
order,
request_id,
code_sets,
msg: start(
version,
order,
request_id,
ReplyStatus::NoException,
&contexts,
)?,
status: ReplyStatus::NoException,
contexts,
exception_id: None,
})
}
pub fn output(&mut self) -> OutStream<'_> {
OutStream {
enc: self.msg.body(),
code_sets: self.code_sets,
orb: None,
values: None,
}
}
pub fn user_exception(
&mut self,
repository_id: &str,
) -> Result<OutStream<'_>, SystemException> {
self.msg = start(
self.version,
self.order,
self.request_id,
ReplyStatus::UserException,
&self.contexts,
)?;
self.status = ReplyStatus::UserException;
self.exception_id = Some(repository_id.to_owned());
let mut out = self.output();
out.write_string(repository_id)?;
Ok(out)
}
pub fn status(&self) -> ReplyStatus {
self.status
}
pub(crate) fn exception_id(&self) -> Option<&str> {
self.exception_id.as_deref()
}
pub(crate) fn finish(self) -> Result<OutMessage, SystemException> {
self.msg.finish_shared().map_err(|_| internal())
}
pub(crate) fn finish_with(
self,
contexts: Vec<ServiceContext>,
) -> Result<OutMessage, SystemException> {
if contexts == self.contexts {
return self.finish();
}
let header = ReplyHeader {
request_id: self.request_id,
reply_status: self.status,
service_context: contexts,
};
let msg = self.msg.finish_shared().map_err(|_| internal())?;
Ok(match msg.with_reply_header(&header) {
Ok(msg) => msg,
Err(msg) => {
crate::trace::warning!(
"reply to request id {}: the service contexts added after the servant ran \
would misalign the GIOP 1.0/1.1 body, and are not sent",
header.request_id
);
msg
}
})
}
}
fn start(
version: Version,
order: ByteOrder,
request_id: u32,
reply_status: ReplyStatus,
contexts: &[ServiceContext],
) -> Result<MessageEncoder, SystemException> {
let header = ReplyHeader {
request_id,
reply_status,
service_context: contexts.to_vec(),
};
MessageEncoder::reply(version, order, &header).map_err(|_| internal())
}
fn internal() -> SystemException {
SystemException::new(SystemExceptionKind::INTERNAL, 0, CompletionStatus::Maybe)
}
pub(crate) fn location_forward_reply(
version: Version,
order: ByteOrder,
request_id: u32,
ior: &Ior,
contexts: &[ServiceContext],
) -> Option<Vec<u8>> {
let mut m = start(
version,
order,
request_id,
ReplyStatus::LocationForward,
contexts,
)
.ok()?;
ior.encode(m.body()).ok()?;
m.finish().ok()
}
pub(crate) fn system_exception_reply(
version: Version,
order: ByteOrder,
request_id: u32,
e: &SystemException,
contexts: &[ServiceContext],
) -> Option<Vec<u8>> {
let mut m = start(
version,
order,
request_id,
ReplyStatus::SystemException,
contexts,
)
.ok()?;
SystemExceptionBody::from(e).encode(m.body()).ok()?;
m.finish().ok()
}