Skip to content

Commit 99f3708

Browse files
committed
Add doctest example
1 parent 9a3e074 commit 99f3708

File tree

3 files changed

+74
-9
lines changed

3 files changed

+74
-9
lines changed

sdk-core-protos/src/lib.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,10 @@ pub mod coresdk {
260260
coresdk::{AsJsonPayloadExt, IntoPayloadsExt},
261261
temporal::api::common::v1::{Payload as ApiPayload, Payloads},
262262
};
263-
use std::collections::HashMap;
264-
use std::fmt::{Display, Formatter};
263+
use std::{
264+
collections::HashMap,
265+
fmt::{Display, Formatter},
266+
};
265267

266268
impl<T> From<T> for Payload
267269
where

sdk/Cargo.toml

+3
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,14 @@ categories = ["development-tools"]
1414

1515
[dependencies]
1616
anyhow = "1.0"
17+
base64 = "0.13"
1718
crossbeam = "0.8"
1819
derive_more = "0.99"
1920
futures = "0.3"
21+
once_cell = "1.10"
2022
parking_lot = { version = "0.12", features = ["send_guard"] }
2123
prost-types = "0.9"
24+
sha2 = "0.10"
2225
serde = "1.0"
2326
tokio = { version = "1.1", features = ["rt", "rt-multi-thread", "parking_lot", "time", "fs"] }
2427
tokio-util = { version = "0.7" }

sdk/src/lib.rs

+67-7
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,36 @@
11
#![warn(missing_docs)] // error if there are missing docs
22

3-
//! This crate is a rough prototype Rust SDK. It can be used to create closures that look sort of
4-
//! like normal workflow code. It should only depend on things in the core crate that are already
5-
//! publicly exposed.
3+
//! This crate defines an alpha-stage Temporal Rust SDK.
64
//!
7-
//! Needs lots of love to be production ready but the basis is there
5+
//! Currently defining activities and running an activity-only worker is the most stable code.
6+
//! Workflow definitions exist and running a workflow worker works, but the API is still very
7+
//! unstable.
8+
//!
9+
//! An example of running an activity worker:
10+
//! ```no_run
11+
//! use std::sync::Arc;
12+
//! use std::str::FromStr;
13+
//! use temporal_sdk::{sdk_client_options, Worker};
14+
//! use temporal_sdk_core::{init_worker, Url};
15+
//! use temporal_sdk_core_api::worker::{WorkerConfig, WorkerConfigBuilder};
16+
//!
17+
//! #[tokio::main]
18+
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
19+
//! let server_options = sdk_client_options(Url::from_str("http://localhost:7233")?).build()?;
20+
//! let client = server_options.connect("my_namespace", None).await?;
21+
//! let worker_config = WorkerConfigBuilder::default().build()?;
22+
//! let core_worker = init_worker(worker_config, client);
23+
//!
24+
//! let mut worker = Worker::new(Arc::new(core_worker), "task_queue", None);
25+
//! worker.register_activity(
26+
//! "echo_activity",
27+
//! |echo_me: String| async move { Ok(echo_me) },
28+
//! );
29+
//! // TODO: This should be different
30+
//! worker.run_until_done().await?;
31+
//! Ok(())
32+
//! }
33+
//! ```
834
935
#[macro_use]
1036
extern crate tracing;
@@ -22,6 +48,7 @@ pub use workflow_context::{
2248
use crate::workflow_context::{ChildWfCommon, PendingChildWorkflow};
2349
use anyhow::{anyhow, bail};
2450
use futures::{future::BoxFuture, stream::FuturesUnordered, FutureExt, StreamExt};
51+
use once_cell::sync::OnceCell;
2552
use std::{
2653
collections::HashMap,
2754
fmt::{Debug, Display, Formatter},
@@ -32,7 +59,8 @@ use std::{
3259
},
3360
time::Duration,
3461
};
35-
use temporal_client::{ServerGatewayApis, WorkflowOptions};
62+
use temporal_client::{ServerGatewayApis, ServerGatewayOptionsBuilder, WorkflowOptions};
63+
use temporal_sdk_core::Url;
3664
use temporal_sdk_core_api::{
3765
errors::{PollActivityError, PollWfError},
3866
Worker as CoreWorker,
@@ -64,6 +92,21 @@ use tokio::{
6492
};
6593
use tokio_util::sync::CancellationToken;
6694

95+
const VERSION: &str = env!("CARGO_PKG_VERSION");
96+
97+
/// Returns a [ServerGatewayOptionsBuilder] with required fields set to appropriate values
98+
/// for the Rust SDK.
99+
pub fn sdk_client_options(url: impl Into<Url>) -> ServerGatewayOptionsBuilder {
100+
let mut builder = ServerGatewayOptionsBuilder::default();
101+
builder
102+
.target_url(url)
103+
.client_name("rust-sdk".to_string())
104+
.client_version(VERSION.to_string())
105+
.worker_binary_id(binary_id().to_string());
106+
107+
builder
108+
}
109+
67110
/// A worker that can poll for and respond to workflow tasks by using [WorkflowFunction]s,
68111
/// and activity tasks by using [ActivityFunction]s
69112
pub struct Worker {
@@ -96,12 +139,12 @@ impl Worker {
96139
/// Create a new rust worker
97140
pub fn new(
98141
worker: Arc<dyn CoreWorker>,
99-
task_queue: String,
142+
task_queue: impl Into<String>,
100143
task_timeout: Option<Duration>,
101144
) -> Self {
102145
Self {
103146
worker,
104-
task_queue,
147+
task_queue: task_queue.into(),
105148
task_timeout,
106149
workflow_half: WorkflowHalf {
107150
workflows: Default::default(),
@@ -683,3 +726,20 @@ where
683726
Arc::new(wrapper)
684727
}
685728
}
729+
730+
/// Reads own binary, hashes it, and returns b64 str version of that hash
731+
fn binary_id() -> &'static str {
732+
use sha2::{Digest, Sha256};
733+
use std::{env, fs, io};
734+
735+
static INSTANCE: OnceCell<String> = OnceCell::new();
736+
INSTANCE.get_or_init(|| {
737+
let exe_path = env::current_exe().expect("Cannot read own binary to determine binary id");
738+
let mut exe_file =
739+
fs::File::open(exe_path).expect("Cannot read own binary to determine binary id");
740+
let mut hasher = Sha256::new();
741+
io::copy(&mut exe_file, &mut hasher).expect("Copying data into binary hasher works");
742+
let hash = hasher.finalize();
743+
base64::encode(hash)
744+
})
745+
}

0 commit comments

Comments
 (0)