Skip to main content

HttpClient

Struct HttpClient 

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

HTTP client bound to one engine.

Holds an optional RateBudget. When None, the client is unthrottled — appropriate for narrow test paths that want to exercise transport behavior without budget interference. In production the client is always built with a budget attached; the with_rate_budget builder method is the canonical on-ramp.

Implementations§

Source§

impl HttpClient

Source

pub fn new( base_url: impl AsRef<str>, token: Option<String>, ) -> Result<Self, HttpError>

Build a client for the given base URL. The URL must be parseable as an absolute URL (no trailing path needed; joined relative paths land under it). The returned client has no rate budget attached — callers who want one chain .with_rate_budget(...) (production path) or leave it off (narrow test paths that want raw transport behavior).

Source

pub fn with_mode(self, mode: Mode) -> Self

Attach a per-invocation engine-mode override. Every subsequent request carries X-Zero-Mode: <value>; the engine honors the header per M2_PLAN §5 / §7. Passing Mode::Live is explicit (None means “respect engine launch mode”), so an operator invoking zero --paper followed by a non-paper command inside the same TUI session gets paper → live flipped via the adapter, not via a header absence.

Source

pub fn with_operator_context(self, operator: OperatorRequestContext) -> Self

Attach operator audit context headers to every request.

Source

pub const fn mode(&self) -> Option<Mode>

Access the attached engine-mode override. The TUI status bar + the doctor row use this so the mode breadcrumb is rendered off the same source of truth the HTTP layer will act on.

Source

pub fn with_rate_budget(self, budget: RateBudget) -> Self

Attach a RateBudget. Every subsequent call consults the budget (via rate_budget::cost_of on the request path) before the request leaves the process. A None budget (the default after Self::new) disables the whole layer.

Source

pub const fn rate_budget(&self) -> Option<&RateBudget>

Access the attached RateBudget, if any. The doctor row and the status-bar widget use this to read a crate::BudgetSnapshot; holding the reference rather than cloning lets callers take a fresh snapshot on every render.

Source

pub fn base_url(&self) -> &Url

Source

pub fn has_token(&self) -> bool

Source

pub async fn get_json<T: DeserializeOwned>( &self, path: &str, ) -> Result<T, HttpError>

GET a path and decode the JSON body into T.

Order of operations:

  1. Consult the rate budget. Exhausted bucket → typed error, no network call. An operator hammering /status reads a typed refusal, not a silent stall.
  2. Send once. On retryable failure (502/503/504/ transport/timeout): sleep RETRY_DELAY, send again. One retry only.
  3. On 429 (engine’s limiter, not ours): refund the local bucket (we debited it in step 1) and return HttpError::RateBudgetExhausted shaped as Engine429 with the engine’s own Retry-After value parsed out.

Auth failures (401 / 403) and 404 are mapped to dedicated variants because the TUI renders them differently.

Source

pub async fn post_json<B, R>( &self, path: &str, body: &B, ) -> Result<R, HttpError>

POST a JSON body to a path and decode the JSON response into R.

Retry semantics mirror Self::get_json: one retry on 502/503/504/ transport/timeout with a 500 ms backoff. POSTs to /operator/events are idempotent at the bus-adapter layer (the event-log is append- only and the classifier replay is deterministic), so a retried duplicate is a no-op in the worst case — an extra benign duplicate in the event-log rather than a phantom trade. Any endpoint added later that is not idempotent must not route through this helper; the entire M2 spec’s POST surface today is idempotent.

Source

pub async fn post_json_no_retry<B, R>( &self, path: &str, body: &B, idempotency_key: Option<&str>, ) -> Result<R, HttpError>

POST a JSON body without any retry budget, optionally attaching an X-Idempotency-Key header.

Retry semantics (M2_PLAN §7):

POST endpoints never auto-retry (idempotency key compensates, but a silent retry of a live composition change is the single worst failure mode a trading CLI can have). Tests pin the no-retry rule against 5xx + timeout.

Used by Self::post_execute, Self::post_auto_toggle, and the /live/* control endpoints — every surface where a silent duplicate would change operator or exchange state. The contrast with Self::post_json (idempotent POST /operator/events, retry-once is safe) is deliberate: any future POST surface must pick its bucket explicitly.

idempotency_key, when Some, lands as an X-Idempotency-Key: <value> header in addition to whatever shape the body carries. Engine-side proxies that redact bodies but log headers still see the dedupe key; callers who want to skip the header entirely pass None.

Source

pub async fn root(&self) -> Result<Root, HttpError>

GET / — unauthenticated version probe.

Source

pub async fn health(&self) -> Result<Health, HttpError>

GET /health — unauthenticated component heartbeat rollup.

Source

pub async fn hyperliquid_status( &self, symbol: Option<&str>, ) -> Result<HyperliquidStatus, HttpError>

GET /hl/status[?symbol=...] — read-only Hyperliquid info adapter status.

Source

pub async fn hyperliquid_account(&self) -> Result<HyperliquidAccount, HttpError>

GET /hl/account — read-only Hyperliquid account truth.

Source

pub async fn hyperliquid_reconciliation( &self, ) -> Result<HyperliquidReconciliation, HttpError>

GET /hl/reconcile — local runtime versus Hyperliquid account state.

Source

pub async fn market_quote(&self, symbol: &str) -> Result<MarketQuote, HttpError>

GET /market/quote?symbol=... — active quote source feeding paper mode.

Source

pub async fn live_preflight(&self) -> Result<LivePreflight, HttpError>

GET /live/preflight — non-secret live readiness gate.

Source

pub async fn live_certification(&self) -> Result<LiveCertification, HttpError>

GET /live/certification — dry-run live certification drills.

Source

pub async fn live_cockpit(&self) -> Result<LiveCockpit, HttpError>

GET /live/cockpit — consolidated live-readiness operator packet.

Source

pub async fn live_evidence(&self) -> Result<LiveEvidence, HttpError>

GET /live/evidence — public-safe hash-only live evidence bundle.

Source

pub async fn live_canary_policy(&self) -> Result<LiveCanaryPolicy, HttpError>

GET /live/canary-policy — live canary readiness and proof policy.

Source

pub async fn runtime_parity(&self) -> Result<RuntimeParity, HttpError>

GET /runtime/parity — paper OODA plus disabled live-shadow parity report.

Source

pub async fn live_receipts(&self) -> Result<LiveExecutionReceipts, HttpError>

GET /live/receipts — public-safe local execution receipt bundle.

Source

pub async fn operator_context(&self) -> Result<OperatorContext, HttpError>

GET /operator/context — current operator audit identity.

Source

pub async fn immune(&self) -> Result<ImmuneReport, HttpError>

GET /immune — risk-blocking immune and circuit-breaker state.

Source

pub async fn post_live_heartbeat( &self, ) -> Result<LiveControlResponse, HttpError>

POST /live/heartbeat — refresh the exchange-side dead-man switch.

Source

pub async fn post_live_pause(&self) -> Result<LiveControlResponse, HttpError>

POST /live/pause — stop new risk-increasing live entries.

Source

pub async fn post_live_resume(&self) -> Result<LiveControlResponse, HttpError>

POST /live/resume — resume risk-increasing live entries.

Source

pub async fn post_live_kill(&self) -> Result<LiveControlResponse, HttpError>

POST /live/kill — activate kill switch and cancel open exchange orders.

Source

pub async fn post_live_flatten(&self) -> Result<LiveControlResponse, HttpError>

POST /live/flatten — submit reduce-only close orders for open positions.

Source

pub async fn v2_status(&self) -> Result<V2Status, HttpError>

GET /v2/status — condensed engine summary for the status bar.

Source

pub async fn positions(&self) -> Result<Positions, HttpError>

GET /positions — open positions for the authenticated operator.

Source

pub async fn risk(&self) -> Result<Risk, HttpError>

GET /risk — risk guardrail summary.

Source

pub async fn regime(&self, coin: Option<&str>) -> Result<Regime, HttpError>

GET /regime (whole-market) or /regime?coin={coin} (per-coin).

Source

pub async fn brief(&self) -> Result<Brief, HttpError>

GET /brief — morning / midday briefing.

Source

pub async fn evaluate(&self, coin: &str) -> Result<Evaluation, HttpError>

GET /evaluate/{coin} — per-coin gate verdict.

Source

pub async fn pulse(&self, limit: u32) -> Result<Pulse, HttpError>

GET /pulse?limit=... — live engine pulse feed.

Source

pub async fn approaching(&self) -> Result<ApproachingFeed, HttpError>

GET /approaching — coins approaching entry gates.

Source

pub async fn operator_state(&self) -> Result<OperatorSnapshot, HttpError>

GET /operator/state — operator behavioral state snapshot (ADR-016). The classifier runs on the engine host; this call is the CLI’s only window into it. Returned payload is a zero_operator_state::Snapshot.

Source

pub async fn post_operator_event( &self, event: &OperatorEvent, ) -> Result<OperatorEventsAccepted, HttpError>

POST /operator/events — append one operator-state event to the engine-side classifier log (ADR-016).

The wire format is the canonical zero_operator_state::Event tagged-union pinned by the cross-language golden-vector test (crates/zero-operator-state/tests/golden_vectors.rs). Sending via the typed Event rather than a hand-rolled JSON map is what keeps operators honest: a future schema change breaks the compile, not the runtime.

The engine response carries the post-ingest classifier snapshot so CLI callers can (a) confirm the event landed and (b) reflect any resulting label/friction change without a second round trip. Callers that only want a fire-and-forget tag can discard the returned OperatorEventsAccepted.

Retries are safe — see Self::post_json on idempotency.

Source

pub async fn post_execute( &self, coin: &str, side: ExecuteSide, size: f64, ) -> Result<ExecuteResponse, HttpError>

POST /execute — composition change (live-trade surface).

Mints a fresh v4 idempotency key per call, embeds it into the body, and mirrors it into an X-Idempotency-Key HTTP header. The server-side dedupe window suppresses a second /execute with the same key so a CLI retry after a spurious timeout does not double-compose.

Never retries. The caller sees the raw error. See Self::post_json_no_retry for the policy rationale; the short version is “silent retry of a live composition change is the single worst failure mode a trading CLI can have” (M2_PLAN §7).

Paper vs. live is controlled by the X-Zero-Mode header, which is attached automatically when the client was built with Self::with_mode. The response’s simulated flag is engine-asserted — the CLI suffixes the operator-visible line with (paper) when the engine says the fill was simulated, not when the CLI “thinks” it’s in paper mode.

Source

pub async fn post_auto_toggle( &self, enabled: bool, ) -> Result<AutoToggleResponse, HttpError>

POST /auto/toggle — flip the engine’s Auto-mode flag.

Never retries. Same rationale as Self::post_execute: the engine treats this as a composition-affecting call because it changes whether subsequent /plan outputs auto-accept. The response’s state is the engine’s post-call truth, not the requested state — friction may have refused the flip.

The body is the small AutoToggleRequest envelope; no idempotency key is emitted because the engine treats the endpoint as naturally idempotent (flipping on twice is a no-op). The no-retry rule still holds — a network failure mid-flight leaves the state ambiguous, and the correct response is an operator-visible alert, not a silent duplicate.

Source

pub async fn rejections( &self, limit: u32, coin: Option<&str>, ) -> Result<RejectionsFeed, HttpError>

GET /rejections?limit=...[&coin=...].

Trait Implementations§

Source§

impl Clone for HttpClient

Source§

fn clone(&self) -> HttpClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for HttpClient

Source§

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

Formats the value using the given formatter. 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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