8000 Release 0.2.2: parallel task calls, named task limits, late lease renewal warning by arminhammer · Pull Request #43 · arminhammer/jackdaw · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,26 @@ The workspace publishes three crates with the same version: `jackdaw-wf` (the li

## [Unreleased]

## [0.2.2] - 2026-11-02

### Added

- Named limits on how many task calls run at once. `#[task(limit = "name")]` (async or blocking, free functions and
`#[tasks]` methods) names a limit, and `EngineBuilder::limit(name, permits)` defines it for every instance the
engine runs. `EngineBuilder::blocking_limit(permits)` limits the blocking tasks that name none. Calls wait for a
permit in order without holding a thread. A YAML workflow's `call:` of a Rust task waits for the task's limit too.
`build` fails when a task names a limit the engine does not define.
- With the `metrics` feature, the `jackdaw_task_limit_waiting` gauge counts the calls waiting for each limit.
- An engine with leases logs a warning when its lease renewal runs late because the async runtime's threads were
busy (for more than a quarter of the lease TTL). The warning points at code that blocks inside an async task, the
usual cause, before another engine takes the instances over.

### Changed

- Each call of an async task runs as a tokio task of its own. The calls a workflow makes at once
(`futures::try_join!`, `join_all`, `ctx.for_each(..).concurrency(n)`) used to share the workflow's tokio task, and
so one thread; they now run in parallel. Dropping a call's future still stops it.

## [0.2.1] - 2026-11-01

### Fixed
Expand Down Expand Up @@ -146,7 +166,8 @@ an optional part of the same engine. The CLI is now a separate crate built on th

The CLI release before the library refactor; see the GitHub release.

[Unreleased]: https://github.com/arminhammer/jackdaw/compare/v0.2.1...HEAD
[Unreleased]: https://github.com/arminhammer/jackdaw/compare/v0.2.2...HEAD
[0.2.2]: https://github.com/arminhammer/jackdaw/compare/v0.2.1...v0.2.2
[0.2.1]: https://github.com/arminhammer/jackdaw/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/arminhammer/jackdaw/compare/v0.1.1...v0.2.0
[0.1.1]: https://github.com/arminhammer/jackdaw/releases/tag/v0.1.1
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ members = [
# Shared by all crates. Publish them together: jackdaw's macros expand to paths in jackdaw, so the two are pinned to
# each other with `=` and must have the same version.
[workspace.package]
version = "0.2.1"
version = "0.2.2"
edition = "2024"
# The oldest toolchain that builds the workspace and its dependencies (sqlx 0.9 needs 1.94).
rust-version = "1.94"
Expand All @@ -18,8 +18,8 @@ license = "Apache-2.0"
repository = "https://github.com/arminhammer/jackdaw"

[workspace.dependencies]
jackdaw = { package = "jackdaw-wf", path = "jackdaw", version = "=0.2.1" }
jackdaw-macros = { package = "jackdaw-wf-macros", path = "jackdaw-macros", version = "=0.2.1" }
jackdaw = { package = "jackdaw-wf", path = "jackdaw", version = "=0.2.2" }
jackdaw-macros = { package = "jackdaw-wf-macros", path = "jackdaw-macros", version = "=0.2.2" }

[workspace.lints.clippy]
indexing_slicing = "deny"
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ All three are released together, at the same version.
whose message names the replacement.
- **One engine for Rust and YAML.** They share events and storage, and they call each other: Rust runs YAML
workflows, and YAML calls Rust tasks.
- **Operational features.** Retries, timeouts, heartbeats, caching, durable timers, cron schedules, leases for
several engines on one store, retention, `tracing` spans and `metrics`.
- **Operational features.** Retries, timeouts, heartbeats, caching, named concurrency limits, durable timers, cron
schedules, leases for several engines on one store, retention, `tracing` spans and `metrics`.
- **Pluggable storage.** Redb (embedded, the default), SQLite and Postgres, or your own store.
- **Serve APIs from workflows.** Listeners start a workflow for each request to an OpenAPI operation or a gRPC
method, with requests checked against the OpenAPI document.
Expand Down
2 changes: 1 addition & 1 deletion jackdaw-cli/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -144,5 +144,5 @@ LABEL org.opencontainers.image.description="A durable, cached, graph-based execu
LABEL org.opencontainers.image.authors="Armin Graf"
LABEL org.opencontainers.image.source="https://github.com/arminhammer/jackdaw"
LABEL org.opencontainers.image.licenses="Apache-2.0"
LABEL org.opencontainers.image.version="0.2.1"
LABEL org.opencontainers.image.version="0.2.2"
LABEL org.opencontainers.image.vendor="Jackdaw Project"
3 changes: 3 additions & 0 deletions jackdaw-macros/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub struct Args {
pub source: Option<LitStr>,
pub cached: bool,
pub blocking: bool,
pub limit: Option<LitStr>,
}

impl Args {
Expand All @@ -33,6 +34,8 @@ impl Args {
args.cached = true;
} else if meta.path.is_ident("blocking") {
args.blocking = true;
} else if meta.path.is_ident("limit") {
args.limit = Some(meta.value()?.parse()?);
} else {
return Err(meta.error("unsupported argument"));
}
Expand Down
21 changes: 18 additions & 3 deletions jackdaw-macros/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ fn task_name(args: &Args, ident: &Ident) -> LitStr {
.unwrap_or_else(|| LitStr::new(&ident.to_string(), ident.span()))
}

/// `native`, naming the limit its calls wait for when the attribute sets one.
fn with_limit(native: TokenStream, args: &Args) -> TokenStream {
match &args.limit {
Some(limit) => quote!(#native.limit(#limit)),
None => native,
}
}

pub fn expand_fn(attr: TokenStream, item: TokenStream) -> syn::Result<TokenStream> {
let args = Args::parse(attr)?;
let function: ItemFn = syn::parse2(item)?;
Expand Down Expand Up @@ -96,6 +104,7 @@ pub fn expand_fn(attr: TokenStream, item: TokenStream) -> syn::Result<TokenStrea
)
}
};
let native = with_limit(native, &args);
let doc = format!(
"Typed marker for the `{name}` task: pass it to `ctx.call(..)` or `Engine::task(..)`.",
name = name.value()
Expand Down Expand Up @@ -192,16 +201,22 @@ pub fn expand_impl(attr: TokenStream, item: TokenStream) -> syn::Result<TokenStr
} else {
quote!(_ctx)
};
registrations.push(quote! {
{
let this = ::std::sync::Arc::clone(&self);
let native = with_limit(
quote! {
::jackdaw::__private::NativeTask::new::<#input, #output, _, 10000 _>(
#name, #cached,
move |#ctx_param, input| {
let this = ::std::sync::Arc::clone(&this);
async move { #invoke }
},
)
},
&args,
);
registrations.push(quote! {
{
let this = ::std::sync::Arc::clone(&self);
#native
}
});
consts.push(quote! {
Expand Down
71 changes: 65 additions & 6 deletions jackdaw/src/api/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,10 @@ impl<T: TaskSet> IntoTaskSet for T {

/// Lets YAML workflows `call:` a native task by name.
#[cfg(feature = "yaml")]
struct NativeExecutor(NativeTask);
struct NativeExecutor {
task: NativeTask,
limits: Arc<super::limits::Limits>,
}

#[cfg(feature = "yaml")]
#[async_trait::async_trait]
Expand All @@ -121,17 +124,18 @@ impl Executor for NativeExecutor {
) -> crate::executor::Result<Value> {
let instance_id = ctx.metadata.instance_id.clone();
let key = format!("{instance_id}/{task_name}");
let context = TaskContext::new(&instance_id, self.0.name, 1, key);
self.0
.invoke(context, params.clone())
let context = TaskContext::new(&instance_id, self.task.name, 1, key);
let permit = self.limits.acquire(&self.task).await;
self.task
.invoke(context, params.clone(), permit)
.await
.map_err(|error| crate::executor::Error::Task {
message: error.as_fault().to_string(),
})
}

fn cacheable(&self) -> bool {
self.0.cached
self.task.cached
}
}

Expand Down Expand Up @@ -208,6 +212,8 @@ pub struct EngineBuilder {
poll: std::time::Duration,
#[cfg(any(feature = "http-listener", feature = "grpc-listener"))]
listeners: Vec<super::listener::Listener>,
limits: Vec<(String, usize)>,
blocking_limit: Option<usize>,
}

impl Default for EngineBuilder {
Expand Down Expand Up @@ -239,6 +245,8 @@ impl EngineBuilder {
poll: std::time::Duration::from_secs(1),
#[cfg(any(feature = "http-listener", feature = "grpc-listener"))]
listeners: Vec::new(),
< 10BC8 span class='blob-code-inner blob-code-marker ' data-code-marker="+"> limits: Vec::new(),
blocking_limit: None,
}
}

Expand Down Expand Up @@ -348,6 +356,46 @@ impl EngineBuilder {
self
}

/// Defines a named limit: at most `permits` calls of the tasks that name it run at once, across every instance
/// this engine runs.
///
/// A task names a limit with `#[task(limit = "name")]`, async or blocking, and any number of tasks can share one.
/// A call that finds no permit free waits for one without holding a thread, in the order the calls arrived. Use it
/// to keep CPU-heavy work to the machine's cores, or calls to a rate-limited service or a small connection pool
/// to what they allow. Defining a name again replaces it.
///
/// The wait is part of the step, so a step timeout counts it; a heartbeat timeout starts once the call has its
/// permit. Limits belong to one engine: engines sharing a store each have their own.
///
/// ```
/// use jackdaw::prelude::*;
///
/// #[task(blocking, limit = "cpu")]
/// fn resize(width: u32) -> Result<u32, TaskError> {
/// Ok(width / 2)
/// }
///
/// # fn main() -> Result<(), Error> {
/// let cores = std::thread::available_parallelism().map_or(4, |n| n.get());
/// let engine = Engine::builder().task(Resize).limit("cpu", cores).build()?;
/// # let _ = engine;
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn limit(mut self, name: impl Into<String>, permits: usize) -> Self {
self.limits.push((name.into(), permits));
self
}

/// Limits the calls of `#[task(blocking)]` tasks that name no limit of their own: at most `permits` run at once.
/// Without it they are not limited by the engine, only by tokio's blocking pool.
#[must_use]
pub fn blocking_limit(mut self, permits: usize) -> Self {
self.blocking_limit = Some(permits);
self
}

/// Registers a workflow (and, automatically, the child workflows it runs).
#[must_use]
pub fn workflow<W: WorkflowDef>(mut self) -> Self {
Expand Down Expand Up @@ -437,6 +485,13 @@ impl EngineBuilder {
}
#[cfg(not(feature = "yaml"))]
registry.validate()?;
let limits = Arc::new(super::limits::Limits::new(
self.limits,
self.blocking_limit,
)?);
for task in registry.tasks.values() {
limits.check(task)?;
}

let persistence = self.persistence.unwrap_or_else(|| {
Arc::new(InMemoryPersistence::new()) as Arc<dyn PersistenceProvider>
Expand Down Expand Up @@ -486,7 +541,10 @@ impl EngineBuilder {
.map(|(name, task)| {
(
(*name).to_string(),
Box::new(NativeExecutor(task.clone())) as Box<dyn Executor>,
Box::new(NativeExecutor {
task: task.clone(),
limits: Arc::clone(&limits),
}) as Box<dyn Executor>,
)
})
.collect();
Expand Down Expand Up @@ -520,6 +578,7 @@ impl EngineBuilder {
self.codec,
);
shared.retention = self.retention;
shared.limits = limits;
if let Some(ttl) = self.lease {
if !shared.persistence.supports_leases() {
return Err(Error::invalid(
Expand Down
85 changes: 85 additions & 0 deletions jackdaw/src/api/limits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//! Named limits on how many calls of a task run at once (see [`EngineBuilder::limit`](super::EngineBuilder::limit)).
//!
//! A limit is a semaphore. A call takes a permit before it starts and gives it back when it finishes, so a call that
//! waits holds no thread. The permit moves into the call itself: a blocking call cannot be stopped, so a cancelled
//! workflow keeps the permit taken until the call's thread is done.
use super::Error;
use super::task::NativeTask;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

/// The limits an engine was built with.
#[derive(Default)]
pub(crate) struct Limits {
named: HashMap<String, Arc<Semaphore>>,
/// Applies to blocking tasks that name no limit of their own.
blocking: Option<Arc<Semaphore>>,
}

/// The name the default limit for blocking tasks reports under.
const BLOCKING: &str = "blocking";

fn semaphore(name: &str, permits: usize) -> Result<Arc<Semaphore>, Error> {
if permits == 0 || permits > Semaphore::MAX_PERMITS {
return Err(Error::invalid(format!(
"the limit `{name}` needs between 1 and {} permits, not {permits}",
Semaphore::MAX_PERMITS
)));
}
Ok(Arc::new(Semaphore::new(permits)))
}

impl Limits {
pub(crate) fn new(named: Vec<(String, usize)>, blocking: Option<usize>) -> Result<Self, Error> {
let mut limits = Self {
named: HashMap::new(),
blocking: blocking
.map(|permits| semaphore(BLOCKING, permits))
.transpose()?,
};
for (name, permits) in named {
let semaphore = semaphore(&name, permits)?;
limits.named.insert(name, semaphore);
}
Ok(limits)
}

/// Fails when `task` names a limit the engine does not define.
pub(crate) fn check(&self, task: &NativeTask) -> Result<(), Error> {
match task.limit {
Some(name) if !self.named.contains_key(name) => Err(Error::invalid(format!(
"task `{}` uses the limit `{name}`, which the engine does not define; add `.limit(\"{name}\", n)` to the builder",
task.name
))),
Some(_) | None => Ok(()),
}
}

fn for_task(&self, task: &NativeTask) -> Option<(&str, &Arc<Semaphore>)> {
match task.limit {
Some(name) => self.named.get(name).map(|semaphore| (name, semaphore)),
None if task.blocking => self
.blocking
.as_ref()
.map(|semaphore| (BLOCKING, semaphore)),
None => None,
}
}

/// Waits for a permit to run `task`; `None` when no limit applies to it.
pub(crate) async fn acquire(&self, task: &NativeTask) -> Option<OwnedSemaphorePermit> {
let (name, semaphore) = self.for_task(task)?;
if let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() {
return Some(permit);
}
tracing::debug!(
task = task.name,
limit = name,
"the task waits for its limit"
);
let _waiting = super::observe::limit_waiting(name);
// The semaphore is never closed, so this only ends with a permit.
Arc::clone(semaphore).acquire_owned().await.ok()
}
}
1 change: 1 addition & 0 deletions jackdaw/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mod executor;
#[cfg(feature = "yaml")]
mod fence;
mod helpers;
mod limits;
#[cfg(any(feature = "http-listener", feature = "grpc-listener"))]
pub(crate) mod listener;
pub(crate) mod observe;
Expand Down
Loading
Loading
0