use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::collections::HashMap;
use crate::abi::{read_bytes, unpack, write_bytes, Envelope};
use crate::error::{code, HostError};
#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "salamandr")]
extern "C" {
fn host_log(ptr: u32, len: u32);
fn host_http_fetch(ptr: u32, len: u32) -> u64;
fn host_get_config(ptr: u32, len: u32) -> u64;
fn host_kv_get(ptr: u32, len: u32) -> u64;
fn host_kv_set(key_ptr: u32, key_len: u32, val_ptr: u32, val_len: u32) -> u64;
fn host_kv_delete(ptr: u32, len: u32) -> u64;
fn host_kv_list(ptr: u32, len: u32) -> u64;
fn host_core(ptr: u32, len: u32) -> u64;
fn host_oauth_fetch(ptr: u32, len: u32) -> u64;
fn host_http_upload(ptr: u32, len: u32) -> u64;
fn host_self() -> u64;
fn host_ws_send(ptr: u32, len: u32) -> u64;
fn host_richtext_to_markdown(ptr: u32, len: u32) -> u64;
fn host_richtext_to_jira_wiki(ptr: u32, len: u32) -> u64;
}
#[cfg(not(target_arch = "wasm32"))]
use crate::testing::{
host_core, host_get_config, host_http_fetch, host_http_upload, host_kv_delete, host_kv_get, host_kv_list,
host_kv_set, host_log, host_oauth_fetch, host_richtext_to_jira_wiki, host_richtext_to_markdown, host_self,
host_ws_send,
};
fn call_host<In: Serialize, Out: DeserializeOwned>(
host_fn: unsafe extern "C" fn(u32, u32) -> u64,
input: &In,
) -> Result<Out, HostError> {
let req_bytes = serde_json::to_vec(input).map_err(|e| HostError::new(e.to_string()))?;
call_host_bytes(host_fn, &req_bytes)
}
fn call_host_bytes<Out: DeserializeOwned>(
host_fn: unsafe extern "C" fn(u32, u32) -> u64,
input: &[u8],
) -> Result<Out, HostError> {
let (ptr, len) = write_bytes(input);
let packed = unsafe { host_fn(ptr, len) };
decode_envelope(packed)
}
fn call_host_bytes_ack(host_fn: unsafe extern "C" fn(u32, u32) -> u64, input: &[u8]) -> Result<(), HostError> {
let (ptr, len) = write_bytes(input);
let packed = unsafe { host_fn(ptr, len) };
let (out_ptr, out_len) = unpack(packed);
if out_len == 0 {
return Err(HostError::new("host function returned no result"));
}
let env: Envelope<()> =
serde_json::from_slice(read_bytes(out_ptr, out_len)).map_err(|e| HostError::new(e.to_string()))?;
if !env.ok {
return Err(HostError { code: env.code, message: env.error });
}
Ok(())
}
fn decode_envelope<Out: DeserializeOwned>(packed: u64) -> Result<Out, HostError> {
let (out_ptr, out_len) = unpack(packed);
if out_len == 0 {
return Err(HostError::new("host function returned no result"));
}
let env: Envelope<Out> =
serde_json::from_slice(read_bytes(out_ptr, out_len)).map_err(|e| HostError::new(e.to_string()))?;
if !env.ok {
return Err(HostError { code: env.code, message: env.error });
}
env.data.ok_or_else(|| HostError::new("host function returned no data"))
}
pub fn log(msg: &str) {
let (ptr, len) = write_bytes(msg.as_bytes());
unsafe { host_log(ptr, len) };
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct HttpRequest {
pub method: String,
pub url: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub headers: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<String>,
}
impl HttpRequest {
pub fn get(url: impl Into<String>) -> Self {
Self { method: "GET".into(), url: url.into(), ..Default::default() }
}
pub fn post(url: impl Into<String>, body: impl Into<String>) -> Self {
Self { method: "POST".into(), url: url.into(), body: Some(body.into()), ..Default::default() }
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.insert(name.into(), value.into());
self
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct HttpResponse {
pub status: u32,
#[serde(default)]
pub headers: HashMap<String, String>,
#[serde(default)]
pub body: String,
}
impl HttpResponse {
pub fn is_success(&self) -> bool {
(200..300).contains(&self.status)
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UploadRequest {
pub url: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub method: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub headers: HashMap<String, String>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub fields: HashMap<String, String>,
pub file_field: String,
pub attachment_id: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub file_name: String,
}
impl UploadRequest {
pub fn build(url: &str, file_field: &str, attachment_id: &str) -> Self {
Self {
url: url.to_string(),
file_field: file_field.to_string(),
attachment_id: attachment_id.to_string(),
..Default::default()
}
}
pub fn field(mut self, name: &str, value: &str) -> Self {
self.fields.insert(name.to_string(), value.to_string());
self
}
pub fn header(mut self, name: &str, value: &str) -> Self {
self.headers.insert(name.to_string(), value.to_string());
self
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SelfInfo {
#[serde(default)]
pub extension_id: String,
#[serde(default)]
pub name: String,
#[serde(default)]
pub version: String,
#[serde(default)]
pub kind: String,
#[serde(default)]
pub webhook_url: String,
#[serde(default)]
pub custom_webhook_url: String,
}
pub fn self_info() -> Result<SelfInfo, HostError> {
let packed = unsafe { host_self() };
decode_envelope(packed)
}
pub fn http_upload(req: UploadRequest) -> Result<HttpResponse, HostError> {
call_host(host_http_upload, &req)
}
pub fn http_fetch(req: HttpRequest) -> Result<HttpResponse, HostError> {
call_host(host_http_fetch, &req)
}
pub fn ws_send(frame: &str) -> Result<(), HostError> {
call_host_bytes_ack(host_ws_send, frame.as_bytes())
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct OAuthFetchRequest {
pub connection_user_id: String,
pub method: String,
pub url: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub headers: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<String>,
}
impl OAuthFetchRequest {
pub fn get(connection_user_id: impl Into<String>, url: impl Into<String>) -> Self {
Self { connection_user_id: connection_user_id.into(), method: "GET".into(), url: url.into(), ..Default::default() }
}
pub fn post(connection_user_id: impl Into<String>, url: impl Into<String>, body: impl Into<String>) -> Self {
Self {
connection_user_id: connection_user_id.into(),
method: "POST".into(),
url: url.into(),
body: Some(body.into()),
..Default::default()
}
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.insert(name.into(), value.into());
self
}
}
pub fn oauth_fetch(req: OAuthFetchRequest) -> Result<HttpResponse, HostError> {
call_host(host_oauth_fetch, &req)
}
pub fn get_config(key: &str) -> Result<Option<String>, HostError> {
match call_host_bytes::<String>(host_get_config, key.as_bytes()) {
Ok(v) => Ok(Some(v)),
Err(e) if e.code == code::NOT_SET => Ok(None),
Err(e) => Err(e),
}
}
pub fn richtext_to_markdown(html: &str) -> Result<String, HostError> {
call_host_bytes::<String>(host_richtext_to_markdown, html.as_bytes())
}
pub fn richtext_to_jira_wiki(html: &str) -> Result<String, HostError> {
call_host_bytes::<String>(host_richtext_to_jira_wiki, html.as_bytes())
}
pub fn kv_get(key: &str) -> Result<Option<String>, HostError> {
match call_host_bytes::<String>(host_kv_get, key.as_bytes()) {
Ok(v) => Ok(Some(v)),
Err(e) if e.is_not_found() => Ok(None),
Err(e) => Err(e),
}
}
pub fn kv_set(key: &str, value: &str) -> Result<(), HostError> {
let (key_ptr, key_len) = write_bytes(key.as_bytes());
let (val_ptr, val_len) = write_bytes(value.as_bytes());
let packed = unsafe { host_kv_set(key_ptr, key_len, val_ptr, val_len) };
let (out_ptr, out_len) = unpack(packed);
if out_len == 0 {
return Err(HostError::new("host_kv_set returned no result"));
}
let env: Envelope<()> =
serde_json::from_slice(read_bytes(out_ptr, out_len)).map_err(|e| HostError::new(e.to_string()))?;
if !env.ok {
return Err(HostError { code: env.code, message: env.error });
}
Ok(())
}
pub fn kv_delete(key: &str) -> Result<(), HostError> {
call_host_bytes_ack(host_kv_delete, key.as_bytes())
}
pub fn kv_list(prefix: &str) -> Result<Vec<String>, HostError> {
call_host_bytes::<Vec<String>>(host_kv_list, prefix.as_bytes())
}
#[derive(Serialize)]
struct CoreRequest<'a, P: Serialize> {
resource: &'a str,
action: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
params: Option<P>,
}
pub fn core_call<P: Serialize, Out: DeserializeOwned>(
resource: &str,
action: &str,
params: Option<P>,
) -> Result<Out, HostError> {
call_host(host_core, &CoreRequest { resource, action, params })
}