Working with Golem Promises in Python
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 Python the promise API can be used by directly importing and using the Golem runtime API.
Adding as a dependency
To use Golem's runtime API, add all the WIT files from https://github.com/golemcloud/golem-wit/tree/main/wit/deps (opens in a new tab) in the project's wit/deps
directory, and then importing this interface to the component's world:
world example {
import golem:api/host@0.2.0;
// ...
}
The golem-cli new
examples for Python automatically create the wit/deps
directory for you,
except the c-actor-minimal
one.
Creating a promise
To create a promise simply call the golem_create_promise
function:
from py_example.imports.host import golem_create_promise
promise_id = golem_create_promise()
The returned value, PromiseId
, is defined as the following:
@dataclass
class Uuid:
"""
UUID
"""
high_bits: int
low_bits: int
@dataclass
class ComponentId:
"""
Represents a Golem component
"""
uuid: Uuid
@dataclass
class WorkerId:
"""
Represents a Golem worker
"""
component_id: ComponentId
worker_name: str
@dataclass
class PromiseId:
"""
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.
"""
worker_id: WorkerId
oplog_idx: int
Deleting a promise
If a promise is no longer used, it has to be deleted with
golem_delete_promise(promise_id);
Awaiting a promise
To await a promise, use the golem_await_promise
function:
payload = golem_await_promise(promise_id)
The resulting payload
is a byte array (bytes
) 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:
golem_complete_promise(promise_id, str.encode("hello world"))
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.