Skip to main content

ff_sdk/
lib.rs

1//! FlowFabric Worker SDK — public API for worker authors.
2//!
3//! This crate depends on `ff-script` for the Lua-function types, Lua error
4//! kinds (`ScriptError`), and retry helpers (`is_retryable_kind`,
5//! `kind_to_stable_str`). Consumers using `ff-sdk` do not need to import
6//! `ff-script` directly for normal worker operations, but can if they need
7//! the `ScriptError` or retry types.
8//!
9//! # Quick start
10//!
11//! The production claim path is
12//! [`FlowFabricWorker::claim_from_grant`]: obtain a
13//! [`ClaimGrant`] from `ff_scheduler::Scheduler::claim_for_worker`
14//! (the scheduler enforces budget, quota, and capability checks),
15//! then hand it to the SDK. `claim_next` is gated behind the
16//! default-off `direct-valkey-claim` feature and bypasses admission
17//! control — fine for benchmarks, not production.
18//!
19//! ```rust,ignore
20//! use ff_sdk::{FlowFabricWorker, WorkerConfig};
21//! use ff_core::backend::BackendConfig;
22//! use ff_core::types::{LaneId, Namespace, WorkerId, WorkerInstanceId};
23//!
24//! #[tokio::main]
25//! async fn main() -> Result<(), ff_sdk::SdkError> {
26//!     let config = WorkerConfig {
27//!         backend: BackendConfig::valkey("localhost", 6379),
28//!         worker_id: WorkerId::new("my-worker"),
29//!         worker_instance_id: WorkerInstanceId::new("my-worker-instance-1"),
30//!         namespace: Namespace::new("default"),
31//!         lanes: vec![LaneId::new("main")],
32//!         capabilities: Vec::new(),
33//!         lease_ttl_ms: 30_000,
34//!         claim_poll_interval_ms: 1_000,
35//!         max_concurrent_tasks: 1,
36//!     };
37//!
38//!     let worker = FlowFabricWorker::connect(config).await?;
39//!     let lane = LaneId::new("main");
40//!
41//!     // In a real deployment `grant` is obtained from the
42//!     // scheduler's `claim_for_worker` RPC/helper; it carries the
43//!     // execution id, capability match, and admission result.
44//!     # let grant: ff_core::contracts::ClaimGrant = unimplemented!();
45//!     let task = worker.claim_from_grant(lane, grant).await?;
46//!     println!("claimed: {}", task.execution_id());
47//!     // Process task...
48//!     task.complete(Some(b"done".to_vec())).await?;
49//!     Ok(())
50//! }
51//! ```
52//!
53//! # Migration: `direct-valkey-claim` → scheduler-issued grants
54//!
55//! The `direct-valkey-claim` cargo feature — which gates
56//! [`FlowFabricWorker::claim_next`] — is **deprecated** in favour of
57//! the pair of scheduler-issued grant entry points:
58//!
59//! * [`FlowFabricWorker::claim_from_grant`] — fresh claims. Use
60//!   `ff_scheduler::Scheduler::claim_for_worker` to obtain the
61//!   [`ClaimGrant`], then hand it to the SDK.
62//! * [`FlowFabricWorker::claim_from_reclaim_grant`] — resumed claims
63//!   for an `attempt_interrupted` execution. Wraps a
64//!   [`ReclaimGrant`].
65//!
66//! `claim_next` bypasses budget and quota admission control; the
67//! grant-based path does not. See each method's rustdoc for the
68//! exact migration recipe.
69//!
70//! [`ClaimGrant`]: ff_core::contracts::ClaimGrant
71//! [`ReclaimGrant`]: ff_core::contracts::ReclaimGrant
72
73#[cfg(feature = "valkey-default")]
74pub mod admin;
75pub mod config;
76pub mod engine_error;
77#[cfg(feature = "valkey-default")]
78pub mod snapshot;
79#[cfg(feature = "valkey-default")]
80pub mod task;
81#[cfg(feature = "valkey-default")]
82pub mod worker;
83
84// Re-exports for convenience
85#[cfg(feature = "valkey-default")]
86pub use admin::{
87    rotate_waitpoint_hmac_secret_all_partitions, FlowFabricAdminClient, PartitionRotationOutcome,
88    RotateWaitpointSecretRequest, RotateWaitpointSecretResponse,
89};
90pub use config::WorkerConfig;
91pub use engine_error::{
92    BugKind, ConflictKind, ContentionKind, EngineError, StateKind, ValidationKind,
93};
94// #88: backend-agnostic transport error surface. Consumers that
95// previously matched on `ferriskey::ErrorKind` via `valkey_kind()`
96// now match on `BackendErrorKind` via `backend_kind()`.
97pub use ff_core::engine_error::{BackendError, BackendErrorKind};
98// `FailOutcome` is ff-core-native (Stage 1a move); re-export
99// unconditionally so consumers can name `ff_sdk::FailOutcome` even
100// under `--no-default-features`.
101pub use ff_core::backend::FailOutcome;
102// `ResumeSignal` is also ff-core-native (Stage 0 move).
103pub use ff_core::backend::ResumeSignal;
104#[cfg(feature = "valkey-default")]
105pub use task::{
106    read_stream, tail_stream, AppendFrameOutcome, ClaimedTask, ConditionMatcher, Signal,
107    SignalOutcome, StreamCursor, StreamFrames, SuspendOutcome, TimeoutBehavior,
108    MAX_TAIL_BLOCK_MS, STREAM_READ_HARD_CAP,
109};
110#[cfg(feature = "valkey-default")]
111pub use worker::FlowFabricWorker;
112
113/// SDK error type.
114#[derive(Debug, thiserror::Error)]
115pub enum SdkError {
116    /// Backend transport error. Previously wrapped `ferriskey::Error`
117    /// directly (#88); now carries a backend-agnostic
118    /// [`BackendError`] so consumers match on
119    /// [`BackendErrorKind`] instead of ferriskey's native taxonomy.
120    /// The ferriskey → [`BackendError`] mapping lives in
121    /// `ff_backend_valkey::backend_error::backend_error_from_ferriskey`.
122    #[error("backend: {0}")]
123    Backend(#[from] BackendError),
124
125    /// Backend error with additional context (e.g. call-site label).
126    /// Previously `ValkeyContext { source: ferriskey::Error }` (#88).
127    #[error("backend: {context}: {source}")]
128    BackendContext {
129        #[source]
130        source: BackendError,
131        context: String,
132    },
133
134    /// FlowFabric engine error — typed sum over Lua error codes + transport
135    /// faults. See [`EngineError`] for the variant-granularity contract.
136    /// Replaces the previous `Script(ScriptError)` carrier (#58.6).
137    ///
138    /// `Box`ed to keep `SdkError`'s stack footprint small: the richest
139    /// variant (`ConflictKind::DependencyAlreadyExists { existing:
140    /// EdgeSnapshot }`) is ~200 bytes. Boxing keeps `Result<T, SdkError>`
141    /// at the same width every other variant pays.
142    #[error("engine: {0}")]
143    Engine(Box<EngineError>),
144
145    /// Configuration error. `context` identifies the call site / logical
146    /// operation (e.g. `"describe_execution: exec_core"`, `"admin_client"`).
147    /// `field` names the specific offending field when the error is
148    /// field-scoped (e.g. `Some("public_state")`), or `None` for
149    /// whole-object validation (e.g. `"at least one lane is required"`).
150    /// `message` carries dynamic detail: source-error rendering, the
151    /// offending raw value, etc.
152    #[error("{}", fmt_config(.context, .field.as_deref(), .message))]
153    Config {
154        context: String,
155        field: Option<String>,
156        message: String,
157    },
158
159    /// Worker is at its configured `max_concurrent_tasks` capacity —
160    /// the caller should retry later. Returned by
161    /// [`FlowFabricWorker::claim_from_grant`] and
162    /// [`FlowFabricWorker::claim_from_reclaim_grant`] when the
163    /// concurrency semaphore is saturated. Distinct from `Ok(None)`:
164    /// a `ClaimGrant`/`ReclaimGrant` represents real work already
165    /// selected by the scheduler, so silently dropping it would waste
166    /// the grant and let the grant TTL elapse. Surfacing the
167    /// saturation lets the caller release the grant (or wait +
168    /// retry).
169    ///
170    /// # Classification
171    ///
172    /// * [`SdkError::is_retryable`] returns `true` — saturation is
173    ///   transient: any in-flight task's
174    ///   complete/fail/cancel/drop releases a permit. Retry after
175    ///   milliseconds, not a retry loop with backoff for a backend
176    ///   transport failure.
177    /// * [`SdkError::backend_kind`] returns `None` — this is not a
178    ///   backend transport error, so there is no
179    ///   [`BackendErrorKind`] to inspect. Callers that fan out on
180    ///   `backend_kind()` should match `WorkerAtCapacity` explicitly
181    ///   (or use `is_retryable()`).
182    ///
183    /// [`FlowFabricWorker::claim_from_grant`]: crate::FlowFabricWorker::claim_from_grant
184    /// [`FlowFabricWorker::claim_from_reclaim_grant`]: crate::FlowFabricWorker::claim_from_reclaim_grant
185    #[error("worker at capacity: max_concurrent_tasks reached")]
186    WorkerAtCapacity,
187
188    /// HTTP transport error from the admin REST surface. Carries
189    /// the underlying `reqwest::Error` via `#[source]` so callers
190    /// can inspect `is_timeout()` / `is_connect()` / etc. for
191    /// finer-grained retry logic. Distinct from
192    /// [`SdkError::Backend`] — this fires on the HTTP/JSON surface,
193    /// not on the Lua/Valkey hot path.
194    #[error("http: {context}: {source}")]
195    Http {
196        #[source]
197        source: reqwest::Error,
198        context: String,
199    },
200
201    /// The admin REST endpoint returned a non-2xx response.
202    ///
203    /// Fields surface the server-side `ErrorBody` JSON shape
204    /// (`{ error, kind?, retryable? }`) as structured values so
205    /// cairn-fabric and other consumers can match without
206    /// re-parsing the body:
207    ///
208    /// * `status` — HTTP status code.
209    /// * `message` — the `error` string from the JSON body (or
210    ///   the raw body if it didn't parse as JSON).
211    /// * `kind` — server-supplied Valkey `ErrorKind` label for 5xxs
212    ///   backed by a transport error; `None` for 4xxs.
213    /// * `retryable` — server-supplied hint; `None` for 4xxs.
214    /// * `raw_body` — the full response body, preserved for logging
215    ///   when the JSON shape doesn't match.
216    #[error("admin api: {status}: {message}")]
217    AdminApi {
218        status: u16,
219        message: String,
220        kind: Option<String>,
221        retryable: Option<bool>,
222        raw_body: String,
223    },
224}
225
226/// Renders `SdkError::Config` as `config: <context>[.<field>]: <message>`.
227/// The `field` slot is omitted when `None` (whole-object validation).
228fn fmt_config(context: &str, field: Option<&str>, message: &str) -> String {
229    match field {
230        Some(f) => format!("config: {context}.{f}: {message}"),
231        None => format!("config: {context}: {message}"),
232    }
233}
234
235/// Lift a native `ferriskey::Error` into [`SdkError::Backend`] via
236/// [`ff_backend_valkey::backend_error_from_ferriskey`] (#88). Keeps
237/// `?`-propagation ergonomic at FCALL/transport call sites while
238/// the public variant stays backend-agnostic.
239#[cfg(feature = "valkey-default")]
240impl From<ferriskey::Error> for SdkError {
241    fn from(err: ferriskey::Error) -> Self {
242        Self::Backend(ff_backend_valkey::backend_error_from_ferriskey(&err))
243    }
244}
245
246/// Build an [`SdkError::BackendContext`] from a native
247/// `ferriskey::Error` and a call-site label, preserving the
248/// backend-agnostic shape on the public surface (#88).
249#[cfg(feature = "valkey-default")]
250pub(crate) fn backend_context(
251    err: ferriskey::Error,
252    context: impl Into<String>,
253) -> SdkError {
254    SdkError::BackendContext {
255        source: ff_backend_valkey::backend_error_from_ferriskey(&err),
256        context: context.into(),
257    }
258}
259
260/// Preserves the ergonomic `?`-propagation from FCALL sites that
261/// return `Result<_, ScriptError>`. Routes through `EngineError`'s
262/// typed classification so every call site gets the same
263/// variant-level detail without hand-written conversion.
264impl From<ff_script::error::ScriptError> for SdkError {
265    fn from(err: ff_script::error::ScriptError) -> Self {
266        // ff-script's `From<ScriptError> for EngineError` owns the
267        // mapping table (#58.6). See `ff_script::engine_error_ext`.
268        Self::Engine(Box::new(EngineError::from(err)))
269    }
270}
271
272impl From<EngineError> for SdkError {
273    fn from(err: EngineError) -> Self {
274        Self::Engine(Box::new(err))
275    }
276}
277
278impl SdkError {
279    /// Returns the classified [`BackendErrorKind`] if this error
280    /// carries a backend transport fault. Covers the direct
281    /// [`SdkError::Backend`] / [`SdkError::BackendContext`] variants
282    /// and `Engine(EngineError::Transport { .. })` via the
283    /// ScriptError-aware downcast in `ff_script::engine_error_ext`.
284    ///
285    /// Renamed from `valkey_kind` in #88 — the previous return type
286    /// `Option<ferriskey::ErrorKind>` leaked ferriskey into every
287    /// consumer doing retry classification.
288    pub fn backend_kind(&self) -> Option<BackendErrorKind> {
289        match self {
290            Self::Backend(be) => Some(be.kind()),
291            Self::BackendContext { source, .. } => Some(source.kind()),
292            #[cfg(feature = "valkey-default")]
293            Self::Engine(e) => ff_script::engine_error_ext::valkey_kind(e)
294                .map(ff_backend_valkey::classify_ferriskey_kind),
295            #[cfg(not(feature = "valkey-default"))]
296            Self::Engine(_) => None,
297            // HTTP/admin-surface errors carry no backend fault;
298            // the admin path never touches the backend directly from
299            // the SDK side. Use `AdminApi.kind` for the server-supplied
300            // label when present.
301            Self::Config { .. }
302            | Self::WorkerAtCapacity
303            | Self::Http { .. }
304            | Self::AdminApi { .. } => None,
305        }
306    }
307
308    /// Whether this error is safely retryable by a caller. For backend
309    /// transport variants, delegates to
310    /// [`BackendErrorKind::is_retryable`]. For `Engine` errors, returns
311    /// `true` iff the typed classification is
312    /// `ErrorClass::Retryable`. `Config` errors are never retryable.
313    pub fn is_retryable(&self) -> bool {
314        match self {
315            Self::Backend(be) | Self::BackendContext { source: be, .. } => {
316                be.kind().is_retryable()
317            }
318            Self::Engine(e) => {
319                matches!(
320                    ff_script::engine_error_ext::class(e),
321                    ff_core::error::ErrorClass::Retryable
322                )
323            }
324            // WorkerAtCapacity is retryable: the saturation is transient
325            // and clears as soon as a concurrent task completes.
326            Self::WorkerAtCapacity => true,
327            // HTTP transport: timeouts and connect failures are
328            // retryable (transient network state); body-decode or
329            // request-build errors are terminal (caller must fix
330            // the code). `reqwest::Error` exposes both predicates.
331            Self::Http { source, .. } => source.is_timeout() || source.is_connect(),
332            // Admin API errors: trust the server's `retryable` hint
333            // when present; otherwise fall back to the HTTP-standard
334            // retryable-status set (429, 502, 503, 504). 5xxs without
335            // a hint are conservatively non-retryable — the caller can
336            // override with `AdminApi.status`-based logic if needed.
337            // 502 covers reverse-proxy transients (ALB/nginx returning
338            // Bad Gateway when ff-server restarts mid-request).
339            Self::AdminApi {
340                status, retryable, ..
341            } => retryable.unwrap_or(matches!(*status, 429 | 502 | 503 | 504)),
342            Self::Config { .. } => false,
343        }
344    }
345}
346
347#[cfg(all(test, feature = "valkey-default"))]
348mod tests {
349    use super::*;
350    use ferriskey::ErrorKind;
351    use ff_script::error::ScriptError;
352
353    fn mk_fk_err(kind: ErrorKind) -> ferriskey::Error {
354        ferriskey::Error::from((kind, "synthetic"))
355    }
356
357    #[test]
358    fn backend_kind_direct_and_context() {
359        assert_eq!(
360            SdkError::from(mk_fk_err(ErrorKind::IoError)).backend_kind(),
361            Some(BackendErrorKind::Transport)
362        );
363        assert_eq!(
364            crate::backend_context(mk_fk_err(ErrorKind::BusyLoadingError), "connect")
365                .backend_kind(),
366            Some(BackendErrorKind::BusyLoading)
367        );
368    }
369
370    #[test]
371    fn backend_kind_delegates_through_engine_transport() {
372        let err = SdkError::from(ScriptError::Valkey(mk_fk_err(ErrorKind::ClusterDown)));
373        assert_eq!(err.backend_kind(), Some(BackendErrorKind::Cluster));
374    }
375
376    #[test]
377    fn backend_kind_none_for_lua_and_config() {
378        assert_eq!(
379            SdkError::from(ScriptError::LeaseExpired).backend_kind(),
380            None
381        );
382        assert_eq!(
383            SdkError::Config {
384                context: "worker_config".into(),
385                field: Some("bearer_token".into()),
386                message: "bad host".into(),
387            }
388            .backend_kind(),
389            None
390        );
391    }
392
393    #[test]
394    fn is_retryable_transport() {
395        // Transport-bucketed kinds (IoError, FatalSend/Receive,
396        // ProtocolDesync) are retryable under the #88 classifier.
397        assert!(SdkError::from(mk_fk_err(ErrorKind::IoError)).is_retryable());
398        // Auth-bucketed kinds are terminal.
399        assert!(!SdkError::from(mk_fk_err(ErrorKind::AuthenticationFailed)).is_retryable());
400        // Protocol-bucketed kinds (ResponseError, ParseError, TypeError,
401        // InvalidClientConfig, etc.) are terminal.
402        assert!(!SdkError::from(mk_fk_err(ErrorKind::ResponseError)).is_retryable());
403    }
404
405    #[test]
406    fn is_retryable_engine_delegates_to_class() {
407        // NoEligibleExecution is classified Retryable via EngineError::class().
408        assert!(SdkError::from(ScriptError::NoEligibleExecution).is_retryable());
409        // StaleLease is Terminal.
410        assert!(!SdkError::from(ScriptError::StaleLease).is_retryable());
411        // Transport(Valkey(IoError)) is Retryable via class() delegation.
412        assert!(
413            SdkError::from(ScriptError::Valkey(mk_fk_err(ErrorKind::IoError))).is_retryable()
414        );
415    }
416
417    /// Regression (#98): `SdkError::Config` carries `context`, optional
418    /// `field`, and `message` separately so consumers can pattern-match on
419    /// the offending field without parsing the Display string. Test covers
420    /// both the field-scoped and whole-object renderings.
421    #[test]
422    fn config_structured_fields_render_and_match() {
423        let with_field = SdkError::Config {
424            context: "admin_client".into(),
425            field: Some("bearer_token".into()),
426            message: "is empty or all-whitespace".into(),
427        };
428        assert_eq!(
429            with_field.to_string(),
430            "config: admin_client.bearer_token: is empty or all-whitespace"
431        );
432        assert!(matches!(
433            &with_field,
434            SdkError::Config { field: Some(f), .. } if f == "bearer_token"
435        ));
436
437        let whole_object = SdkError::Config {
438            context: "worker_config".into(),
439            field: None,
440            message: "at least one lane is required".into(),
441        };
442        assert_eq!(
443            whole_object.to_string(),
444            "config: worker_config: at least one lane is required"
445        );
446        assert!(matches!(
447            &whole_object,
448            SdkError::Config { field: None, .. }
449        ));
450    }
451
452    #[test]
453    fn is_retryable_config_false() {
454        assert!(
455            !SdkError::Config {
456                context: "worker_config".into(),
457                field: None,
458                message: "at least one lane is required".into(),
459            }
460            .is_retryable()
461        );
462    }
463
464    #[test]
465    fn is_retryable_admin_api_uses_server_hint_when_present() {
466        let err = SdkError::AdminApi {
467            status: 429,
468            message: "throttled".into(),
469            kind: None,
470            retryable: Some(false),
471            raw_body: String::new(),
472        };
473        assert!(!err.is_retryable());
474
475        let err = SdkError::AdminApi {
476            status: 500,
477            message: "valkey timeout".into(),
478            kind: Some("IoError".into()),
479            retryable: Some(true),
480            raw_body: String::new(),
481        };
482        assert!(err.is_retryable());
483    }
484
485    #[test]
486    fn is_retryable_admin_api_falls_back_to_standard_retryable_statuses() {
487        // 502 covers ALB/nginx Bad Gateway transients on ff-server
488        // restart — same retry-is-safe as 503/504 because rotation
489        // is idempotent server-side.
490        for s in [429u16, 502, 503, 504] {
491            let err = SdkError::AdminApi {
492                status: s,
493                message: "x".into(),
494                kind: None,
495                retryable: None,
496                raw_body: String::new(),
497            };
498            assert!(err.is_retryable(), "status {s} should be retryable");
499        }
500        for s in [400u16, 401, 403, 404, 500] {
501            let err = SdkError::AdminApi {
502                status: s,
503                message: "x".into(),
504                kind: None,
505                retryable: None,
506                raw_body: String::new(),
507            };
508            assert!(!err.is_retryable(), "status {s} should NOT be retryable without hint");
509        }
510    }
511
512    #[test]
513    fn valkey_kind_none_for_admin_surface() {
514        let err = SdkError::AdminApi {
515            status: 500,
516            message: "x".into(),
517            kind: Some("IoError".into()),
518            retryable: Some(true),
519            raw_body: String::new(),
520        };
521        assert_eq!(err.backend_kind(), None);
522    }
523}