Skip to main content

schedr_client/
lib.rs

1//! A client of the webserver's REST API (`/api/v1`), for the user CLI and the web UI.
2//!
3//! Requests go through a [`Transport`]: HTTP in the real CLI ([`HttpTransport`]), something in
4//! process in tests. Every request carries `Schedr-Client-Version`. Actions return a command;
5//! [`Client::wait`] reads it back until the master has decided it (see archive/PROJECT.md, Web UI
6//! and CLI: the CLI waits for the decision).
7
8use std::fmt::Write as _;
9use std::time::Duration;
10
11use jiff::Timestamp;
12use schedr_api::views::{
13    AllRunsQuery, AttemptList, AttemptMemoryList, BackfillList, BackfillRequest, BackfillView,
14    CheckConnectionsRequest, CommandList, CommandView, ConnectionList, DagList, DagMemoryList,
15    DagView, DeploymentView, EventList, ImportErrorList, LogChunk, MemoryTotals, NamedEventList,
16    NamedEventView, OutputView, PauseRequest, PostEventRequest, ResourceList, RunDetail, RunList,
17    SampleSeriesList, SensorList, TaskFlowList, TestConnectionRequest, TriggerList, TriggerRequest,
18    TriggerView, WorkerList,
19};
20use schedr_model::commands::ConnectionsResult;
21use serde::de::DeserializeOwned;
22
23/// This client's version (the workspace's), sent in [`CLIENT_VERSION_HEADER`].
24pub const VERSION: &str = env!("CARGO_PKG_VERSION");
25
26pub mod stream;
27pub mod times;
28
29pub use stream::{Chunks, EventReader, ServerEvent};
30
31#[cfg(test)]
32mod tests;
33
34/// The header carrying this client's version.
35pub const CLIENT_VERSION_HEADER: &str = "schedr-client-version";
36
37/// How often [`Client::wait`] reads a command back.
38pub const POLL_INTERVAL: Duration = Duration::from_millis(500);
39
40/// How long [`Client::wait`] waits for the master's decision.
41pub const WAIT_TIMEOUT: Duration = Duration::from_secs(30);
42
43/// How long connecting to the server may take.
44///
45/// A handshake that never completes (a black-holed address) stops here.
46pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
47
48/// How long one request may take, from the start of the connection until the body ends.
49pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
50
51/// An HTTP method the client uses.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Method {
54    /// `GET`.
55    Get,
56    /// `POST`.
57    Post,
58}
59
60/// A request to the API.
61#[derive(Debug, Clone, PartialEq)]
62pub struct ApiRequest {
63    /// The method.
64    pub method: Method,
65    /// The path and query, e.g. `/api/v1/dags/sync/runs?for=...`.
66    pub path: String,
67    /// The JSON body, if any.
68    pub body: Option<serde_json::Value>,
69    /// A command's `Idempotency-Key` (see [`COMMAND_KEY`]).
70    pub key: Option<String>,
71}
72
73/// The API's answer.
74#[derive(Debug, Clone, PartialEq)]
75pub struct ApiResponse {
76    /// The HTTP status.
77    pub status: u16,
78    /// The JSON body (`null` when empty or not JSON).
79    pub body: serde_json::Value,
80}
81
82/// Why a request failed.
83#[derive(Debug, thiserror::Error)]
84pub enum ClientError {
85    /// The server can't be reached.
86    #[error("can't reach the schedr server at {server}: {reason}")]
87    Connect {
88        /// The server's URL.
89        server: String,
90        /// Why.
91        reason: String,
92    },
93    /// No connection could be made: nothing was sent (B215).
94    #[error("can't reach the schedr server at {server}: {reason}")]
95    Unreachable {
96        /// The server's URL.
97        server: String,
98        /// Why.
99        reason: String,
100    },
101    /// The server answered with an error.
102    #[error("{message}")]
103    Server {
104        /// The HTTP status.
105        status: u16,
106        /// The server's message.
107        message: String,
108    },
109    /// The answer isn't what the API describes.
110    #[error("unexpected answer from the server: {0}")]
111    Unexpected(String),
112    /// The master rejected the command.
113    #[error("rejected: {0}")]
114    Rejected(String),
115    /// A command was sent [`COMMAND_TRIES`] times and no answer came (or the server failed):
116    /// it may have been stored, so it is not "not sent" (B140).
117    #[error(
118        "no answer from the schedr server ({reason}): the command may have arrived. Look \
119         before sending it again (`schedr runs list`, `schedr dags list`, `schedr workers \
120         list`): sent again, it is a new command"
121    )]
122    Unanswered {
123        /// The last try's error.
124        reason: String,
125    },
126    /// The master didn't decide in time.
127    #[error(
128        "the master hasn't applied the command yet (command {command_id}); is the master \
129         running? `schedr` will apply it when it is"
130    )]
131    Timeout {
132        /// The command.
133        command_id: String,
134    },
135}
136
137/// Sends requests to the API.
138pub trait Transport: Sync {
139    /// Sends one request.
140    fn send(
141        &self,
142        request: ApiRequest,
143    ) -> impl Future<Output = Result<ApiResponse, ClientError>> + Send;
144
145    /// Opens `GET <path>` and reads its body as it comes (server-sent events); a transport
146    /// that can't stream says so.
147    fn open(&self, path: String) -> impl Future<Output = Result<Chunks, ClientError>> + Send {
148        let _ = path;
149        std::future::ready(Err(ClientError::Unexpected(
150            "this transport can't stream".to_owned(),
151        )))
152    }
153}
154
155tokio::task_local! {
156    /// The person a request is made for (the web UI sets it for each page it serves): sent
157    /// as `X-Schedr-User`, which a webserver takes only from a caller proven to be the UI
158    /// (see `schedr_api::auth`).
159    pub static USER: String;
160}
161
162/// `work` made for the same person as the current request: [`USER`] doesn't follow a spawned
163/// task by itself, so a page asking several deployments at once carries it over.
164pub fn for_same_user<F: Future>(work: F) -> impl Future<Output = F::Output> {
165    let user = current_user();
166    async move {
167        match user {
168            Some(user) => USER.scope(user, work).await,
169            None => work.await,
170        }
171    }
172}
173
174tokio::task_local! {
175    /// The key of the command sent in this scope (B140): sent as `Idempotency-Key` with each
176    /// `POST`, so a command sent again with it after its answer was lost (the webserver may
177    /// have stored it) is the one stored then, not a second.
178    pub static COMMAND_KEY: String;
179}
180
181/// `send` made with `key` as its command's `Idempotency-Key` ([`COMMAND_KEY`]).
182pub async fn with_command_key<F: Future>(key: String, send: F) -> F::Output {
183    COMMAND_KEY.scope(key, send).await
184}
185
186/// How many times [`Client::submit`] sends a command whose answer doesn't come.
187pub const COMMAND_TRIES: u32 = 3;
188
189/// A new command key: unique, for one command (see [`Client::submit`]).
190#[must_use]
191pub fn new_command_key() -> String {
192    uuid::Uuid::now_v7().to_string()
193}
194
195/// The person the current request is made for, if [`USER`] is set.
196#[must_use]
197pub fn current_user() -> Option<String> {
198    USER.try_with(Clone::clone).ok()
199}
200
201/// How long a stream may stay open before the client gives up on it (and opens another).
202pub const STREAM_TIMEOUT: Duration = Duration::from_hours(24);
203
204/// Credentials the CLI sends (never validated here).
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub enum Auth {
207    /// None (`auth.mode = "none"`, from inside the namespace).
208    None,
209    /// A bearer token (`--token` / `SCHEDR_TOKEN`).
210    Bearer(String),
211    /// HTTP Basic (`--user` / `SCHEDR_USER`, password from `SCHEDR_PASSWORD`).
212    Basic {
213        /// The user name.
214        user: String,
215        /// The password.
216        password: Option<String>,
217    },
218}
219
220impl Auth {
221    /// Bearer when `token` is set (it wins over a user name), else HTTP Basic, else none.
222    #[must_use]
223    pub fn from_cli(token: Option<&str>, user: Option<&str>, password: Option<&str>) -> Self {
224        match (token, user) {
225            (Some(token), _) => Self::Bearer(token.to_owned()),
226            (None, Some(user)) => Self::Basic {
227                user: user.to_owned(),
228                password: password.map(str::to_owned),
229            },
230            (None, None) => Self::None,
231        }
232    }
233}
234
235/// An mTLS client and the material generation it was built from.
236type CachedClient = std::sync::Arc<std::sync::Mutex<(u64, reqwest::Client)>>;
237
238/// The API over HTTP.
239#[derive(Debug, Clone)]
240pub struct HttpTransport {
241    client: reqwest::Client,
242    server: String,
243    auth: Auth,
244    /// The token presented to prove the calls are the web UI's (`X-Schedr-Ui-Token`).
245    ui_token: Option<schedr_api::auth::UiToken>,
246    /// mTLS with this role's certificate (a webserver's UI port), and the client built from
247    /// it, by the material's generation (rebuilt when the files change).
248    tls: Option<(schedr_tls::Tls, CachedClient)>,
249    /// How long connecting and a request may take.
250    timeouts: Timeouts,
251}
252
253/// How long the CLI and `schedr ui` wait for a webserver, each a `SCHEDR_HIDDEN__CLIENT__*`
254/// timing (decision 493).
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub struct Timeouts {
257    /// Connecting (`CONNECT_TIMEOUT`).
258    pub connect: Duration,
259    /// One request (`REQUEST_TIMEOUT`).
260    pub request: Duration,
261    /// The master's decision on a command (`COMMAND_WAIT`).
262    pub command_wait: Duration,
263}
264
265impl Default for Timeouts {
266    /// [`CONNECT_TIMEOUT`], [`REQUEST_TIMEOUT`] and [`WAIT_TIMEOUT`].
267    fn default() -> Self {
268        Self {
269            connect: CONNECT_TIMEOUT,
270            request: REQUEST_TIMEOUT,
271            command_wait: WAIT_TIMEOUT,
272        }
273    }
274}
275
276/// A plain HTTP client with `timeouts`.
277fn plain_client(timeouts: Timeouts) -> reqwest::Client {
278    reqwest::Client::builder()
279        .connect_timeout(timeouts.connect)
280        .timeout(timeouts.request)
281        .redirect(reqwest::redirect::Policy::none())
282        .build()
283        .expect("the HTTP client builds with connect and request timeouts")
284}
285
286impl HttpTransport {
287    /// A transport to `server` (e.g. `http://localhost:8080`) sending `auth`.
288    ///
289    /// Connecting gives up after [`CONNECT_TIMEOUT`]; a request gives up after
290    /// [`REQUEST_TIMEOUT`], a stream ([`Transport::open`]) after [`STREAM_TIMEOUT`].
291    ///
292    /// # Panics
293    ///
294    /// If the HTTP client cannot be built. The builder here sets only the two timeouts, so
295    /// this does not happen in practice.
296    #[must_use]
297    pub fn new(server: &str, auth: Auth) -> Self {
298        let timeouts = Timeouts::default();
299        Self {
300            client: plain_client(timeouts),
301            timeouts,
302            server: server.trim_end_matches('/').to_owned(),
303            auth,
304            ui_token: None,
305            tls: None,
306        }
307    }
308
309    /// This transport waiting as `timeouts` say to connect and for a request (call it before
310    /// [`Self::with_tls`]).
311    #[must_use]
312    pub fn with_timeouts(self, timeouts: Timeouts) -> Self {
313        Self {
314            client: plain_client(timeouts),
315            timeouts,
316            ..self
317        }
318    }
319
320    /// This transport reaching its server over mTLS with `tls`'s certificate (`schedr ui` to
321    /// a webserver's UI port, decision 36); the server's certificate must name the URL's host.
322    ///
323    /// # Panics
324    ///
325    /// As [`Self::new`].
326    #[must_use]
327    pub fn with_tls(self, tls: schedr_tls::Tls) -> Self {
328        let client = mtls_client(&tls, self.timeouts);
329        let cached = std::sync::Arc::new(std::sync::Mutex::new((tls.generation(), client)));
330        Self {
331            tls: Some((tls, cached)),
332            ..self
333        }
334    }
335
336    /// The HTTP client to use now: the plain one, or the mTLS one of the material in use.
337    fn http(&self) -> reqwest::Client {
338        let Some((tls, cached)) = &self.tls else {
339            return self.client.clone();
340        };
341        let generation = tls.generation();
342        let mut cached = cached
343            .lock()
344            .unwrap_or_else(std::sync::PoisonError::into_inner);
345        if cached.0 != generation {
346            *cached = (generation, mtls_client(tls, self.timeouts));
347        }
348        cached.1.clone()
349    }
350
351    /// This transport presenting `token` as the web UI's (where there is no mTLS: decision 36),
352    /// as it is at each request (a token file followed).
353    #[must_use]
354    pub fn with_ui_token(self, token: schedr_api::auth::UiToken) -> Self {
355        Self {
356            ui_token: Some(token),
357            ..self
358        }
359    }
360
361    /// The headers every request carries: the version, the credentials, the UI's token and
362    /// the person it is made for.
363    fn headers(&self, mut builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
364        builder = builder.header(CLIENT_VERSION_HEADER, VERSION);
365        builder = match &self.auth {
366            Auth::None => builder,
367            Auth::Bearer(token) => builder.bearer_auth(token),
368            Auth::Basic { user, password } => builder.basic_auth(user, password.as_ref()),
369        };
370        if let Some(token) = &self.ui_token {
371            builder = builder.header(
372                schedr_api::auth::UI_TOKEN_HEADER,
373                token.current().0.as_str(),
374            );
375        }
376        if let Some(user) = current_user() {
377            builder = builder.header(schedr_api::auth::USER_HEADER, user);
378        }
379        builder
380    }
381}
382
383impl HttpTransport {
384    /// The server's URL, without a trailing slash.
385    #[must_use]
386    pub fn server(&self) -> &str {
387        &self.server
388    }
389
390    /// The credentials it sends.
391    #[must_use]
392    pub const fn auth(&self) -> &Auth {
393        &self.auth
394    }
395}
396
397impl Transport for HttpTransport {
398    async fn send(&self, request: ApiRequest) -> Result<ApiResponse, ClientError> {
399        let url = format!("{}{}", self.server, request.path);
400        let client = self.http();
401        let mut builder = self.headers(match request.method {
402            Method::Get => client.get(&url),
403            Method::Post => client.post(&url),
404        });
405        if let Some(body) = &request.body {
406            builder = builder.json(body);
407        }
408        if let Some(key) = &request.key {
409            builder = builder.header("idempotency-key", key);
410        }
411        let response = builder.send().await.map_err(|e| {
412            // Refused before a connection was made: the request never left (B215).
413            if e.is_connect() {
414                let ClientError::Connect { server, reason } = connect_error(&self.server, e) else {
415                    unreachable!("connect_error makes a Connect")
416                };
417                ClientError::Unreachable { server, reason }
418            } else {
419                connect_error(&self.server, e)
420            }
421        })?;
422        refuse_redirect(&self.server, &response)?;
423        let status = response.status().as_u16();
424        let bytes = response
425            .bytes()
426            .await
427            .map_err(|e| connect_error(&self.server, e))?;
428        Ok(ApiResponse {
429            status,
430            body: serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null),
431        })
432    }
433
434    async fn open(&self, path: String) -> Result<Chunks, ClientError> {
435        let url = format!("{}{path}", self.server);
436        let builder = self.headers(
437            self.http()
438                .get(&url)
439                .header("accept", "text/event-stream")
440                .timeout(STREAM_TIMEOUT),
441        );
442        let connect = |e: reqwest::Error| connect_error(&self.server, e);
443        let mut response = builder.send().await.map_err(connect)?;
444        refuse_redirect(&self.server, &response)?;
445        if !response.status().is_success() {
446            return Err(ClientError::Server {
447                status: response.status().as_u16(),
448                message: format!("the server answered {}", response.status()),
449            });
450        }
451        let (sender, chunks) = Chunks::channel();
452        let server = self.server.clone();
453        tokio::spawn(async move {
454            loop {
455                // A reader gone is noticed at once, not at the next chunk: a stalled stream
456                // would otherwise stay open (its socket too) until its timeout (B138).
457                let next = tokio::select! {
458                    () = sender.closed() => return,
459                    next = response.chunk() => next,
460                };
461                let chunk = match next {
462                    Ok(Some(chunk)) => Ok(chunk.to_vec()),
463                    Ok(None) => return,
464                    Err(e) => Err(connect_error(&server, e)),
465                };
466                let failed = chunk.is_err();
467                // The reader went away, or the stream failed: done either way.
468                if sender.send(chunk).await.is_err() || failed {
469                    return;
470                }
471            }
472        });
473        Ok(chunks)
474    }
475}
476
477/// The server couldn't be reached: with its URL and the reason shown masked, so a password
478/// in the URL (`[ui] deployments`, `--server`) or in what the HTTP library says never shows
479/// (Codex's review of M4.4b).
480fn connect_error(server: &str, reason: impl std::fmt::Display) -> ClientError {
481    ClientError::Connect {
482        server: schedr_config::masked::mask_text(server),
483        reason: schedr_config::masked::mask_text(&reason.to_string()),
484    }
485}
486
487/// A redirect is an error: it is never followed (B133), since the request carries
488/// credentials (the UI's token, a password, the person's name) that would go wherever it
489/// points. The message names that address, to be configured instead.
490fn refuse_redirect(server: &str, response: &reqwest::Response) -> Result<(), ClientError> {
491    if !response.status().is_redirection() {
492        return Ok(());
493    }
494    let to = response
495        .headers()
496        .get(reqwest::header::LOCATION)
497        .and_then(|l| l.to_str().ok())
498        .unwrap_or("an address it didn't give");
499    Err(connect_error(
500        server,
501        format!(
502            "it answered {} redirecting to {to}; schedr follows no redirect (the request's \
503             credentials would go there too): configure the address it should reach",
504            response.status()
505        ),
506    ))
507}
508
509/// An HTTP client presenting `tls`'s certificate (its `api_client` configuration).
510fn mtls_client(tls: &schedr_tls::Tls, timeouts: Timeouts) -> reqwest::Client {
511    reqwest::Client::builder()
512        .connect_timeout(timeouts.connect)
513        .timeout(timeouts.request)
514        .redirect(reqwest::redirect::Policy::none())
515        .tls_backend_preconfigured((*tls.api_client()).clone())
516        .build()
517        .expect("the HTTP client builds with its timeouts and TLS configuration")
518}
519
520/// The API in the same process: requests go straight to its router, with no network (the
521/// web UI of `schedr standalone`, and tests).
522#[derive(Debug, Clone)]
523pub struct RouterTransport {
524    app: axum::Router,
525}
526
527impl RouterTransport {
528    /// A transport to the API served by `app` (the webserver's router).
529    #[must_use]
530    pub const fn new(app: axum::Router) -> Self {
531        Self { app }
532    }
533}
534
535impl Transport for RouterTransport {
536    async fn send(&self, request: ApiRequest) -> Result<ApiResponse, ClientError> {
537        use http_body_util::BodyExt as _;
538        use tower::ServiceExt as _;
539        let in_process = |reason: String| ClientError::Connect {
540            server: "the API in this process".to_owned(),
541            reason,
542        };
543        let method = match request.method {
544            Method::Get => axum::http::Method::GET,
545            Method::Post => axum::http::Method::POST,
546        };
547        let body = request.body.map_or_else(axum::body::Body::empty, |b| {
548            axum::body::Body::from(b.to_string())
549        });
550        let mut builder = axum::http::Request::builder()
551            .method(method)
552            .uri(&request.path)
553            .header("content-type", "application/json");
554        if let Some(key) = &request.key {
555            builder = builder.header("idempotency-key", key);
556        }
557        let http = in_process_request(builder)
558            .body(body)
559            .map_err(|e| in_process(e.to_string()))?;
560        let response = self
561            .app
562            .clone()
563            .oneshot(http)
564            .await
565            .map_err(|e| in_process(e.to_string()))?;
566        let status = response.status().as_u16();
567        let bytes = response
568            .into_body()
569            .collect()
570            .await
571            .map_err(|e| in_process(e.to_string()))?
572            .to_bytes();
573        Ok(ApiResponse {
574            status,
575            body: serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null),
576        })
577    }
578
579    async fn open(&self, path: String) -> Result<Chunks, ClientError> {
580        use http_body_util::BodyExt as _;
581        use tower::ServiceExt as _;
582        let in_process = |reason: String| ClientError::Connect {
583            server: "the API in this process".to_owned(),
584            reason,
585        };
586        let http = in_process_request(
587            axum::http::Request::builder()
588                .uri(&path)
589                .header("accept", "text/event-stream"),
590        )
591        .body(axum::body::Body::empty())
592        .map_err(|e| in_process(e.to_string()))?;
593        let response = self
594            .app
595            .clone()
596            .oneshot(http)
597            .await
598            .map_err(|e| in_process(e.to_string()))?;
599        if !response.status().is_success() {
600            return Err(ClientError::Server {
601                status: response.status().as_u16(),
602                message: format!("the server answered {}", response.status()),
603            });
604        }
605        let mut body = response.into_body();
606        let (sender, chunks) = Chunks::channel();
607        tokio::spawn(async move {
608            loop {
609                // As over HTTP: a reader gone is noticed at once (B138).
610                let frame = tokio::select! {
611                    () = sender.closed() => return,
612                    frame = body.frame() => frame,
613                };
614                let Some(frame) = frame else { return };
615                let chunk = match frame {
616                    Ok(frame) => match frame.into_data() {
617                        Ok(data) => Ok(data.to_vec()),
618                        Err(_) => continue,
619                    },
620                    Err(e) => Err(in_process(e.to_string())),
621                };
622                let failed = chunk.is_err();
623                if sender.send(chunk).await.is_err() || failed {
624                    return;
625                }
626            }
627        });
628        Ok(chunks)
629    }
630}
631
632/// A request to the API in this process: the version, the person it is made for, and marked
633/// as the UI's, proven by coming from inside the process (an extension: nothing from the
634/// network can set it; see `schedr_api::auth`).
635fn in_process_request(builder: axum::http::request::Builder) -> axum::http::request::Builder {
636    let mut builder = builder
637        .header(CLIENT_VERSION_HEADER, VERSION)
638        .extension(schedr_api::auth::ProvenUi);
639    if let Some(user) = current_user() {
640        builder = builder.header(schedr_api::auth::USER_HEADER, user);
641    }
642    builder
643}
644
645/// Typed calls to the API.
646#[derive(Debug, Clone)]
647pub struct Client<T> {
648    transport: T,
649    poll: Duration,
650    timeout: Duration,
651}
652
653impl<T: Transport> Client<T> {
654    /// A client over `transport`, waiting for decisions every `poll` for at most `timeout`.
655    pub const fn new(transport: T, poll: Duration, timeout: Duration) -> Self {
656        Self {
657            transport,
658            poll,
659            timeout,
660        }
661    }
662
663    /// The transport.
664    pub const fn transport(&self) -> &T {
665        &self.transport
666    }
667
668    /// How often it reads again while waiting (a decision, a growing log).
669    pub const fn poll(&self) -> Duration {
670        self.poll
671    }
672
673    /// `GET /api/v1/workers`.
674    ///
675    /// # Errors
676    ///
677    /// [`ClientError`] if the request fails or the answer doesn't read.
678    pub async fn workers(&self) -> Result<WorkerList, ClientError> {
679        self.call(Method::Get, "/api/v1/workers".to_owned(), None)
680            .await
681    }
682
683    /// `GET /api/v1/triggers`: every DAG's trigger.
684    ///
685    /// # Errors
686    ///
687    /// [`ClientError`] if the request fails or the answer doesn't read.
688    pub async fn triggers(&self) -> Result<TriggerList, ClientError> {
689        self.call(Method::Get, "/api/v1/triggers".to_owned(), None)
690            .await
691    }
692
693    /// `GET /api/v1/dags/{dag}/trigger`: a DAG's trigger.
694    ///
695    /// # Errors
696    ///
697    /// [`ClientError`] if the request fails or the answer doesn't read.
698    pub async fn dag_trigger(&self, dag: &str) -> Result<TriggerView, ClientError> {
699        self.call(
700            Method::Get,
701            format!("/api/v1/dags/{}/trigger", path(dag)),
702            None,
703        )
704        .await
705    }
706
707    /// `GET /api/v1/dags/{dag}/trigger/events`: what it found, newest first.
708    ///
709    /// # Errors
710    ///
711    /// [`ClientError`] if the request fails or the answer doesn't read.
712    pub async fn trigger_events(&self, dag: &str, limit: u32) -> Result<EventList, ClientError> {
713        self.call(
714            Method::Get,
715            format!("/api/v1/dags/{}/trigger/events?limit={limit}", path(dag)),
716            None,
717        )
718        .await
719    }
720
721    /// `POST /api/v1/events`: posts an event (decision 354), sent under the current command key
722    /// when [`with_command_key`] set one (so [`Client::submit`] can send it again safely).
723    ///
724    /// # Errors
725    ///
726    /// [`ClientError`] if the request fails or the answer doesn't read.
727    pub async fn post_event(
728        &self,
729        event: &PostEventRequest,
730    ) -> Result<NamedEventView, ClientError> {
731        self.call(
732            Method::Post,
733            "/api/v1/events".to_owned(),
734            Some(to_body(event)?),
735        )
736        .await
737    }
738
739    /// `GET /api/v1/events`: the newest events posted, of `name` if given, at most `limit`.
740    ///
741    /// # Errors
742    ///
743    /// [`ClientError`] if the request fails or the answer doesn't read.
744    pub async fn named_events(
745        &self,
746        name: Option<&str>,
747        limit: u32,
748    ) -> Result<NamedEventList, ClientError> {
749        let name = name.map_or_else(String::new, |name| format!("&name={}", path(name)));
750        self.call(
751            Method::Get,
752            format!("/api/v1/events?limit={limit}{name}"),
753            None,
754        )
755        .await
756    }
757
758    /// `POST /api/v1/dags/{dag}/trigger/restart`: the command.
759    ///
760    /// # Errors
761    ///
762    /// [`ClientError`] if the request fails or the answer doesn't read.
763    pub async fn restart_trigger(&self, dag: &str) -> Result<CommandView, ClientError> {
764        self.call(
765            Method::Post,
766            format!("/api/v1/dags/{}/trigger/restart", path(dag)),
767            None,
768        )
769        .await
770    }
771
772    /// `POST /api/v1/dags/{dag}/trigger/skip`: the command.
773    ///
774    /// # Errors
775    ///
776    /// [`ClientError`] if the request fails or the answer doesn't read.
777    pub async fn skip_trigger_run(&self, dag: &str) -> Result<CommandView, ClientError> {
778        self.call(
779            Method::Post,
780            format!("/api/v1/dags/{}/trigger/skip", path(dag)),
781            None,
782        )
783        .await
784    }
785
786    /// `POST /api/v1/dags/{dag}/trigger/switch-on`: the command.
787    ///
788    /// # Errors
789    ///
790    /// [`ClientError`] if the request fails or the answer doesn't read.
791    pub async fn switch_on_trigger(&self, dag: &str) -> Result<CommandView, ClientError> {
792        self.call(
793            Method::Post,
794            format!("/api/v1/dags/{}/trigger/switch-on", path(dag)),
795            None,
796        )
797        .await
798    }
799
800    /// `GET /api/v1/sensors/switched-off`: the wait steps switched off.
801    ///
802    /// # Errors
803    ///
804    /// [`ClientError`] if the request fails or the answer doesn't read.
805    pub async fn switched_off_sensors(&self) -> Result<SensorList, ClientError> {
806        self.call(Method::Get, "/api/v1/sensors/switched-off".to_owned(), None)
807            .await
808    }
809
810    /// `POST /api/v1/dags/{dag}/sensors/{sensor}/switch-on`: the command.
811    ///
812    /// # Errors
813    ///
814    /// [`ClientError`] if the request fails or the answer doesn't read.
815    pub async fn switch_on_sensor(
816        &self,
817        dag: &str,
818        sensor: &str,
819    ) -> Result<CommandView, ClientError> {
820        self.call(
821            Method::Post,
822            format!(
823                "/api/v1/dags/{}/sensors/{}/switch-on",
824                path(dag),
825                path(sensor)
826            ),
827            None,
828        )
829        .await
830    }
831
832    /// `GET /api/v1/runs/{run}/resources`: a run's resources.
833    ///
834    /// # Errors
835    ///
836    /// [`ClientError`] if the request fails or the answer doesn't read.
837    pub async fn run_resources(&self, run: &str) -> Result<ResourceList, ClientError> {
838        self.call(
839            Method::Get,
840            format!("/api/v1/runs/{}/resources", path(run)),
841            None,
842        )
843        .await
844    }
845
846    /// `GET /api/v1/deployment`: the deployment's nodes and their configurations (masked).
847    ///
848    /// # Errors
849    ///
850    /// [`ClientError`] if the request fails or the answer doesn't read.
851    pub async fn deployment(&self) -> Result<DeploymentView, ClientError> {
852        self.call(Method::Get, "/api/v1/deployment".to_owned(), None)
853            .await
854    }
855
856    /// `GET /api/v1/metrics/samples`: each process's samples over `range` (`1h`, `24h`, `7d`,
857    /// `30d`), or one process's.
858    ///
859    /// # Errors
860    ///
861    /// [`ClientError`] if the request fails or the answer doesn't read.
862    pub async fn samples(
863        &self,
864        range: &str,
865        process: Option<&str>,
866    ) -> Result<SampleSeriesList, ClientError> {
867        let process = process.map_or_else(String::new, |p| format!("&process={}", path(p)));
868        self.call(
869            Method::Get,
870            format!("/api/v1/metrics/samples?range={}{process}", path(range)),
871            None,
872        )
873        .await
874    }
875
876    /// `GET /api/v1/metrics/tasks`: the attempts over `range` in buckets: how many ended, by
877    /// how, and the start latency of those started (decision 494).
878    ///
879    /// # Errors
880    ///
881    /// [`ClientError`] if the request fails or the answer doesn't read.
882    pub async fn task_flow(&self, range: &str) -> Result<TaskFlowList, ClientError> {
883        self.call(
884            Method::Get,
885            format!("/api/v1/metrics/tasks?range={}", path(range)),
886            None,
887        )
888        .await
889    }
890
891    /// `GET /api/v1/metrics/memory`: every process's memory together over `range`.
892    ///
893    /// # Errors
894    ///
895    /// [`ClientError`] if the request fails or the answer doesn't read.
896    pub async fn memory_totals(&self, range: &str) -> Result<MemoryTotals, ClientError> {
897        self.call(
898            Method::Get,
899            format!("/api/v1/metrics/memory?range={}", path(range)),
900            None,
901        )
902        .await
903    }
904
905    /// `GET /api/v1/dags/{dag}/tasks/{task}/memory`: the task's last attempts' peak memory.
906    ///
907    /// # Errors
908    ///
909    /// [`ClientError`] if the request fails or the answer doesn't read.
910    pub async fn task_memory(
911        &self,
912        dag: &str,
913        task: &str,
914    ) -> Result<AttemptMemoryList, ClientError> {
915        self.call(
916            Method::Get,
917            format!("/api/v1/dags/{}/tasks/{}/memory", path(dag), path(task)),
918            None,
919        )
920        .await
921    }
922
923    /// `GET /api/v1/dags/{dag}/memory`: each task's p95 peak memory against its limit.
924    ///
925    /// # Errors
926    ///
927    /// [`ClientError`] if the request fails or the answer doesn't read.
928    pub async fn dag_memory(&self, dag: &str) -> Result<DagMemoryList, ClientError> {
929        self.call(
930            Method::Get,
931            format!("/api/v1/dags/{}/memory", path(dag)),
932            None,
933        )
934        .await
935    }
936
937    /// `GET /api/v1/import-errors`.
938    ///
939    /// # Errors
940    ///
941    /// [`ClientError`] if the request fails or the answer doesn't read.
942    pub async fn import_errors(&self) -> Result<ImportErrorList, ClientError> {
943        self.call(Method::Get, "/api/v1/import-errors".to_owned(), None)
944            .await
945    }
946
947    /// `GET /api/v1/connections`: each root's connections and the tasks declaring them.
948    ///
949    /// # Errors
950    ///
951    /// [`ClientError`] if the request fails or the answer doesn't read.
952    pub async fn connections(&self) -> Result<ConnectionList, ClientError> {
953        self.call(Method::Get, "/api/v1/connections".to_owned(), None)
954            .await
955    }
956
957    /// `GET /api/v1/dags`.
958    ///
959    /// # Errors
960    ///
961    /// [`ClientError`] if the request fails or the answer doesn't read.
962    pub async fn dags(&self) -> Result<DagList, ClientError> {
963        self.call(Method::Get, "/api/v1/dags".to_owned(), None)
964            .await
965    }
966
967    /// `GET /api/v1/dags/{dag}`.
968    ///
969    /// # Errors
970    ///
971    /// [`ClientError`] if the request fails (a DAG that doesn't exist: the server's 404) or
972    /// the answer doesn't read.
973    pub async fn dag(&self, dag: &str) -> Result<DagView, ClientError> {
974        self.call(Method::Get, format!("/api/v1/dags/{}", path(dag)), None)
975            .await
976    }
977
978    /// `GET /api/v1/dags/{dag}/runs`, optionally for one moment.
979    ///
980    /// # Errors
981    ///
982    /// [`ClientError`] if the request fails or the answer doesn't read.
983    pub async fn runs(
984        &self,
985        dag: &str,
986        planned_for: Option<Timestamp>,
987    ) -> Result<RunList, ClientError> {
988        let query = planned_for.map_or_else(String::new, |t| format!("?for={t}"));
989        self.call(
990            Method::Get,
991            format!("/api/v1/dags/{}/runs{query}", path(dag)),
992            None,
993        )
994        .await
995    }
996
997    /// `GET /api/v1/runs?dag=...&state=...&before=...&before_run=...&limit=...`: runs of every DAG (or one),
998    /// newest triggered first.
999    ///
1000    /// # Errors
1001    ///
1002    /// [`ClientError`] if the request fails or the answer doesn't read.
1003    pub async fn all_runs(&self, query: &AllRunsQuery) -> Result<RunList, ClientError> {
1004        let mut params = Vec::new();
1005        if let Some(dag) = &query.dag {
1006            params.push(format!("dag={}", path(dag.as_str())));
1007        }
1008        if let Some(part) = &query.dag_contains {
1009            params.push(format!("dag_contains={}", path(part)));
1010        }
1011        if let Some(state) = query.state {
1012            params.push(format!("state={state}"));
1013        }
1014        if let Some(before) = query.before {
1015            params.push(format!("before={}", path(&before.to_string())));
1016        }
1017        if let Some(run_id) = &query.before_run {
1018            params.push(format!("before_run={}", path(run_id)));
1019        }
1020        if let Some(limit) = query.limit {
1021            params.push(format!("limit={limit}"));
1022        }
1023        let query = if params.is_empty() {
1024            String::new()
1025        } else {
1026            format!("?{}", params.join("&"))
1027        };
1028        self.call(Method::Get, format!("/api/v1/runs{query}"), None)
1029            .await
1030    }
1031
1032    /// `GET /api/v1/runs/{run}/dag`: the DAG JSON of the version the run ran with.
1033    ///
1034    /// # Errors
1035    ///
1036    /// [`ClientError`] if the request fails or the answer doesn't read.
1037    pub async fn run_dag(&self, run_id: &str) -> Result<serde_json::Value, ClientError> {
1038        self.call(
1039            Method::Get,
1040            format!("/api/v1/runs/{}/dag", path(run_id)),
1041            None,
1042        )
1043        .await
1044    }
1045
1046    /// `GET /api/v1/runs/{run}/commands`.
1047    ///
1048    /// # Errors
1049    ///
1050    /// [`ClientError`] if the request fails or the answer doesn't read.
1051    pub async fn run_commands(&self, run_id: &str) -> Result<CommandList, ClientError> {
1052        self.call(
1053            Method::Get,
1054            format!("/api/v1/runs/{}/commands", path(run_id)),
1055            None,
1056        )
1057        .await
1058    }
1059
1060    /// `GET /api/v1/runs/{run}/tasks/{task}/output` (an error with status 404 while it has
1061    /// none).
1062    ///
1063    /// # Errors
1064    ///
1065    /// [`ClientError`] if the request fails or the answer doesn't read.
1066    pub async fn output(&self, run_id: &str, task_id: &str) -> Result<OutputView, ClientError> {
1067        self.instance_output(run_id, task_id, None).await
1068    }
1069
1070    /// As [`Self::output`], of one instance of a mapped task (`None`: a mapped task's whole
1071    /// list, decision 81).
1072    ///
1073    /// # Errors
1074    ///
1075    /// As [`Self::output`].
1076    pub async fn instance_output(
1077        &self,
1078        run_id: &str,
1079        task_id: &str,
1080        map_index: Option<u32>,
1081    ) -> Result<OutputView, ClientError> {
1082        self.call(
1083            Method::Get,
1084            format!(
1085                "/api/v1/runs/{}/tasks/{}/output{}",
1086                path(run_id),
1087                path(task_id),
1088                instance(map_index, '?')
1089            ),
1090            None,
1091        )
1092        .await
1093    }
1094
1095    /// `GET /api/v1/changes`: what changed, as it happens (`run`, `dag`, `workers` and
1096    /// `refresh` events).
1097    ///
1098    /// # Errors
1099    ///
1100    /// [`ClientError`] if the stream can't be opened.
1101    pub async fn events(&self) -> Result<EventReader, ClientError> {
1102        let chunks = self.transport.open("/api/v1/changes".to_owned()).await?;
1103        Ok(EventReader::new(chunks))
1104    }
1105
1106    /// `GET /api/v1/commands/{command}`: a command and the master's decision.
1107    ///
1108    /// # Errors
1109    ///
1110    /// [`ClientError`] if the request fails or the answer doesn't read.
1111    pub async fn command(&self, command_id: &str) -> Result<CommandView, ClientError> {
1112        self.call(
1113            Method::Get,
1114            format!("/api/v1/commands/{}", path(command_id)),
1115            None,
1116        )
1117        .await
1118    }
1119
1120    /// `GET /api/v1/runs/{run}`.
1121    ///
1122    /// # Errors
1123    ///
1124    /// [`ClientError`] if the request fails or the answer doesn't read.
1125    pub async fn run(&self, run_id: &str) -> Result<RunDetail, ClientError> {
1126        self.call(Method::Get, format!("/api/v1/runs/{}", path(run_id)), None)
1127            .await
1128    }
1129
1130    /// `GET /api/v1/runs/{run}/tasks/{task}/attempts`.
1131    ///
1132    /// # Errors
1133    ///
1134    /// [`ClientError`] if the request fails or the answer doesn't read.
1135    pub async fn attempts(&self, run_id: &str, task_id: &str) -> Result<AttemptList, ClientError> {
1136        self.instance_attempts(run_id, task_id, None).await
1137    }
1138
1139    /// As [`Self::attempts`], of one instance of a mapped task (decision 82).
1140    ///
1141    /// # Errors
1142    ///
1143    /// As [`Self::attempts`].
1144    pub async fn instance_attempts(
1145        &self,
1146        run_id: &str,
1147        task_id: &str,
1148        map_index: Option<u32>,
1149    ) -> Result<AttemptList, ClientError> {
1150        self.call(
1151            Method::Get,
1152            format!(
1153                "/api/v1/runs/{}/tasks/{}/attempts{}",
1154                path(run_id),
1155                path(task_id),
1156                instance(map_index, '?')
1157            ),
1158            None,
1159        )
1160        .await
1161    }
1162
1163    /// `GET /api/v1/runs/{run}/tasks/{task}/attempts/{try}/log?from=...`.
1164    ///
1165    /// # Errors
1166    ///
1167    /// [`ClientError`] if the request fails (the worker is gone, the log deleted) or the
1168    /// answer doesn't read.
1169    pub async fn log(
1170        &self,
1171        run_id: &str,
1172        task_id: &str,
1173        try_number: u32,
1174        from: u64,
1175    ) -> Result<LogChunk, ClientError> {
1176        self.call(
1177            Method::Get,
1178            format!(
1179                "/api/v1/runs/{}/tasks/{}/attempts/{try_number}/log?from={from}",
1180                path(run_id),
1181                path(task_id)
1182            ),
1183            None,
1184        )
1185        .await
1186    }
1187
1188    /// As [`Self::log`], at most `limit` bytes (the API's limits apply).
1189    ///
1190    /// # Errors
1191    ///
1192    /// As [`Self::log`].
1193    pub async fn log_part(
1194        &self,
1195        run_id: &str,
1196        task_id: &str,
1197        try_number: u32,
1198        from: u64,
1199        limit: u64,
1200    ) -> Result<LogChunk, ClientError> {
1201        self.instance_log_part(run_id, (task_id, None), try_number, from, limit)
1202            .await
1203    }
1204
1205    /// As [`Self::log_part`], of one instance of a mapped task (decision 82).
1206    ///
1207    /// # Errors
1208    ///
1209    /// As [`Self::log`].
1210    pub async fn instance_log_part(
1211        &self,
1212        run_id: &str,
1213        (task_id, map_index): (&str, Option<u32>),
1214        try_number: u32,
1215        from: u64,
1216        limit: u64,
1217    ) -> Result<LogChunk, ClientError> {
1218        self.call(
1219            Method::Get,
1220            format!(
1221                "/api/v1/runs/{}/tasks/{}/attempts/{try_number}/log?from={from}&limit={limit}{}",
1222                path(run_id),
1223                path(task_id),
1224                instance(map_index, '&')
1225            ),
1226            None,
1227        )
1228        .await
1229    }
1230
1231    /// `POST /api/v1/dags/{dag}/pause` or `.../unpause`: the command.
1232    ///
1233    /// # Errors
1234    ///
1235    /// [`ClientError`] if the request fails or the answer doesn't read.
1236    pub async fn set_paused(
1237        &self,
1238        dag: &str,
1239        paused: bool,
1240        cancel_runs: bool,
1241    ) -> Result<CommandView, ClientError> {
1242        let (action, body) = if paused {
1243            let request = PauseRequest { cancel_runs };
1244            ("pause", Some(to_body(&request)?))
1245        } else {
1246            ("unpause", None)
1247        };
1248        self.call(
1249            Method::Post,
1250            format!("/api/v1/dags/{}/{action}", path(dag)),
1251            body,
1252        )
1253        .await
1254    }
1255
1256    /// `POST /api/v1/dags/{dag}/runs`: the command; `params`, values for the run's
1257    /// parameters over the DAG's defaults.
1258    ///
1259    /// # Errors
1260    ///
1261    /// [`ClientError`] if the request fails or the answer doesn't read.
1262    pub async fn trigger(
1263        &self,
1264        dag: &str,
1265        planned_for: Option<Timestamp>,
1266        params: Option<&serde_json::Map<String, serde_json::Value>>,
1267    ) -> Result<CommandView, ClientError> {
1268        self.trigger_with(
1269            dag,
1270            &TriggerRequest {
1271                planned_for,
1272                params: params.cloned(),
1273                ..TriggerRequest::default()
1274            },
1275        )
1276        .await
1277    }
1278
1279    /// `POST /api/v1/dags/{dag}/runs`: the command, for a run asked for in full.
1280    ///
1281    /// # Errors
1282    ///
1283    /// [`ClientError`] if the request fails or the answer doesn't read.
1284    pub async fn trigger_with(
1285        &self,
1286        dag: &str,
1287        request: &TriggerRequest,
1288    ) -> Result<CommandView, ClientError> {
1289        let body = to_body(request)?;
1290        self.call(
1291            Method::Post,
1292            format!("/api/v1/dags/{}/runs", path(dag)),
1293            Some(body),
1294        )
1295        .await
1296    }
1297
1298    /// `POST /api/v1/dags/{dag}/backfills`: the command (`schedr runs backfill`).
1299    ///
1300    /// # Errors
1301    ///
1302    /// [`ClientError`] if the request fails or the answer doesn't read.
1303    pub async fn backfill(
1304        &self,
1305        dag: &str,
1306        request: &BackfillRequest,
1307    ) -> Result<CommandView, ClientError> {
1308        let body = to_body(request)?;
1309        self.call(
1310            Method::Post,
1311            format!("/api/v1/dags/{}/backfills", path(dag)),
1312            Some(body),
1313        )
1314        .await
1315    }
1316
1317    /// `GET /api/v1/dags/{dag}/backfills`: its newest backfills.
1318    ///
1319    /// # Errors
1320    ///
1321    /// [`ClientError`] if the request fails or the answer doesn't read.
1322    pub async fn dag_backfills(&self, dag: &str) -> Result<BackfillList, ClientError> {
1323        self.call(
1324            Method::Get,
1325            format!("/api/v1/dags/{}/backfills", path(dag)),
1326            None,
1327        )
1328        .await
1329    }
1330
1331    /// `GET /api/v1/backfills/{backfill}`.
1332    ///
1333    /// # Errors
1334    ///
1335    /// [`ClientError`] if the request fails or the answer doesn't read.
1336    pub async fn get_backfill(&self, backfill_id: &str) -> Result<BackfillView, ClientError> {
1337        self.call(
1338            Method::Get,
1339            format!("/api/v1/backfills/{}", path(backfill_id)),
1340            None,
1341        )
1342        .await
1343    }
1344
1345    /// `POST /api/v1/backfills/{backfill}/cancel`: the command (`schedr runs cancel --backfill`).
1346    ///
1347    /// # Errors
1348    ///
1349    /// [`ClientError`] if the request fails or the answer doesn't read.
1350    pub async fn cancel_backfill(&self, backfill_id: &str) -> Result<CommandView, ClientError> {
1351        self.call(
1352            Method::Post,
1353            format!("/api/v1/backfills/{}/cancel", path(backfill_id)),
1354            None,
1355        )
1356        .await
1357    }
1358
1359    /// `POST /api/v1/connections/check`: the command (`schedr connections check`).
1360    ///
1361    /// # Errors
1362    ///
1363    /// [`ClientError`] if the request fails or the answer doesn't read.
1364    pub async fn check_connections(
1365        &self,
1366        request: &CheckConnectionsRequest,
1367    ) -> Result<CommandView, ClientError> {
1368        let body = to_body(request)?;
1369        self.call(
1370            Method::Post,
1371            "/api/v1/connections/check".to_owned(),
1372            Some(body),
1373        )
1374        .await
1375    }
1376
1377    /// `POST /api/v1/connections/{name}/test`: the command (`schedr connections test`).
1378    ///
1379    /// # Errors
1380    ///
1381    /// [`ClientError`] if the request fails or the answer doesn't read.
1382    pub async fn test_connection(
1383        &self,
1384        name: &str,
1385        request: &TestConnectionRequest,
1386    ) -> Result<CommandView, ClientError> {
1387        let body = to_body(request)?;
1388        self.call(
1389            Method::Post,
1390            format!("/api/v1/connections/{}/test", path(name)),
1391            Some(body),
1392        )
1393        .await
1394    }
1395
1396    /// Reads an applied connections command back until every job has its answer (or was
1397    /// lost), for at most `timeout`: its result.
1398    ///
1399    /// # Errors
1400    ///
1401    /// [`ClientError::Timeout`] if a worker hasn't answered by then, a result that doesn't
1402    /// read ([`ClientError::Unexpected`]), or a request failure.
1403    pub async fn wait_connections(
1404        &self,
1405        command: CommandView,
1406        timeout: Duration,
1407    ) -> Result<ConnectionsResult, ClientError> {
1408        let deadline = tokio::time::Instant::now() + timeout;
1409        let mut current = command;
1410        loop {
1411            let result: ConnectionsResult = current
1412                .result
1413                .clone()
1414                .map(serde_json::from_value)
1415                .transpose()
1416                .map_err(|e| ClientError::Unexpected(format!("a connections result: {e}")))?
1417                .unwrap_or_default();
1418            if result.finished() {
1419                return Ok(result);
1420            }
1421            if tokio::time::Instant::now() >= deadline {
1422                return Err(ClientError::Timeout {
1423                    command_id: current.command_id,
1424                });
1425            }
1426            tokio::time::sleep(self.poll).await;
1427            current = self.command(&current.command_id).await?;
1428        }
1429    }
1430
1431    /// `POST /api/v1/runs/{run}/cancel`: the command.
1432    ///
1433    /// # Errors
1434    ///
1435    /// [`ClientError`] if the request fails or the answer doesn't read.
1436    pub async fn cancel(&self, run_id: &str) -> Result<CommandView, ClientError> {
1437        self.call(
1438            Method::Post,
1439            format!("/api/v1/runs/{}/cancel", path(run_id)),
1440            None,
1441        )
1442        .await
1443    }
1444
1445    /// `POST /api/v1/runs/{run}/tasks/{task}/{action}` (`cancel` or `retry`): the command.
1446    ///
1447    /// # Errors
1448    ///
1449    /// [`ClientError`] if the request fails or the answer doesn't read.
1450    pub async fn task_action(
1451        &self,
1452        run_id: &str,
1453        (task_id, map_index): (&str, Option<u32>),
1454        action: TaskAction,
1455    ) -> Result<CommandView, ClientError> {
1456        let action = match action {
1457            TaskAction::Cancel => "cancel",
1458            TaskAction::Retry => "retry",
1459        };
1460        self.call(
1461            Method::Post,
1462            format!(
1463                "/api/v1/runs/{}/tasks/{}/{action}{}",
1464                path(run_id),
1465                path(task_id),
1466                instance(map_index, '?')
1467            ),
1468            None,
1469        )
1470        .await
1471    }
1472
1473    /// `POST /api/v1/workers/{worker}/{action}` (`drain` or `resume`): the command.
1474    ///
1475    /// # Errors
1476    ///
1477    /// [`ClientError`] if the request fails or the answer doesn't read.
1478    pub async fn worker_action(
1479        &self,
1480        worker_id: &str,
1481        action: WorkerAction,
1482    ) -> Result<CommandView, ClientError> {
1483        let action = match action {
1484            WorkerAction::Drain => "drain",
1485            WorkerAction::Resume => "resume",
1486        };
1487        self.call(
1488            Method::Post,
1489            format!("/api/v1/workers/{}/{action}", path(worker_id)),
1490            None,
1491        )
1492        .await
1493    }
1494
1495    /// [`Self::submit`] under a new key: one command, stored once however often it is sent
1496    /// (boxed: its future stays small in the caller's). For one-shot callers (the CLI), whose
1497    /// key is gone once they return.
1498    ///
1499    /// # Errors
1500    ///
1501    /// As [`Self::submit`], but [`ClientError::Unanswered`] when no answer came: the command
1502    /// may have arrived.
1503    pub async fn send_command<F>(&self, request: impl Fn() -> F) -> Result<CommandView, ClientError>
1504    where
1505        F: Future<Output = Result<CommandView, ClientError>>,
1506    {
1507        match Box::pin(self.submit(new_command_key(), request)).await {
1508            Err(
1509                error @ (ClientError::Connect { .. } | ClientError::Server { status: 500.., .. }),
1510            ) => Err(ClientError::Unanswered {
1511                reason: error.to_string(),
1512            }),
1513            // No try made a connection: said so, the command can be sent again (B215).
1514            Err(ClientError::Unreachable { server, reason }) => Err(ClientError::Unreachable {
1515                server,
1516                reason: format!("{reason}; the command wasn't sent"),
1517            }),
1518            other => other,
1519        }
1520    }
1521
1522    /// Sends a command with `request`, stored once (B140): under `key` (the client's
1523    /// `Idempotency-Key`; [`new_command_key`] for a new one), and sent again with the same key,
1524    /// at most [`COMMAND_TRIES`] times in all, while no answer comes or the server fails (it may
1525    /// have stored it): the webserver gives the command stored the first time.
1526    ///
1527    /// # Errors
1528    ///
1529    /// The last try's [`ClientError`], or the first that isn't worth another try (the server
1530    /// refused the command).
1531    pub async fn submit<R, F>(&self, key: String, request: impl Fn() -> F) -> Result<R, ClientError>
1532    where
1533        F: Future<Output = Result<R, ClientError>>,
1534    {
1535        let mut delay = self.poll;
1536        let mut tries = 1;
1537        // Whether a try may have reached the server: then the last one's `Unreachable` doesn't
1538        // mean the command was never sent.
1539        let mut reached = false;
1540        loop {
1541            let sent = with_command_key(key.clone(), request()).await;
1542            let again = match &sent {
1543                Err(ClientError::Unreachable { .. }) => true,
1544                Err(ClientError::Connect { .. }) => {
1545                    reached = true;
1546                    true
1547                }
1548                Err(ClientError::Server { status, .. }) => {
1549                    reached = true;
1550                    *status >= 500
1551                }
1552                _ => false,
1553            };
1554            if !again || tries >= COMMAND_TRIES {
1555                return match sent {
1556                    Err(ClientError::Unreachable { server, reason }) if reached => {
1557                        Err(ClientError::Connect { server, reason })
1558                    }
1559                    other => other,
1560                };
1561            }
1562            tokio::time::sleep(delay).await;
1563            delay = delay.saturating_mul(2);
1564            tries += 1;
1565        }
1566    }
1567
1568    /// Reads `command` back until the master decides it.
1569    ///
1570    /// # Errors
1571    ///
1572    /// [`ClientError::Rejected`] with the master's reason, [`ClientError::Timeout`] if it
1573    /// stays pending, or a request failure.
1574    pub async fn wait(&self, command: CommandView) -> Result<CommandView, ClientError> {
1575        let deadline = tokio::time::Instant::now() + self.timeout;
1576        let mut current = command;
1577        loop {
1578            match current.status.as_str() {
1579                "applied" => return Ok(current),
1580                "rejected" => {
1581                    return Err(ClientError::Rejected(current.reason.unwrap_or_default()));
1582                }
1583                _ => {}
1584            }
1585            if tokio::time::Instant::now() >= deadline {
1586                return Err(ClientError::Timeout {
1587                    command_id: current.command_id,
1588                });
1589            }
1590            tokio::time::sleep(self.poll).await;
1591            current = self
1592                .call(
1593                    Method::Get,
1594                    format!("/api/v1/commands/{}", path(&current.command_id)),
1595                    None,
1596                )
1597                .await?;
1598        }
1599    }
1600
1601    async fn call<R: DeserializeOwned>(
1602        &self,
1603        method: Method,
1604        path: String,
1605        body: Option<serde_json::Value>,
1606    ) -> Result<R, ClientError> {
1607        let key = match method {
1608            Method::Post => COMMAND_KEY.try_with(Clone::clone).ok(),
1609            Method::Get => None,
1610        };
1611        let response = self
1612            .transport
1613            .send(ApiRequest {
1614                method,
1615                path,
1616                body,
1617                key,
1618            })
1619            .await?;
1620        if !(200..300).contains(&response.status) {
1621            // Masked: an error may quote an address with its password (as `connect_error`).
1622            let message = response.body["error"].as_str().map_or_else(
1623                || format!("the server answered {}", response.status),
1624                schedr_config::masked::mask_text,
1625            );
1626            return Err(ClientError::Server {
1627                status: response.status,
1628                message,
1629            });
1630        }
1631        serde_json::from_value(response.body).map_err(|e| ClientError::Unexpected(e.to_string()))
1632    }
1633}
1634
1635fn to_body(value: &impl serde::Serialize) -> Result<serde_json::Value, ClientError> {
1636    serde_json::to_value(value).map_err(|e| ClientError::Unexpected(e.to_string()))
1637}
1638
1639/// `segment` as one URL path segment: everything but letters, digits and `-._~`
1640/// percent-encoded (a DAG ID may hold `/`, `:` and `#`).
1641#[must_use]
1642pub fn path_segment(segment: &str) -> String {
1643    path(segment)
1644}
1645
1646fn path(segment: &str) -> String {
1647    let mut out = String::with_capacity(segment.len());
1648    for byte in segment.bytes() {
1649        if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
1650            out.push(char::from(byte));
1651        } else {
1652            let _ = write!(out, "%{byte:02X}");
1653        }
1654    }
1655    out
1656}
1657
1658/// What `schedr workers drain` / `resume` asks of a worker.
1659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1660pub enum WorkerAction {
1661    /// Drain it for maintenance.
1662    Drain,
1663    /// Let it take tasks again.
1664    Resume,
1665}
1666
1667/// What `schedr tasks` asks of a task.
1668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1669pub enum TaskAction {
1670    /// Cancel it.
1671    Cancel,
1672    /// Retry it (an `unschedulable` one).
1673    Retry,
1674}
1675
1676/// The query parameter naming a mapped task's instance (`?map_index=N`, or with `&` after
1677/// other parameters); empty for none.
1678fn instance(map_index: Option<u32>, separator: char) -> String {
1679    map_index.map_or_else(String::new, |i| format!("{separator}map_index={i}"))
1680}