golem_rust/json.rs
1// Copyright 2024-2025 Golem Cloud
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::await_promise;
16use crate::bindings::golem::api::host::PromiseId;
17use serde::de::DeserializeOwned;
18use serde::Serialize;
19
20/// Awaits a promise blocking the execution of the agent. The agent is going to be
21/// suspended until the promise is completed.
22///
23/// The completed promise's payload is decoded as JSON.
24///
25/// Use `await_promise_json` for an async version of this function, allowing to interleave
26/// awaiting of the promise with other operations.
27pub fn blocking_await_promise_json<T: DeserializeOwned>(
28 promise_id: &PromiseId,
29) -> Result<T, serde_json::Error> {
30 let promise = crate::bindings::golem::api::host::get_promise(promise_id);
31 promise.subscribe().block();
32 let bytes = promise.get().unwrap();
33 serde_json::from_slice(&bytes)
34}
35
36/// Awaits a promise.
37///
38/// The completed promise's payload is decoded as JSON.
39///
40/// If only promises or timeouts are awaited simultaneously, the agent is going to be
41/// suspended until any of them completes.
42pub async fn await_promise_json<T: DeserializeOwned>(
43 promise_id: &PromiseId,
44) -> Result<T, serde_json::Error> {
45 let bytes = await_promise(promise_id).await;
46 serde_json::from_slice(&bytes)
47}
48
49/// Completes a promise with a JSON payload
50pub fn complete_promise_json<T: Serialize>(
51 promise_id: &PromiseId,
52 value: T,
53) -> Result<bool, serde_json::Error> {
54 let bytes = serde_json::to_vec(&value)?;
55 Ok(crate::bindings::golem::api::host::complete_promise(
56 promise_id, &bytes,
57 ))
58}