Reference

Client API


The Client connects to the Orcher server over gRPC. It starts workflows and returns WorkflowHandles, through which you wait for results, send events, run queries and updates, and cancel, terminate or reset workflows. It also lists workflows, calls actors and manages namespaces.


Connecting

1
use orcher_sdk::prelude::*;
2
3
pub async fn connect_locally() -> Result<Client> {
4
// Namespace "default", 30-second request timeout, no credentials.
5
// The channel connects lazily: an unreachable server shows up on the
6
// first call, not here.
7
Client::connect("http://localhost:50051").await
8
}

Client::connect(url) uses the defaults: namespace default, a 30-second timeout per request and no credentials, with TLS for an https:// URL only. For anything else, build a ClientConfig:

1
use orcher_sdk::client::ClientConfig;
2
3
pub async fn connect_to_server() -> Result<Client> {
4
let api_key = std::env::var("ORCHER_API_KEY")
5
.map_err(|_| Error::Configuration("ORCHER_API_KEY is not set".to_string()))?;
6
7
let config = ClientConfig::new("https://orcher.example.com:443")
8
// Workflows started without a namespace of their own go here.
9
.with_namespace("payments")
10
// Sent as `authorization: Bearer <key>` on every call.
11
.with_api_key(api_key)
12
// An https:// URL connects over TLS, verified against the system
13
// trust store; no TLS setting is needed for that.
14
.with_timeout(std::time::Duration::from_secs(60));
15
16
Client::with_config(config).await
17
}
ClientConfig methodDefaultDescription
ClientConfig::new(url)http://localhost:50051Server URL, with its scheme
with_namespace(name)defaultNamespace for starts and handles that don't name one
with_api_key(key)NoneSent as authorization: Bearer <key> on every call
with_organization_id(id)NoneSent as x-organization-id; only for an API key that doesn't belong to an organization itself
with_tls(ClientTlsConfig)None (follows the URL scheme)A private CA, a client certificate for mutual TLS, or another server name (below)
with_timeout(duration)30 sTimeout for each request
with_identity(name)orcher-client-<uuid>Identity reported to the server

The SDK doesn't read ORCHER_API_KEY or any other variable for the client; pass the key in yourself. A client that is already connected can also take a key: Client::with_api_key returns a client that sends it from the next call on, over the same connection (since 0.7.1; earlier it changed nothing that was sent). Clones taken before the call keep their old credentials.

1
pub async fn connect_then_authenticate(api_key: String) -> Result<Client> {
2
let client = Client::connect("https://orcher.example.com:443").await?;
3
// Sent from the next call on; clones taken before keep their old key.
4
Ok(client.with_api_key(api_key))
5
}

TLS belongs to the connection, so set it on the ClientConfig before Client::with_config. Client::with_tls is deprecated: it never changed a connected client.

TLS and mutual TLS

TLS follows the URL scheme. An https:// URL connects over TLS and verifies the server against the system trust store, with no other setting. An http:// URL connects in plaintext, even with a ClientTlsConfig set (the SDK logs a warning), so use https:// whenever the server expects TLS.

A ClientTlsConfig adds certificates. Give a CA only for a private or self-signed authority, and a client certificate and key for mutual TLS:

1
use orcher_sdk::client::ClientTlsConfig;
2
3
pub async fn connect_with_mtls() -> Result<Client> {
4
let tls = ClientTlsConfig::new()
5
// Only for a private or self-signed authority; without it the server
6
// is verified against the system trust store.
7
.with_ca_cert_file("/etc/orcher/ca.pem")?
8
// The client certificate and key, for mutual TLS.
9
.with_client_identity_files("/etc/orcher/client.pem", "/etc/orcher/client-key.pem")?;
10
11
// TLS needs an https:// URL; an http:// one stays plaintext.
12
let config = ClientConfig::new("https://orcher.internal:443").with_tls(tls);
13
Client::with_config(config).await
14
}
ClientTlsConfig methodDescription
new()Verify the server against the system trust store, with no client certificate
with_ca_cert_file(path)? / with_ca_cert(pem)Verify the server against this CA instead
with_client_identity_files(cert, key)? / with_client_identity(cert, key)Present this client certificate and key, for mutual TLS
with_domain_name(name)The name used for SNI and certificate verification, instead of the URL's host

The _file and _files methods read PEM files and return an std::io::Error naming the path if one can't be read; the others take PEM bytes you already have:

1
pub fn tls_from_pem(ca: Vec<u8>, cert: Vec<u8>, key: Vec<u8>) -> ClientTlsConfig {
2
// PEM already in memory, from a secret store for example.
3
ClientTlsConfig::new()
4
.with_ca_cert(ca)
5
.with_client_identity(cert, key)
6
// Verify the certificate against this name, not the URL's host.
7
.with_domain_name("orcher.internal")
8
}

A client certificate without its key, or PEM that doesn't parse, makes Client::with_config return ClientError::ConnectionFailed. When a handshake fails, the error names the cause, such as a certificate the client doesn't trust or a client certificate the server requires. The worker takes the same ClientTlsConfig.

Automatic TLS for https:// URLs needs orcher-sdk 0.7.1 or later; in 0.7.0 an https:// URL connected only with with_tls set.


Starting Workflows

1
pub async fn start_quickly(client: &Client) -> Result<WorkflowHandle> {
2
// A generated workflow id, on the task queue named "default".
3
client
4
.start_workflow(
5
"process_order",
6
OrderInput {
7
order_id: "ord_1".to_string(),
8
amount_cents: 4_200,
9
},
10
)
11
.await
12
}

start_workflow(type, input) generates the workflow id and puts the workflow on the task queue named default. Make sure a worker polls that queue, or use start_workflow_with_options:

1
use orcher_sdk::client::{StartWorkflowOptions, WorkflowIdReusePolicy};
2
3
pub async fn start_order(client: &Client, order_id: &str) -> Result<WorkflowHandle> {
4
let options = StartWorkflowOptions::new("orders")
5
.with_workflow_id(format!("order-{order_id}"))
6
.with_namespace("payments")
7
// The whole execution, across retries and fresh restarts.
8
.with_workflow_execution_timeout(std::time::Duration::from_secs(30 * 60))
9
.with_id_reuse_policy(WorkflowIdReusePolicy::RejectDuplicate);
10
11
client
12
.start_workflow_with_options(
13
"process_order",
14
OrderInput {
15
order_id: order_id.to_string(),
16
amount_cents: 4_200,
17
},
18
options,
19
)
20
.await
21
}
StartWorkflowOptions methodDescription
StartWorkflowOptions::new(task_queue)The task queue; everything else unset
with_workflow_id(id)Your own id; generated when unset
with_namespace(name)Start in this namespace instead of the client's
with_workflow_execution_timeout(duration)Deadline for the whole execution (below)
with_workflow_run_timeout(duration)Limit on a single run
with_id_reuse_policy(policy)What to do if the id is already in use (below)
with_retry_policy(policy)Retry a failed workflow as a fresh run (below)
with_cron_schedule(expr)Run on a cron schedule

The handle returned by a start keeps the namespace the workflow was started in, so later calls through it go to the same namespace.

Execution deadline

with_workflow_execution_timeout bounds the whole workflow, retries and fresh restarts included. When it passes, the workflow is marked timed out and stops. Without it a workflow runs until it finishes, however long that takes.

Duplicate starts and id reuse

A workflow id names at most one open run in a namespace. Starting an id whose run is still open fails with ClientError::WorkflowAlreadyExists, which carries the open run's id, under every policy except TerminateIfRunning. The policies differ in what they allow once earlier runs have closed:

WorkflowIdReusePolicyA start with an id already used
AllowDuplicateStarts once the previous run has closed, however it closed
AllowDuplicateFailedOnlyStarts only if the previous run failed, was cancelled, terminated or timed out
RejectDuplicateNever starts an id any run has carried
TerminateIfRunningTerminates the open run, if there is one, and starts

With no policy, the server allows a new run once the previous one has closed. To make a start idempotent, choose the workflow id from your own data, and attach to the existing run when the id is taken:

1
use orcher_sdk::error::ClientError;
2
3
/// Starts the order's workflow, or attaches to the run already doing it.
4
pub async fn start_once(client: &Client, order_id: &str) -> Result<WorkflowHandle> {
5
match start_order(client, order_id).await {
6
Ok(handle) => Ok(handle),
7
Err(Error::Client(ClientError::WorkflowAlreadyExists {
8
workflow_id,
9
run_id,
10
..
11
})) => {
12
client
13
.get_workflow_handle_with_run_id(workflow_id, run_id)
14
.await
15
}
16
Err(e) => Err(e),
17
}
18
}

Retrying a workflow

A workflow that fails is not retried by default; recover with task retries and compensation. With a retry policy, a failed run is retried as a fresh run with its own history:

1
use orcher_sdk::task::RetryPolicy;
2
3
pub fn retried_start() -> StartWorkflowOptions {
4
// Off by default: a failed workflow stays failed. With a policy, a failed
5
// run is retried as a fresh run with its own history.
6
StartWorkflowOptions::new("orders").with_retry_policy(
7
RetryPolicy::default()
8
.with_max_attempts(3)
9
.with_initial_interval(std::time::Duration::from_secs(10)),
10
)
11
}

Cron schedules

1
pub fn every_night() -> StartWorkflowOptions {
2
StartWorkflowOptions::new("reports")
3
.with_workflow_id("nightly-report")
4
.with_cron_schedule("0 2 * * *")
5
}

Starting many workflows

client.batch_start_workflows(type, inputs, options) starts one workflow per input in a single request. The server generates the ids, the inputs are sent as plain JSON (without a codec), and the options' workflow id, cron schedule and reuse policy are not applied.


Workflow Handles

1
pub async fn work_with_a_handle(client: &Client) -> Result<()> {
2
// A handle to the latest run of an existing workflow. No request is made
3
// until you use it.
4
let handle = client.get_workflow_handle("order-ord_1").await?;
5
6
println!("workflow {} (run {:?})", handle.id(), handle.run_id());
7
println!("status {:?}", handle.status().await?);
8
9
// Deliver an event to `ctx.wait_for_event("approval")`.
10
handle
11
.send_event("approval", serde_json::json!({ "approved": true, "approver": "kim" }))
12
.await?;
13
14
// Run a query handler. The SDK sends the argument, but a Rust workflow's
15
// handlers take none, so pass `()`.
16
let phase: String = handle.query("phase", ()).await?;
17
println!("phase {phase}");
18
19
// Run an update handler and wait for its result.
20
let accepted: bool = handle
21
.update(
22
"change_address",
23
serde_json::json!({ "street": "1 Main St", "city": "Springfield" }),
24
)
25
.await?;
26
println!("address change accepted: {accepted}");
27
28
// Wait for the result, but give up waiting after five minutes. The
29
// workflow keeps running either way.
30
let output: OrderOutput = handle.result_with_timeout(std::time::Duration::from_secs(300)).await?;
31
println!("{} finished: {}", output.order_id, output.status);
32
Ok(())
33
}

get_workflow_handle(id) targets the latest run in the client's namespace, and get_workflow_handle_with_run_id(id, Some(run_id)) a specific run. Neither makes a request; an unknown id shows up on the first call through the handle.

1
pub async fn stop(client: &Client) -> Result<()> {
2
let handle = client.get_workflow_handle("order-ord_2").await?;
3
4
// Ask the workflow to cancel; returns once the request is accepted.
5
handle.cancel().await?;
6
7
// Or end it at once, with no chance to clean up.
8
let other = client.get_workflow_handle("order-ord_3").await?;
9
other.terminate("duplicate order").await?;
10
Ok(())
11
}

cancel() asks the workflow to cancel and lets it clean up; terminate(reason) ends it at once.

Resetting a workflow

reset(event_id, reason) keeps the journal up to and including event_id, ends the current execution with the status reset, and continues in a new execution that replays the kept events and makes fresh decisions from there. It returns the new execution's id. Find the event id in the workflow's history (orcher workflow history <workflow-id> on the CLI).

1
pub async fn reset_after_bad_deploy(client: &Client) -> Result<String> {
2
let handle = client.get_workflow_handle("order-ord_4").await?;
3
// Keep journal events up to and including event 5, end the current
4
// execution with status "reset", and continue in a new one from there.
5
handle.reset(5, "bad deploy of the shipping task").await
6
}

Listing Workflows

1
use orcher_sdk::{ListWorkflowsOptions, WorkflowStatus};
2
3
pub async fn running_orders(client: &Client) -> Result<Vec<String>> {
4
let mut ids = Vec::new();
5
let mut options = ListWorkflowsOptions::default()
6
.with_workflow_type("process_order")
7
.with_status_filter(vec![WorkflowStatus::Running])
8
.with_page_size(100);
9
loop {
10
let page = client.list_workflows(options.clone()).await?;
11
ids.extend(page.executions.iter().map(|e| e.workflow_id.clone()));
12
if !page.has_more() {
13
return Ok(ids);
14
}
15
options = options.with_next_page_token(page.next_page_token);
16
}
17
}

search_workflows(query, SearchWorkflowsOptions) takes an SQL-like query instead of filters.


Errors

Client calls return orcher_sdk::Error. The variants you will match most are Error::Client(ClientError::...) for connection, authentication and request failures (including WorkflowAlreadyExists) and Error::Workflow(WorkflowError::...) for the workflow's own outcome. error.code() gives a stable ErrorCode, such as WORKFLOW_ALREADY_EXISTS, and error.is_retryable() says whether repeating the call can help. Both enums are #[non_exhaustive], so end a match with a catch-all arm.

1
use orcher_sdk::error::WorkflowError;
2
3
pub async fn report(handle: &WorkflowHandle) {
4
match handle.result::<OrderOutput>().await {
5
Ok(output) => println!("{} {}", output.order_id, output.status),
6
Err(Error::Workflow(WorkflowError::Canceled)) => println!("cancelled"),
7
Err(Error::Workflow(WorkflowError::NotFound { workflow_id, .. })) => {
8
println!("no workflow {workflow_id}")
9
}
10
Err(e) => println!("failed [{}]: {e}", e.code()),
11
}
12
}

Payload Encoding

client.with_gzip_compression() and client.with_encryption(&key) encode workflow inputs before they are sent, with gzip or AES-256-GCM. The worker must decode them with the matching WorkerBuilder::with_gzip_compression() or with_encryption(&key). The server decodes payloads and stores plain JSON, so encryption protects data in transit only; it is not end-to-end encryption.


Client Reference

MethodDescription
Client::connect(url) / Client::with_config(config)Connect
start_workflow(type, input)Start with a generated id on the default queue
start_workflow_with_options(type, input, options)Start with StartWorkflowOptions
batch_start_workflows(type, inputs, options)Start one workflow per input
get_workflow_handle(id) / get_workflow_handle_with_run_id(id, run_id)Handle to an existing workflow
query_workflow(id, query, args)Query without getting a handle first
list_workflows(options) / search_workflows(query, options)List executions, a page at a time
actor::<A>(key) / invoke_actor(...) / send_actor(...)Call actors
create_namespace, get_namespace, list_namespaces, update_namespace, deprecate_namespace, delete_namespaceManage namespaces

WorkflowHandle

MethodDescription
id() / run_id()The workflow id; the run id, if the handle has one (Option)
result::<T>() / result_with_timeout::<T>(duration)Wait for the result
status() / describe()Current status; full metadata
send_event(name, payload)Send an event
query(name, ())Run a query handler
update(name, args)Run an update handler and wait for its result
cancel() / terminate(reason)Stop the workflow
reset(event_id, reason)Reset to a journal event; returns the new execution id

Next Steps

  • Workflows: receiving events, answering queries and updates
  • Worker: connecting workers to the same server and namespace
  • Patterns: approvals and other event-driven workflows