golem-rust 2.0.0-dev.7

Golem Rust tooling library that facilitates writing Golem backends in Rust
Documentation
// Copyright 2024-2026 Golem Cloud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

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
    }
}