Welcome to the new Golem Cloud Docs! 👋
Documentation
Rust Language Guide
Promises

Working with Golem Promises in Rust

Golem promises provide a way for Golem workers to wait on an external condition. The worker creates the promise and somehow sends its identifier to the external system responsible for completing the promise. Then the worker can await the promise, being suspended until the external system completes the promise using Golem's REST API.

It is also possible to complete a promise from within a Golem worker using the Golem SDK.

When a promise is completed, an arbitrary byte array can be attached to it as a payload - this data is returned to the awaiting worker when is continues execution.

In Rust the easiest way to work with promises is to use the golem-rust library.

Adding as a dependency

To use the Golem Rust library, add the following dependency to your component's Cargo.toml:

golem-rust = { version = "0.3.0" }
golem-rust-macro = { version = "0.3.0" }

Creating a promise

To create a promise simply call the golem_create_promise function:

use golem_rust::bindings::golem::api::host::golem_create_promise;
 
let promise_id = golem_create_promise();

The returned value is a PromiseId, defined as the following:

/// A promise ID is a value that can be passed to an external Golem API to complete that promise
/// from an arbitrary external source, while Golem workers can await for this completion.
#[derive(Clone)]
pub struct PromiseId {
    pub worker_id: WorkerId,
    pub oplog_idx: OplogIndex,
}
 
/// An index into the persistent log storing all performed operations of a worker
pub type OplogIndex = u64;
 
/// Represents a Golem worker
#[derive(Clone)]
pub struct WorkerId {
    pub component_id: ComponentId,
    pub worker_name: String,
}
 
/// Represents a Golem component
#[derive(Clone, Copy)]
pub struct ComponentId {
    pub uuid: Uuid,
}

Note that although this Uuid is a generated type from the WIT specification, the golem-rust crate provides From and Into implementations to convert it to the uuid crate's Uuid type.

Deleting a promise

If a promise is no longer used, it can be deleted with

use golem_rust::bindings::golem::api::host::golem_delete_promise;
golem_delete_promise(&promise_id);

Awaiting a promise

To await a promise, use the golem_await_promise function:

use golem_rust::bindings::golem::api::host::golem_await_promise;
let payload = golem_await_promise(&promise_id);

The resulting payload is a Vec<u8> containig the data attached to the promise on completion.

Completing a promise from within a worker

To complete a promise from within a worker, use the golem_complete_promise function:

use golem_rust::bindings::golem::api::host::golem_complete_promise;
golem_complete_promise(&promise_id, &payload);

where &payload has the type &[u8]

Completing a promise from an external source

To see how to use the promise ID to complete a promise through the external REST API, check the REST API documentation.