Reference

Client API


The Client talks to the engine over gRPC. Use it from any process (a web handler, a script, a test) to start workflows, wait for their results, send them events, query them, and list or search executions.


Connecting

1
config = ClientConfig(
2
server_url="http://localhost:50051",
3
namespace="default",
4
# api_key defaults to the ORCHER_API_KEY environment variable.
5
request_timeout=timedelta(seconds=30),
6
)
7
8
async with Client(config) as client:
9
handle = await client.start_workflow("order", task_queue="orders", args=("order-1",))
10
print(handle.workflow_id)

async with connects and closes the connection for you. Without it, call connect() before the first request and close() when done:

1
client = Client(config)
2
await client.connect()
3
try:
4
handle = await client.get_workflow("order-1")
5
finally:
6
await client.close()

ClientConfig

OptionDefaultDescription
server_urlrequiredThe engine's gRPC address; must start with http://, https:// or grpc://
namespace"default"The namespace the client works in
api_keyORCHER_API_KEYSent as authorization: Bearer <key> on every request; None or blank sends none; never shown by repr
identityNoneA name for this client
tls_ca_cert_pathNoneCA certificate (PEM) to verify the engine against, instead of the system trust store
tls_client_cert_pathNoneClient certificate (PEM), for mutual TLS
tls_client_key_pathNoneClient private key (PEM), for mutual TLS
connection_timeouttimedelta(seconds=10)How long connecting may take
request_timeouttimedelta(seconds=30)Default timeout for requests

Like the worker builder, ClientConfig reads ORCHER_API_KEY when api_key isn't given.

API keys and TLS

An engine that requires authentication rejects requests without a valid API key. api_key defaults to the ORCHER_API_KEY environment variable, so a client whose environment sets it needs no code. Pass a key to use another one, or None to send none:

1
def explicit_key_config() -> ClientConfig:
2
# A key from somewhere other than ORCHER_API_KEY.
3
return ClientConfig(
4
server_url="https://orcher.example.com:443",
5
api_key=os.environ["PAYMENTS_ORCHER_KEY"],
6
)
7
8
9
def no_key_config() -> ClientConfig:
10
# No key, even when ORCHER_API_KEY is set.
11
return ClientConfig(server_url="http://localhost:50051", api_key=None)

TLS follows the URL scheme. An https:// URL connects over TLS and verifies the engine against the system trust store, with no other setting. An http:// URL connects in plaintext, even with certificates set, so use https:// whenever the engine expects TLS. The tls_* paths add certificates: give a CA certificate to trust a private or self-signed authority, and a client certificate and key for mutual TLS:

1
return ClientConfig(
2
server_url="https://orcher.example.com:443",
3
tls_ca_cert_path="/etc/orcher/ca.pem", # omit to use the system trust store
4
tls_client_cert_path="/etc/orcher/client.pem", # client certificate, for mTLS
5
tls_client_key_path="/etc/orcher/client-key.pem",
6
)

The client certificate and key go together: ClientConfig raises ConfigurationError if only one is given. The worker takes the same settings.


Starting workflows

1
handle = await client.start_workflow(
2
"process-order", # the name given to @workflow
3
workflow_id="order-123", # default: a random UUID
4
task_queue="orders", # default: "default"
5
args=({"order_id": "ord_123", "amount": 9999},),
6
execution_timeout=timedelta(hours=1),
7
retry_policy=RetryPolicy(max_attempts=3),
8
)
OptionDefaultDescription
workflow_typerequiredThe name given to @workflow
workflow_ida random UUIDYour id for the run; see duplicate starts
task_queue"default"The queue whose workers run the workflow
args()The input; see below
retry_policynoneA RetryPolicy (or dict) for the workflow itself
execution_timeoutnoneBounds the whole workflow, retries included
run_timeout, task_timeoutnoneAccepted, but the current engine ignores them
cron_schedulenoneCreate a schedule instead of a run; not available on the current engine, see cron schedules
id_reuse_policyengine defaultWhat to do when workflow_id was used before

args follows the rules in Inputs and results: pass a one-element tuple holding a dict to call the workflow with keyword arguments, or holding a single value to pass one positional argument. Several values arrive as a single list.

Execution deadline

execution_timeout bounds the whole workflow. When it passes, the workflow is marked timed out and stops; without one, a workflow runs until it finishes, however long that takes. A deadline is a safety net for work that should never run unbounded, not a substitute for task timeouts: a bounded task tells you which step hung.

Cron schedules

A start with cron_schedule asks the engine to create a schedule instead of starting a run. The current engine image does not have schedules turned on, so it rejects such a start with "Schedule support not configured on this server instance". Until it does, start runs on a schedule from your own scheduler, or have a workflow loop on ctx.sleep() and restart with fresh history between rounds.

Duplicate starts

A workflow id names at most one open run. Starting a workflow whose id belongs to a run that's still open raises WorkflowError with the code ErrorCode.WORKFLOW_ALREADY_EXISTS, and its run_id names the run in the way. That makes the id an idempotency key for starts: a retried request starts nothing new, and can attach to the existing run instead:

1
try:
2
handle = await client.start_workflow(
3
"process-order",
4
workflow_id="order-123",
5
task_queue="orders",
6
args=({"order_id": "ord_123", "amount": 9999},),
7
id_reuse_policy=WorkflowIdReusePolicy.REJECT_DUPLICATE,
8
)
9
except WorkflowError as err:
10
if err.code != ErrorCode.WORKFLOW_ALREADY_EXISTS:
11
raise
12
# Started before: attach to the run that holds the id instead.
13
handle = await client.get_workflow("order-123", run_id=err.run_id)
14
result = await handle.result()

id_reuse_policy decides what happens once the previous run with that id has closed:

WorkflowIdReusePolicyA new run may start when
ALLOW_DUPLICATEThe previous run has closed, however it ended
ALLOW_DUPLICATE_FAILED_ONLYThe previous run failed, was canceled or terminated, or timed out
REJECT_DUPLICATENever: the id can be used once
TERMINATE_IF_RUNNINGAlways: an open run with the id is terminated first

Leave it unset and the engine allows a new run once the previous one has closed.


Workflow handles

start_workflow returns a WorkflowHandle; get_workflow(workflow_id, run_id=None) returns one for an existing workflow (its latest run unless you give a run_id):

1
handle = await client.get_workflow("order-123")
2
3
status = await handle.status() # a WorkflowStatus
4
if status == WorkflowStatus.RUNNING:
5
await handle.send_event("approval", {"approved": True})
6
progress = await handle.query("progress")
7
changed = await handle.update("set-priority", {"level": "high"})
8
print(progress, changed)
9
10
description = await handle.describe()
11
print(description.workflow_type, description.status, description.journal_length)
12
13
result = await handle.result(timeout=60.0) # seconds

query and update arguments follow the same rules as workflow input: a dict reaches the handler as keyword arguments, any other single value as one positional argument. See State, queries and updates.

To stop a workflow:

1
await handle.cancel() # ask the workflow to stop
2
await handle.terminate(reason="duplicate order") # stop it now

cancel() asks the workflow to stop; terminate() ends it at once, with no further workflow code running. reset() rewinds a run to an event in its journal; see Reset.


Listing and searching

list_workflows filters by type, task queue and status (RUNNING, COMPLETED, FAILED, CANCELLED, TERMINATED, TIMED_OUT, RESTARTED_FRESH), a page at a time:

1
page = await client.list_workflows(
2
page_size=100,
3
workflow_type="process-order",
4
status_filter=["RUNNING", "FAILED"],
5
)
6
while True:
7
for execution in page.executions:
8
print(execution.workflow_id, execution.status.value, execution.start_time)
9
if not page.has_more:
10
break
11
page = await client.list_workflows(
12
page_size=100,
13
workflow_type="process-order",
14
status_filter=["RUNNING", "FAILED"],
15
next_page_token=page.next_page_token,
16
)

search_workflows takes conditions of the form Key = 'value' joined with AND. WorkflowType, Status and WorkflowVersion filter on those fields; any other key matches a label:

1
page = await client.search_workflows(
2
"WorkflowType = 'process-order' AND Status = 'running'"
3
)
4
print(len(page.executions))

Errors

Handle methods raise WorkflowError when the workflow ended without a result and ClientError when the request itself failed. Both derive from OrcherError and carry a code (an ErrorCode) and a message:

1
try:
2
result = await handle.result(timeout=60.0)
3
except WorkflowError as err:
4
# The workflow failed, was canceled or terminated, or timed out.
5
print(f"{err.workflow_id} ended without a result: {err.message}")
6
except ClientError as err:
7
# The call itself failed: no connection, or `timeout` passed first.
8
print(f"request failed ({err.code.name}): {err.message}")
9
else:
10
print(result)

Reference

Client

MethodDescription
Client(config)Create a client; connect with async with or connect()
await client.start_workflow(workflow_type, **options)Start a workflow and return its handle
await client.get_workflow(workflow_id, run_id=None)A handle to an existing workflow
await client.list_workflows(**filters)A WorkflowListPage of executions
await client.search_workflows(query, page_size=100, next_page_token=None)Executions matching a query
await client.close()Close the connection

WorkflowHandle

Method or propertyDescription
handle.workflow_id, handle.run_idThe run's ids
await handle.result(timeout=None)Wait for the result; timeout in seconds
await handle.status()A WorkflowStatus
await handle.describe()A WorkflowExecutionDescription: type, queue, status, times, journal length, attempt
await handle.send_event(name, data=None)Send an event
await handle.query(name, *args)Run a query handler and return its result
await handle.update(name, *args)Run an update handler and return its result
await handle.cancel()Ask the workflow to stop
await handle.terminate(reason="")End the workflow now
await handle.reset(target_event_id, reason="")Rewind the run; returns the new execution's id

Next steps

  • Workflows: the code these calls drive
  • Worker: run the workflows you start
  • Patterns: approvals and other event-driven workflows