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