hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! Raising a tenant's rate-limit allowances.

use hatchet_proto::root::{PutRateLimitRequest, RateLimitDuration as WireDuration};

use crate::declare::{RateLimitDuration, saturating_i32};
use crate::error::{Error, Result};
use crate::{Client, retry};

/// Creates and raises the tenant's rate limits.
///
/// Get one from [`Client::rate_limits`]. A *static*
/// [`RateLimit`](crate::RateLimit) on a task spends an allowance that has to
/// exist first, and this is what creates it — the official Python SDK's
/// `rate_limits().put(..)` over the same v0 `WorkflowService/PutRateLimit`
/// call (`sdks/python/hatchet_sdk/features/rate_limits.py:31-65`). A
/// *dynamic* rate limit carries its own allowance in
/// [`limit_expr`](crate::RateLimit::limit_expr) and needs nothing here.
///
/// **Order matters.** A task that declares a static
/// [`RateLimit`](crate::RateLimit) whose key
/// was never [`put`](RateLimitsClient::put) fails registration with a bare
/// `Internal` error and no further detail — observed against both
/// supported engine versions. Put the key before registering the worker
/// that uses it:
///
/// ```no_run
/// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
/// use hatchet_client::{RateLimit, RateLimitDuration, TaskBuilder};
///
/// // 1. Create (or raise) the allowance first.
/// client
///     .rate_limits()
///     .put("github-api", 5_000, RateLimitDuration::Hour)
///     .await?;
///
/// // 2. Only now register a task that spends it.
/// let call_api = TaskBuilder::<(), ()>::new("call-api")
///     .rate_limit(RateLimit::new("github-api", 1))
///     .handler(|_ctx, _input| async { Ok(()) });
/// client.worker("api-worker").register(&call_api).build().await?;
/// # Ok(())
/// # }
/// ```
///
/// Keys are **tenant-global and not namespaced**: the client's namespace
/// configured with [`ClientBuilder::namespace`](crate::ClientBuilder::namespace)
/// is not applied here, matching the official Python SDK. Two environments
/// sharing a tenant share these keys.
#[derive(Clone, Debug)]
pub struct RateLimitsClient {
    client: Client,
}

impl RateLimitsClient {
    pub(crate) fn new(client: Client) -> Self {
        Self { client }
    }

    /// Sets the allowance for `key` to `limit` per `duration`, creating it
    /// if it is new and replacing whatever it was before.
    ///
    /// `key` is not namespaced; see the [`RateLimitsClient`] docs.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidArgument`](crate::Error::InvalidArgument) when `key`
    /// is empty or all whitespace — checked before any call is made, rather
    /// than left to the engine's own `InvalidArgument`. Otherwise
    /// [`Error::Grpc`](crate::Error::Grpc) when the call fails.
    pub async fn put(
        &self,
        key: impl AsRef<str>,
        limit: u32,
        duration: RateLimitDuration,
    ) -> Result<()> {
        let key = key.as_ref();
        if key.trim().is_empty() {
            return Err(Error::InvalidArgument(
                "a rate limit key must not be empty".to_string(),
            ));
        }
        let request = PutRateLimitRequest {
            key: key.to_string(),
            limit: saturating_i32(limit),
            duration: wire_duration(duration) as i32,
        };
        retry::unary(|| {
            let mut workflows = self.client.workflows_grpc();
            let request = retry::timed(request.clone());
            async move { workflows.put_rate_limit(request).await }
        })
        .await?;
        Ok(())
    }
}

/// The v0 `WorkflowService` has its own `RateLimitDuration` enum, distinct
/// from the v1 one a declaration uses, with the same values in the same
/// order.
fn wire_duration(duration: RateLimitDuration) -> WireDuration {
    match duration {
        RateLimitDuration::Second => WireDuration::Second,
        RateLimitDuration::Minute => WireDuration::Minute,
        RateLimitDuration::Hour => WireDuration::Hour,
        RateLimitDuration::Day => WireDuration::Day,
        RateLimitDuration::Week => WireDuration::Week,
        RateLimitDuration::Month => WireDuration::Month,
        RateLimitDuration::Year => WireDuration::Year,
    }
}