Skip to main content

kruxiaflow_worker/
lib.rs

1//! Worker SDK for [Kruxia Flow](https://kruxiaflow.com) — run Rust
2//! activities in budgeted workflows with engine-enforced cost limits.
3//!
4//! A Kruxia Flow *worker* polls the server for queued activities, executes
5//! registered handlers, and reports results (including LLM usage, so
6//! external activities count against workflow budgets with full fidelity).
7//! This crate provides the complete worker loop: registration, polling,
8//! bounded concurrency, heartbeats, timeout and panic containment,
9//! completion/failure reporting, OAuth2 client-credentials auth, and
10//! graceful drain on shutdown.
11//!
12//! # Quickstart
13//!
14//! Run a server locally (no auth needed in dev mode):
15//!
16//! ```text
17//! kruxiaflow serve --insecure-dev
18//! ```
19//!
20//! Then a minimal worker:
21//!
22//! ```no_run
23//! use kruxiaflow_worker::{ActivityContext, ActivityResult, Worker};
24//! use serde_json::json;
25//!
26//! #[derive(serde::Deserialize)]
27//! struct EchoParams {
28//!     message: String,
29//! }
30//!
31//! #[tokio::main]
32//! async fn main() -> anyhow::Result<()> {
33//!     let worker = Worker::builder()
34//!         .worker("demo") // the workflow definition's `worker:` field
35//!         .register_fn("echo", |params: EchoParams, _ctx: ActivityContext| async move {
36//!             Ok(ActivityResult::value("echoed", json!(params.message)))
37//!         })
38//!         .build()?; // config from KRUXIAFLOW_* environment variables
39//!
40//!     worker.run_until_shutdown().await;
41//!     Ok(())
42//! }
43//! ```
44//!
45//! A workflow activity with `worker: demo` and `name: echo` now executes on
46//! this worker.
47//!
48//! # Reporting cost and usage
49//!
50//! Activities that call LLMs themselves report per-call usage so the engine
51//! records it exactly like built-in LLM activities — visible in cost
52//! history/analytics and counted against workflow budgets:
53//!
54//! ```no_run
55//! use kruxiaflow_worker::{ActivityResult, UsageEntry};
56//! use serde_json::json;
57//!
58//! # fn example() -> ActivityResult {
59//! ActivityResult::value("summary", json!("..."))
60//!     .push_usage(
61//!         UsageEntry::new("anthropic", "claude-sonnet-5")
62//!             .input_tokens(12034)
63//!             .output_tokens(512)
64//!             .cache_read_tokens(9800),
65//!     )
66//! # }
67//! ```
68//!
69//! The server prices entries from its model catalog unless an entry carries
70//! an explicit `cost_usd`. Failures spend money too: attach usage to
71//! [`ActivityError`] so failed attempts are budget-counted.
72//!
73//! # Failure semantics
74//!
75//! Handlers return `Result<ActivityResult, ActivityError>`. Construct errors
76//! with [`ActivityError::retryable`] (transient: the orchestrator re-queues
77//! up to the activity's retry limit) or [`ActivityError::terminal`] (bad
78//! input, business rejection: no retry). Panics and timeouts are caught and
79//! reported as retryable; parameter deserialization failures are terminal.
80//!
81//! # Shutdown
82//!
83//! [`Worker::run_until_shutdown`] listens for SIGINT/SIGTERM;
84//! [`Worker::handle`] gives a programmatic trigger. Shutdown stops polling
85//! and drains in-flight activities up to the configured `shutdown_timeout`,
86//! then fails the remainder as retryable so they re-queue — nothing is lost
87//! or double-completed.
88
89pub mod client;
90pub mod config;
91pub mod context;
92pub mod error;
93pub mod poller;
94pub mod registry;
95pub mod result;
96pub mod types;
97pub mod worker;
98
99pub use client::{ReportAck, WakeConnect, WakeStream, WorkerApiClient};
100pub use config::{WakeMode, WorkerConfig, WorkerConfigBuilder};
101pub use context::ActivityContext;
102pub use error::{ActivityError, ClientError, ConfigError};
103pub use poller::WorkerPoller;
104pub use registry::{ActivityExecutor, ActivityImpl, ActivityRegistry, TypedActivity};
105pub use result::ActivityResult;
106pub use types::{
107    ActivityOutput, OutputType, PendingActivity, PollActivitiesResponse, PollOutcome, UsageEntry,
108};
109pub use worker::{Worker, WorkerBuilder, WorkerHandle};
110
111// Implementing [`ActivityImpl`]/[`TypedActivity`] requires the same
112// `async_trait` attribute the traits are declared with; re-exported so
113// consumers don't need the direct dependency.
114pub use async_trait::async_trait;