use serde::{de::DeserializeOwned, Serialize};
use std::collections::HashMap;
use crate::abi::{read_bytes, respond_err, respond_err_code, respond_err_retry, respond_ok};
use crate::error::{OpError, Outcome};
pub const ABI_VERSION: u32 = 1;
type OpFn = Box<dyn Fn(&[u8]) -> u64>;
#[derive(Default)]
pub struct Registry {
ops: HashMap<&'static str, OpFn>,
names: Vec<&'static str>,
context_names: Vec<&'static str>,
action_names: Vec<&'static str>,
channel_names: Vec<&'static str>,
chatops_names: Vec<&'static str>,
connector_names: Vec<&'static str>,
}
impl Registry {
pub fn new() -> Self {
Self {
ops: HashMap::new(),
names: Vec::new(),
context_names: Vec::new(),
action_names: Vec::new(),
channel_names: Vec::new(),
chatops_names: Vec::new(),
connector_names: Vec::new(),
}
}
pub fn op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
where
In: DeserializeOwned,
Out: Serialize,
F: Fn(In) -> Result<Out, OpError> + 'static,
{
if self.ops.contains_key(name) {
panic!("operation {name:?} is registered twice");
}
self.names.push(name);
self.ops.insert(
name,
Box::new(move |input_bytes: &[u8]| -> u64 {
let input: In = match decode_input(input_bytes) {
Ok(v) => v,
Err(e) => return respond_ok(&Outcome::<Out>::Error { message: format!("invalid input: {e}") }),
};
match f(input) {
Ok(v) => respond_ok(&Outcome::Ok { data: v }),
Err(OpError::NotConfigured) => respond_err_code("not configured", "not_configured"),
Err(OpError::TicketTypeNotEnabled) => {
respond_err_code("context is not enabled for this ticket type", "ticket_type_not_enabled")
}
Err(OpError::NotFound) => respond_ok(&Outcome::<Out>::NotFound),
Err(OpError::EndOfCollection(message)) => respond_ok(&Outcome::<Out>::EndOfCollection { message }),
Err(OpError::RateLimited { retry_after }) => {
respond_ok(&Outcome::<Out>::RateLimited { retry_after })
}
Err(OpError::Transient(message)) => respond_ok(&Outcome::<Out>::Transient { message }),
Err(OpError::Other(message)) => respond_ok(&Outcome::<Out>::Error { message }),
}
}),
);
self
}
pub fn context_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
where
In: DeserializeOwned,
Out: Serialize,
F: Fn(In) -> Result<Out, OpError> + 'static,
{
if self.ops.contains_key(name) {
panic!("operation {name:?} is registered twice");
}
self.names.push(name);
self.context_names.push(name);
self.ops.insert(name, raw_handler(f));
self
}
pub fn action_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
where
In: DeserializeOwned,
Out: Serialize,
F: Fn(In) -> Result<Out, OpError> + 'static,
{
if self.ops.contains_key(name) {
panic!("operation {name:?} is registered twice");
}
self.names.push(name);
self.action_names.push(name);
self.ops.insert(name, raw_handler(f));
self
}
pub fn channel_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
where
In: DeserializeOwned,
Out: Serialize,
F: Fn(In) -> Result<Out, OpError> + 'static,
{
if self.ops.contains_key(name) {
panic!("operation {name:?} is registered twice");
}
self.names.push(name);
self.channel_names.push(name);
self.ops.insert(name, raw_handler(f));
self
}
pub fn chatops_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
where
In: DeserializeOwned,
Out: Serialize,
F: Fn(In) -> Result<Out, OpError> + 'static,
{
if self.ops.contains_key(name) {
panic!("operation {name:?} is registered twice");
}
self.names.push(name);
self.chatops_names.push(name);
self.ops.insert(name, raw_handler(f));
self
}
pub fn connector_op<In, Out, F>(mut self, name: &'static str, f: F) -> Self
where
In: DeserializeOwned,
Out: Serialize,
F: Fn(In) -> Result<Out, OpError> + 'static,
{
if self.ops.contains_key(name) {
panic!("operation {name:?} is registered twice");
}
self.names.push(name);
self.connector_names.push(name);
self.ops.insert(name, raw_handler(f));
self
}
pub fn names(&self) -> &[&'static str] {
&self.names
}
pub fn action_names(&self) -> &[&'static str] {
&self.action_names
}
pub fn context_names(&self) -> &[&'static str] {
&self.context_names
}
pub fn channel_names(&self) -> &[&'static str] {
&self.channel_names
}
pub fn chatops_names(&self) -> &[&'static str] {
&self.chatops_names
}
pub fn connector_names(&self) -> &[&'static str] {
&self.connector_names
}
#[doc(hidden)]
pub fn dispatch(&self, op: &str, input_bytes: &[u8]) -> u64 {
match self.ops.get(op) {
Some(f) => f(input_bytes),
None => respond_err(&format!(
"unknown operation {op:?} (this plugin implements: {})",
self.names.join(", ")
)),
}
}
}
fn raw_handler<In, Out, F>(f: F) -> OpFn
where
In: DeserializeOwned,
Out: Serialize,
F: Fn(In) -> Result<Out, OpError> + 'static,
{
Box::new(move |input_bytes: &[u8]| -> u64 {
let input: In = match decode_input(input_bytes) {
Ok(v) => v,
Err(e) => return respond_err(&format!("invalid input: {e}")),
};
match f(input) {
Ok(v) => respond_ok(&v),
Err(OpError::NotConfigured) => respond_err_code("not configured", "not_configured"),
Err(OpError::TicketTypeNotEnabled) => {
respond_err_code("context is not enabled for this ticket type", "ticket_type_not_enabled")
}
Err(OpError::NotFound) => respond_err_code("not found", "not_found"),
Err(OpError::EndOfCollection(message)) => respond_err(&message),
Err(OpError::RateLimited { retry_after }) => respond_err_retry(
"rate limited",
"rate_limited",
&retry_after.unwrap_or_default(),
),
Err(OpError::Transient(message)) => respond_err_code(&message, "transient"),
Err(OpError::Other(message)) => respond_err(&message),
}
})
}
fn decode_input<In: DeserializeOwned>(bytes: &[u8]) -> Result<In, serde_json::Error> {
if bytes.is_empty() {
return serde_json::from_slice(b"null");
}
serde_json::from_slice(bytes)
}
#[derive(Serialize)]
pub struct Descriptor<'a> {
pub abi_version: u32,
pub sdk: &'a str,
pub sdk_version: &'a str,
#[serde(skip_serializing_if = "str::is_empty")]
pub name: &'a str,
#[serde(skip_serializing_if = "str::is_empty")]
pub version: &'a str,
pub ops: &'a [&'a str],
pub context_ops: &'a [&'a str],
pub action_ops: &'a [&'a str],
pub channel_ops: &'a [&'a str],
pub chatops_ops: &'a [&'a str],
pub connector_ops: &'a [&'a str],
}
#[doc(hidden)]
pub fn handle_call(op_ptr: u32, op_len: u32, in_ptr: u32, in_len: u32, build_registry: fn() -> Registry) -> u64 {
let op = match std::str::from_utf8(read_bytes(op_ptr, op_len)) {
Ok(s) => s,
Err(_) => return respond_err("operation name is not valid UTF-8"),
};
build_registry().dispatch(op, read_bytes(in_ptr, in_len))
}
#[doc(hidden)]
pub fn describe_call(name: &str, version: &str, build_registry: fn() -> Registry) -> u64 {
let registry = build_registry();
respond_ok(&Descriptor {
abi_version: ABI_VERSION,
sdk: env!("CARGO_PKG_NAME"),
sdk_version: env!("CARGO_PKG_VERSION"),
name,
version,
ops: registry.names(),
context_ops: registry.context_names(),
action_ops: registry.action_names(),
channel_ops: registry.channel_names(),
chatops_ops: registry.chatops_names(),
connector_ops: registry.connector_names(),
})
}