Skip to main content

AkribesClient

Struct AkribesClient 

Source
pub struct AkribesClient { /* private fields */ }
Expand description

Typed client for the Akribes workflow platform.

Cheaply cloneable — all clones share the same HTTP client, auth token, and heartbeat task.

§Authentication

akribes-server uses two token types. Pick one for the token field:

1. Service token (long-lived, env var, full-Admin within scope) — for trusted backends. The secret is the part after : in AKRIBES_SERVICE_TOKEN_<NAME>=<scope>:<secret> from the server’s env.

use akribes_sdk::AkribesClient;
let client = AkribesClient::builder("https://akribes.example.com")
    .project_id(2)
    .token(std::env::var("AKRIBES_SERVICE_TOKEN").unwrap())
    .build();

2. Scoped token (akribes_tk_... — legacy aura_tk_... still accepted — expires, revokable) — for browsers, CLIs, or anything you don’t want to give a long-lived secret. Mint one via AkribesClient::tokens’s mint:

// From a backend holding a service token, mint a scoped token for a user:
let minted = backend.tokens().mint(&MintTokenRequest {
    user_email: Some("alice@acme.com".to_string()),
    scopes: TokenScopes {
        projects: ProjectScope::Wildcard(WildcardMarker),
        role: TokenRole::Admin,
        scripts: None,
        executions: None,
        can_mint: false,
        features: vec![],
        org_id: None,
    },
    expires_in: 8 * 3600, // 8h browser session
    label: "web-session".to_string(),
}).await?;
// Ship `minted.token` to the browser.

Set X-Akribes-User for metrics attribution when a backend acts on behalf of a user (advisory header — does not grant permission) via AkribesClientBuilder::on_behalf_of at construction or AkribesClient::set_on_behalf_of at runtime. Servers also accept the legacy X-Aura-User form for backwards compat with pre-rebrand clients.

Implementations§

Source§

impl AkribesClient

Source

pub fn new(base_url: &str, project_id: i64, name: &str, id: &str) -> Self

👎Deprecated since 0.4.0:

use AkribesClient::builder(base_url) instead

Create a new project-scoped client.

Deprecated: prefer AkribesClient::builder, which is now the blessed constructor and supports a wider range of configurations (no project, custom http client, etc.).

Source

pub fn builder(base_url: impl Into<String>) -> AkribesClientBuilder

Create a builder for more control over client construction.

let client = AkribesClient::builder("http://localhost:3001")
    .project_id(1)
    .name("my-service")
    .token("aura_abc123")
    .build();
Source

pub async fn set_token(&self, token: Option<String>)

Update the authentication token at runtime.

Pass None to clear the token (requests will be unauthenticated).

Source

pub async fn set_on_behalf_of(&self, email: Option<String>)

Set or clear the X-Akribes-User header sent on every outbound request, used by the server for metrics attribution when a backend (typically holding a service token) acts on behalf of an end user.

This header is advisory — it does not grant any permission. Authorization remains based on the bearer token’s scope. Servers also honor the legacy X-Aura-User form for backwards compat with pre-rebrand clients, but new code should not rely on that.

Mirrors AkribesClientBuilder::on_behalf_of for runtime updates (e.g. when the same long-lived client services many users).

Source

pub fn project_id(&self) -> Option<i64>

Return the configured project ID, or None if this is a global client.

Source

pub fn base_url(&self) -> &str

Return the base URL this client points at (no trailing slash). Useful for callers that need to compose a URL outside the typed sub-clients — e.g. the MCP bench tools poll an SSE endpoint as a plain GET to keep their wire-shape contract intact.

Source

pub async fn get_json_value(&self, url: &str) -> Result<Value>

Authenticated raw GET that returns the response body as a generic serde_json::Value. Goes through the same auth + telemetry pipeline as every typed call; only the deserialisation step is generic.

404 surfaces as AkribesError::HttpStatus (the typed callers convert it to Ok(None) via their own wrappers — for the raw form we keep the status visible so callers can branch on absence vs. unrelated failures).

Source

pub async fn get_json_value_opt(&self, url: &str) -> Result<Option<Value>>

404-tolerant variant of AkribesClient::get_json_value. Returns Ok(None) instead of surfacing the 404 as an error — useful when the caller’s notion of “absence” is a legitimate response.

Source

pub async fn post_json_value(&self, url: &str, body: &Value) -> Result<Value>

Authenticated raw POST with a JSON body, returning the response body as a generic serde_json::Value. Companion to AkribesClient::get_json_value for endpoints whose response shape isn’t (yet) typed in crate::models.

Source

pub fn ingest_poll_timeout(&self) -> Duration

Return the configured documents().ingest() poll timeout. Useful for inspecting the resolved value (builder override → env var → default) from tests or diagnostics.

Source§

impl AkribesClient

Source

pub fn projects(&self) -> ProjectsClient

Project management (list, create, update, delete). Global resource.

Source

pub fn executions(&self) -> ExecutionsClient

Script execution. Global methods only (get, get_output, get_events, cancel, resume, document helpers, await_execution).

For project-scoped methods (run, list, cancel_run, run_from, run_with_upload, run_with_s3, get_graph, get_cost), use AkribesClient::project first.

Source

pub fn tokens(&self) -> TokensClient

Scoped token management (mint, list, revoke). Not project-scoped.

Source

pub fn convert(&self) -> ConvertClient

Document conversion via the server’s Docling integration.

Source

pub fn bench_runs(&self) -> BenchRunsClient

Global bench-run operations (anything keyed on the cross-project bench_runs.id): get/delete a run, list results, page events, cancel, tag-session, compare two runs, promote an execution to a case. These endpoints live at /bench-runs/{id}/... and don’t need a project scope — the server resolves the owning project from the run row.

Project-scoped bench operations (config CRUD, case CRUD, list/trigger runs for a script) live on [ProjectScope::bench] instead.

Source

pub fn project(&self, project_id: i64) -> ProjectScope

Enter a project scope. The returned [ProjectScope] gives infallible access to all project-scoped sub-clients (scripts, drafts, versions, channels, bench, events, registered_clients).

let scripts = client.project(1).scripts().list().await?;
Source

pub fn scoped(&self) -> Result<ProjectScope>

Shortcut for clients constructed with AkribesClientBuilder::project_id: returns a [ProjectScope] using the embedded project id, or Err(MissingProjectId) if none was set.

Source

pub async fn get_state(&self) -> Result<Value>

Fetch the global server state (provider env, etc.). Does not require project_id.

Source

pub async fn get_sandbox_project_id(&self) -> Result<i64>

Fetch the caller’s per-user sandbox project id (creates one if missing). Use this to subscribe to ad-hoc events before calling run_adhoc so the first engine events aren’t missed.

Source

pub async fn run_adhoc( &self, source: &str, inputs: Option<HashMap<String, Value>>, breakpoint_lines: Option<Vec<usize>>, ) -> Result<AdhocRunResult>

Execute raw .akr source ad-hoc. The server runs it in the caller’s per-user sandbox project and returns {execution_id, project_id}.

Equivalent to run_adhoc_with with channel and triggered_by both None.

Source

pub async fn run_adhoc_with( &self, source: &str, inputs: Option<HashMap<String, Value>>, breakpoint_lines: Option<Vec<usize>>, channel: Option<&str>, triggered_by: Option<&str>, ) -> Result<AdhocRunResult>

Execute raw .akr source ad-hoc, with optional channel and triggered_by (#1120). Mirrors Python’s run_adhoc(channel=..., triggered_by=...) and the TS runAdHoc opts.

  • channel: release channel for resolving use foo references. When None, the server applies its default (typically production).
  • triggered_by: opaque identifier recorded with the execution for audit. Common values: "studio", "bench", "<user_email>".
Source

pub async fn adhoc_event_stream( &self, project_id: i64, ) -> Result<(UnboundedReceiver<EngineEvent>, EventSubscription)>

Subscribe to engine events from ad-hoc executions in the given sandbox project. Pass the project_id returned from run_adhoc or get_sandbox_project_id.

Returns a receiver for [EngineEvent]s (filtered to Execution variants) plus a subscription handle — dropping the handle cancels the stream.

Equivalent to adhoc_event_stream_with_ready with ready = None. Use the _with_ready variant when you need to avoid the subscribe-after-POST race on a fast workflow.

Source

pub async fn adhoc_event_stream_with_ready( &self, project_id: i64, ready: Option<Arc<Notify>>, ) -> Result<(UnboundedReceiver<EngineEvent>, EventSubscription)>

Like adhoc_event_stream, but takes an optional tokio::sync::Notify that fires once the SSE GET /events response returns a 2xx status — i.e. the moment the server-side broadcast subscriber is attached and no events emitted from this point on can be missed.

Use this to avoid the subscribe-after-POST race: a fast workflow (single-digit milliseconds, mock providers) can emit NodeStart, TaskStart, … before a naive run_adhoc().then(adhoc_event_stream) has its SSE subscriber registered, and those opening events are then dropped by the broadcast channel.

The pattern is subscribe → await ready → POST:

let project_id = client.get_sandbox_project_id().await?;
let ready = Arc::new(Notify::new());
let (mut rx, _sub) = client
    .adhoc_event_stream_with_ready(project_id, Some(Arc::clone(&ready)))
    .await?;
ready.notified().await;            // SSE attached, safe to POST
client.run_adhoc(source, None, None).await?;
while let Some(_event) = rx.recv().await { /* … */ }

If the SSE subscription fails (auth error, server down, all retries exhausted) the notify is never fired — wrap the wait in a timeout or join it with the subscription handle to avoid blocking forever.

Trait Implementations§

Source§

impl Clone for AkribesClient

Source§

fn clone(&self) -> AkribesClient

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AkribesClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for AkribesClient

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more