use crate::{PromiseId, await_promise, create_promise};
use std::future::Future;
use std::future::IntoFuture;
use std::pin::Pin;
pub fn create_webhook() -> WebhookHandler {
let promise_id = create_promise();
let webhook_url = crate::golem_agentic::golem::agent::host::create_webhook(&promise_id);
WebhookHandler::new(webhook_url, promise_id)
}
pub struct WebhookHandler {
url: String,
promise_id: PromiseId,
}
impl WebhookHandler {
fn new(url: String, promise_id: PromiseId) -> WebhookHandler {
WebhookHandler { url, promise_id }
}
async fn wait(self) -> WebhookRequestPayload {
let result = await_promise(&self.promise_id).await;
WebhookRequestPayload { payload: result }
}
pub fn url(&self) -> &str {
&self.url
}
}
impl IntoFuture for WebhookHandler {
type Output = WebhookRequestPayload;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output>>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(async move { self.wait().await })
}
}
pub struct WebhookRequestPayload {
payload: Vec<u8>,
}
impl WebhookRequestPayload {
pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T, String> {
serde_json::from_slice(&self.payload).map_err(|e| format!("Invalid input: {}", e))
}
pub fn raw_data(self) -> Vec<u8> {
self.payload
}
}