golem_rust/
lib.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 std::fmt;
16use std::fmt::{Display, Formatter};
17use std::str::FromStr;
18
19#[cfg(test)]
20test_r::enable!();
21
22pub use uuid::Uuid;
23
24pub mod bindings {
25    use wit_bindgen::generate;
26
27    generate!({
28        path: "wit",
29        world: "golem-rust",
30        generate_all,
31        generate_unused_types: true,
32        pub_export_macro: true,
33        with: {
34            "golem:rpc/types@0.2.2": golem_wasm::golem_rpc_0_2_x::types,
35            "wasi:io/poll@0.2.3": golem_wasm::wasi::io::poll,
36            "wasi:clocks/wall-clock@0.2.3": golem_wasm::wasi::clocks::wall_clock
37        }
38    });
39}
40
41#[cfg(feature = "export_load_snapshot")]
42pub mod load_snapshot {
43    use wit_bindgen::generate;
44
45    generate!({
46        path: "wit",
47        world: "golem-rust-load-snapshot",
48        generate_all,
49        generate_unused_types: true,
50        pub_export_macro: true,
51        with: {
52            "golem:rpc/types@0.2.2": golem_wasm::golem_rpc_0_2_x::types,
53            "wasi:io/poll@0.2.3": golem_wasm::wasi::io::poll,
54            "wasi:clocks/wall-clock@0.2.3": golem_wasm::wasi::clocks::wall_clock,
55
56            "golem:api/host@1.3.0": crate::bindings::golem::api::host,
57            "golem:api/oplog@1.3.0": crate::bindings::golem::api::oplog,
58            "golem:api/context@1.3.0": crate::bindings::golem::api::context,
59            "golem:durability/durability@1.3.0": crate::bindings::golem::durability::durability,
60            "golem:rdbms/mysql@0.0.1": crate::bindings::golem::rdbms::mysql,
61            "golem:rdbms/postgres@0.0.1": crate::bindings::golem::rdbms::postgres,
62            "golem:rdbms/types@0.0.1": crate::bindings::golem::rdbms::types,
63            "wasi:blobstore/blobstore": crate::bindings::wasi::blobstore::blobstore,
64            "wasi:blobstore/container": crate::bindings::wasi::blobstore::container,
65            "wasi:blobstore/types": crate::bindings::wasi::blobstore::types,
66            "wasi:clocks/monotonic-clock@0.2.3": crate::bindings::wasi::clocks::monotonic_clock,
67            "wasi:filesystem/preopens@0.2.3": crate::bindings::wasi::filesystem::preopens,
68            "wasi:filesystem/types@0.2.3": crate::bindings::wasi::filesystem::types,
69            "wasi:http/types@0.2.3": crate::bindings::wasi::http::types,
70            "wasi:http/outgoing-handler@0.2.3": crate::bindings::wasi::http::outgoing_handler,
71            "wasi:io/error@0.2.3": crate::bindings::wasi::io::error,
72            "wasi:io/streams@0.2.3": crate::bindings::wasi::io::streams,
73            "wasi:keyvalue/eventual-batch@0.1.0": crate::bindings::wasi::keyvalue::eventual_batch,
74            "wasi:keyvalue/eventual@0.1.0": crate::bindings::wasi::keyvalue::eventual,
75            "wasi:keyvalue/types@0.1.0": crate::bindings::wasi::keyvalue::types,
76            "wasi:keyvalue/wasi-keyvalue-error@0.1.0": crate::bindings::wasi::keyvalue::wasi_keyvalue_error,
77            "wasi:logging/logging": crate::bindings::wasi::logging::logging,
78            "wasi:sockets/ip-name-lookup@0.2.3": crate::bindings::wasi::sockets::ip_name_lookup,
79            "wasi:sockets/instance-network@0.2.3": crate::bindings::wasi::sockets::instance_network,
80            "wasi:sockets/network@0.2.3": crate::bindings::wasi::sockets::network,
81        }
82    });
83
84    pub use __export_golem_rust_load_snapshot_impl as export_load_snapshot;
85}
86
87#[cfg(feature = "export_save_snapshot")]
88pub mod save_snapshot {
89    use wit_bindgen::generate;
90
91    generate!({
92        path: "wit",
93        world: "golem-rust-save-snapshot",
94        generate_all,
95        generate_unused_types: true,
96        pub_export_macro: true,
97        with: {
98            "golem:rpc/types@0.2.2": golem_wasm::golem_rpc_0_2_x::types,
99            "wasi:io/poll@0.2.3": golem_wasm::wasi::io::poll,
100            "wasi:clocks/wall-clock@0.2.3": golem_wasm::wasi::clocks::wall_clock,
101
102            "golem:api/host@1.3.0": crate::bindings::golem::api::host,
103            "golem:api/oplog@1.3.0": crate::bindings::golem::api::oplog,
104            "golem:api/context@1.3.0": crate::bindings::golem::api::context,
105            "golem:durability/durability@1.3.0": crate::bindings::golem::durability::durability,
106            "golem:rdbms/mysql@0.0.1": crate::bindings::golem::rdbms::mysql,
107            "golem:rdbms/postgres@0.0.1": crate::bindings::golem::rdbms::postgres,
108            "golem:rdbms/types@0.0.1": crate::bindings::golem::rdbms::types,
109            "wasi:blobstore/blobstore": crate::bindings::wasi::blobstore::blobstore,
110            "wasi:blobstore/container": crate::bindings::wasi::blobstore::container,
111            "wasi:blobstore/types": crate::bindings::wasi::blobstore::types,
112            "wasi:clocks/monotonic-clock@0.2.3": crate::bindings::wasi::clocks::monotonic_clock,
113            "wasi:filesystem/preopens@0.2.3": crate::bindings::wasi::filesystem::preopens,
114            "wasi:filesystem/types@0.2.3": crate::bindings::wasi::filesystem::types,
115            "wasi:http/types@0.2.3": crate::bindings::wasi::http::types,
116            "wasi:http/outgoing-handler@0.2.3": crate::bindings::wasi::http::outgoing_handler,
117            "wasi:io/error@0.2.3": crate::bindings::wasi::io::error,
118            "wasi:io/streams@0.2.3": crate::bindings::wasi::io::streams,
119            "wasi:keyvalue/eventual-batch@0.1.0": crate::bindings::wasi::keyvalue::eventual_batch,
120            "wasi:keyvalue/eventual@0.1.0": crate::bindings::wasi::keyvalue::eventual,
121            "wasi:keyvalue/types@0.1.0": crate::bindings::wasi::keyvalue::types,
122            "wasi:keyvalue/wasi-keyvalue-error@0.1.0": crate::bindings::wasi::keyvalue::wasi_keyvalue_error,
123            "wasi:logging/logging": crate::bindings::wasi::logging::logging,
124            "wasi:sockets/ip-name-lookup@0.2.3": crate::bindings::wasi::sockets::ip_name_lookup,
125            "wasi:sockets/instance-network@0.2.3": crate::bindings::wasi::sockets::instance_network,
126            "wasi:sockets/network@0.2.3": crate::bindings::wasi::sockets::network,
127        }
128    });
129
130    pub use __export_golem_rust_save_snapshot_impl as export_save_snapshot;
131}
132
133#[cfg(feature = "export_golem_agentic")]
134pub mod golem_agentic {
135    use wit_bindgen::generate;
136
137    generate!({
138        path: "wit",
139        world: "golem-agentic",
140        generate_all,
141        generate_unused_types: true,
142        pub_export_macro: true,
143        with: {
144            "golem:rpc/types@0.2.2": golem_wasm::golem_rpc_0_2_x::types,
145        }
146    });
147
148    pub use __export_golem_agentic_impl as export_golem_agentic;
149}
150
151#[cfg(feature = "export_golem_agentic")]
152pub use ctor;
153
154#[cfg(feature = "export_golem_agentic")]
155pub use async_trait;
156
157#[cfg(feature = "export_oplog_processor")]
158pub mod oplog_processor {
159    use wit_bindgen::generate;
160
161    generate!({
162        path: "wit",
163        world: "golem-rust-oplog-processor",
164        generate_all,
165        generate_unused_types: true,
166        pub_export_macro: true,
167        with: {
168            "golem:rpc/types@0.2.2": golem_wasm::golem_rpc_0_2_x::types,
169            "wasi:io/poll@0.2.3": golem_wasm::wasi::io::poll,
170            "wasi:clocks/wall-clock@0.2.3": golem_wasm::wasi::clocks::wall_clock,
171
172            "golem:api/host@1.3.0": crate::bindings::golem::api::host,
173            "golem:api/oplog@1.3.0": crate::bindings::golem::api::oplog,
174            "golem:api/context@1.3.0": crate::bindings::golem::api::context,
175            "golem:durability/durability@1.3.0": crate::bindings::golem::durability::durability,
176            "golem:rdbms/mysql@0.0.1": crate::bindings::golem::rdbms::mysql,
177            "golem:rdbms/postgres@0.0.1": crate::bindings::golem::rdbms::postgres,
178            "golem:rdbms/types@0.0.1": crate::bindings::golem::rdbms::types,
179            "wasi:blobstore/blobstore": crate::bindings::wasi::blobstore::blobstore,
180            "wasi:blobstore/container": crate::bindings::wasi::blobstore::container,
181            "wasi:blobstore/types": crate::bindings::wasi::blobstore::types,
182            "wasi:clocks/monotonic-clock@0.2.3": crate::bindings::wasi::clocks::monotonic_clock,
183            "wasi:filesystem/preopens@0.2.3": crate::bindings::wasi::filesystem::preopens,
184            "wasi:filesystem/types@0.2.3": crate::bindings::wasi::filesystem::types,
185            "wasi:http/types@0.2.3": crate::bindings::wasi::http::types,
186            "wasi:http/outgoing-handler@0.2.3": crate::bindings::wasi::http::outgoing_handler,
187            "wasi:io/error@0.2.3": crate::bindings::wasi::io::error,
188            "wasi:io/streams@0.2.3": crate::bindings::wasi::io::streams,
189            "wasi:keyvalue/eventual-batch@0.1.0": crate::bindings::wasi::keyvalue::eventual_batch,
190            "wasi:keyvalue/eventual@0.1.0": crate::bindings::wasi::keyvalue::eventual,
191            "wasi:keyvalue/types@0.1.0": crate::bindings::wasi::keyvalue::types,
192            "wasi:keyvalue/wasi-keyvalue-error@0.1.0": crate::bindings::wasi::keyvalue::wasi_keyvalue_error,
193            "wasi:logging/logging": crate::bindings::wasi::logging::logging,
194            "wasi:sockets/ip-name-lookup@0.2.3": crate::bindings::wasi::sockets::ip_name_lookup,
195            "wasi:sockets/instance-network@0.2.3": crate::bindings::wasi::sockets::instance_network,
196            "wasi:sockets/network@0.2.3": crate::bindings::wasi::sockets::network,
197        }
198    });
199
200    pub use __export_golem_rust_oplog_processor_impl as export_oplog_processor;
201}
202
203#[cfg(feature = "export_golem_agentic")]
204pub mod agentic;
205
206#[cfg(feature = "durability")]
207pub mod durability;
208
209#[cfg(feature = "json")]
210mod json;
211
212#[cfg(feature = "json")]
213pub use json::*;
214
215mod transaction;
216pub mod value_and_type;
217
218use bindings::golem::api::host::*;
219
220pub use golem_wasm as wasm_rpc;
221
222pub use bindings::golem::api::host::{fork, oplog_commit};
223pub use bindings::golem::api::host::{ForkResult, PersistenceLevel};
224
225pub use transaction::*;
226
227#[cfg(feature = "macro")]
228pub use golem_rust_macro::*;
229
230impl Display for PromiseId {
231    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
232        write!(f, "{}/{}", self.agent_id, self.oplog_idx)
233    }
234}
235
236impl FromStr for PromiseId {
237    type Err = String;
238
239    fn from_str(s: &str) -> Result<Self, Self::Err> {
240        let parts: Vec<&str> = s.split('/').collect();
241        if parts.len() == 2 {
242            let agent_id = AgentId::from_str(parts[0]).map_err(|_| {
243                format!("invalid agent id: {s} - expected format: <component_id>/<agent_id>")
244            })?;
245            let oplog_idx = parts[1]
246                .parse()
247                .map_err(|_| format!("invalid oplog index: {s} - expected integer"))?;
248            Ok(Self {
249                agent_id,
250                oplog_idx,
251            })
252        } else {
253            Err(format!(
254                "invalid promise id: {s} - expected format: <agent_id>/<oplog_idx>"
255            ))
256        }
257    }
258}
259
260#[derive(Clone, Debug, PartialEq)]
261pub struct RetryPolicy {
262    pub max_attempts: u32,
263    pub min_delay: std::time::Duration,
264    pub max_delay: std::time::Duration,
265    pub multiplier: f64,
266    pub max_jitter_factor: Option<f64>,
267}
268
269impl From<bindings::golem::api::host::RetryPolicy> for RetryPolicy {
270    fn from(value: bindings::golem::api::host::RetryPolicy) -> Self {
271        Self {
272            max_attempts: value.max_attempts,
273            min_delay: std::time::Duration::from_nanos(value.min_delay),
274            max_delay: std::time::Duration::from_nanos(value.max_delay),
275            multiplier: value.multiplier,
276            max_jitter_factor: value.max_jitter_factor,
277        }
278    }
279}
280
281impl From<RetryPolicy> for bindings::golem::api::host::RetryPolicy {
282    fn from(val: RetryPolicy) -> Self {
283        bindings::golem::api::host::RetryPolicy {
284            max_attempts: val.max_attempts,
285            min_delay: val.min_delay.as_nanos() as u64,
286            max_delay: val.max_delay.as_nanos() as u64,
287            multiplier: val.multiplier,
288            max_jitter_factor: val.max_jitter_factor,
289        }
290    }
291}
292
293pub struct PersistenceLevelGuard {
294    original_level: PersistenceLevel,
295}
296
297impl Drop for PersistenceLevelGuard {
298    fn drop(&mut self) {
299        set_oplog_persistence_level(self.original_level);
300    }
301}
302
303/// Temporarily sets the oplog persistence level to the given value.
304///
305/// When the returned guard is dropped, the original persistence level is restored.
306#[must_use]
307pub fn use_persistence_level(level: PersistenceLevel) -> PersistenceLevelGuard {
308    let original_level = get_oplog_persistence_level();
309    set_oplog_persistence_level(level);
310    PersistenceLevelGuard { original_level }
311}
312
313/// Executes the given function with the oplog persistence level set to the given value.
314pub fn with_persistence_level<R>(level: PersistenceLevel, f: impl FnOnce() -> R) -> R {
315    let _guard = use_persistence_level(level);
316    f()
317}
318
319pub struct IdempotenceModeGuard {
320    original: bool,
321}
322
323impl Drop for IdempotenceModeGuard {
324    fn drop(&mut self) {
325        set_idempotence_mode(self.original);
326    }
327}
328
329/// Temporarily sets the idempotence mode to the given value.
330///
331/// When the returned guard is dropped, the original idempotence mode is restored.
332#[must_use]
333pub fn use_idempotence_mode(mode: bool) -> IdempotenceModeGuard {
334    let original = get_idempotence_mode();
335    set_idempotence_mode(mode);
336    IdempotenceModeGuard { original }
337}
338
339/// Executes the given function with the idempotence mode set to the given value.
340pub fn with_idempotence_mode<R>(mode: bool, f: impl FnOnce() -> R) -> R {
341    let _guard = use_idempotence_mode(mode);
342    f()
343}
344
345/// Generates an idempotency key. This operation will never be replayed —
346/// i.e. not only is this key generated, but it is persisted and committed, such that the key can be used in third-party systems (e.g. payment processing)
347/// to introduce idempotence.
348pub fn generate_idempotency_key() -> uuid::Uuid {
349    Into::into(bindings::golem::api::host::generate_idempotency_key())
350}
351
352pub struct RetryPolicyGuard {
353    original: RetryPolicy,
354}
355
356impl Drop for RetryPolicyGuard {
357    fn drop(&mut self) {
358        set_retry_policy(Into::into(self.original.clone()));
359    }
360}
361
362/// Temporarily sets the retry policy to the given value.
363///
364/// When the returned guard is dropped, the original retry policy is restored.
365#[must_use]
366pub fn use_retry_policy(policy: RetryPolicy) -> RetryPolicyGuard {
367    let original = Into::into(get_retry_policy());
368    set_retry_policy(Into::into(policy));
369    RetryPolicyGuard { original }
370}
371
372/// Executes the given function with the retry policy set to the given value.
373pub fn with_retry_policy<R>(policy: RetryPolicy, f: impl FnOnce() -> R) -> R {
374    let _guard = use_retry_policy(policy);
375    f()
376}
377
378pub struct AtomicOperationGuard {
379    begin: OplogIndex,
380}
381
382impl Drop for AtomicOperationGuard {
383    fn drop(&mut self) {
384        mark_end_operation(self.begin);
385    }
386}
387
388/// Marks a block as an atomic operation
389///
390/// When the returned guard is dropped, the operation gets committed.
391/// In case of a failure, the whole operation will be re-executed during retry.
392#[must_use]
393pub fn mark_atomic_operation() -> AtomicOperationGuard {
394    let begin = mark_begin_operation();
395    AtomicOperationGuard { begin }
396}
397
398/// Executes the given function as an atomic operation.
399///
400/// In case of a failure, the whole operation will be re-executed during retry.
401pub fn atomically<T>(f: impl FnOnce() -> T) -> T {
402    let _guard = mark_atomic_operation();
403    f()
404}