1use 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
23pub 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
34pub const CLIENT_VERSION_HEADER: &str = "schedr-client-version";
36
37pub const POLL_INTERVAL: Duration = Duration::from_millis(500);
39
40pub const WAIT_TIMEOUT: Duration = Duration::from_secs(30);
42
43pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
47
48pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Method {
54 Get,
56 Post,
58}
59
60#[derive(Debug, Clone, PartialEq)]
62pub struct ApiRequest {
63 pub method: Method,
65 pub path: String,
67 pub body: Option<serde_json::Value>,
69 pub key: Option<String>,
71}
72
73#[derive(Debug, Clone, PartialEq)]
75pub struct ApiResponse {
76 pub status: u16,
78 pub body: serde_json::Value,
80}
81
82#[derive(Debug, thiserror::Error)]
84pub enum ClientError {
85 #[error("can't reach the schedr server at {server}: {reason}")]
87 Connect {
88 server: String,
90 reason: String,
92 },
93 #[error("can't reach the schedr server at {server}: {reason}")]
95 Unreachable {
96 server: String,
98 reason: String,
100 },
101 #[error("{message}")]
103 Server {
104 status: u16,
106 message: String,
108 },
109 #[error("unexpected answer from the server: {0}")]
111 Unexpected(String),
112 #[error("rejected: {0}")]
114 Rejected(String),
115 #[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 reason: String,
125 },
126 #[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 command_id: String,
134 },
135}
136
137pub trait Transport: Sync {
139 fn send(
141 &self,
142 request: ApiRequest,
143 ) -> impl Future<Output = Result<ApiResponse, ClientError>> + Send;
144
145 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 pub static USER: String;
160}
161
162pub 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 pub static COMMAND_KEY: String;
179}
180
181pub async fn with_command_key<F: Future>(key: String, send: F) -> F::Output {
183 COMMAND_KEY.scope(key, send).await
184}
185
186pub const COMMAND_TRIES: u32 = 3;
188
189#[must_use]
191pub fn new_command_key() -> String {
192 uuid::Uuid::now_v7().to_string()
193}
194
195#[must_use]
197pub fn current_user() -> Option<String> {
198 USER.try_with(Clone::clone).ok()
199}
200
201pub const STREAM_TIMEOUT: Duration = Duration::from_hours(24);
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub enum Auth {
207 None,
209 Bearer(String),
211 Basic {
213 user: String,
215 password: Option<String>,
217 },
218}
219
220impl Auth {
221 #[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
235type CachedClient = std::sync::Arc<std::sync::Mutex<(u64, reqwest::Client)>>;
237
238#[derive(Debug, Clone)]
240pub struct HttpTransport {
241 client: reqwest::Client,
242 server: String,
243 auth: Auth,
244 ui_token: Option<schedr_api::auth::UiToken>,
246 tls: Option<(schedr_tls::Tls, CachedClient)>,
249 timeouts: Timeouts,
251}
252
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub struct Timeouts {
257 pub connect: Duration,
259 pub request: Duration,
261 pub command_wait: Duration,
263}
264
265impl Default for Timeouts {
266 fn default() -> Self {
268 Self {
269 connect: CONNECT_TIMEOUT,
270 request: REQUEST_TIMEOUT,
271 command_wait: WAIT_TIMEOUT,
272 }
273 }
274}
275
276fn 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 #[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 #[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 #[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 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 #[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 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 #[must_use]
386 pub fn server(&self) -> &str {
387 &self.server
388 }
389
390 #[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 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 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 if sender.send(chunk).await.is_err() || failed {
469 return;
470 }
471 }
472 });
473 Ok(chunks)
474 }
475}
476
477fn 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
487fn 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
509fn 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#[derive(Debug, Clone)]
523pub struct RouterTransport {
524 app: axum::Router,
525}
526
527impl RouterTransport {
528 #[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 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
632fn 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#[derive(Debug, Clone)]
647pub struct Client<T> {
648 transport: T,
649 poll: Duration,
650 timeout: Duration,
651}
652
653impl<T: Transport> Client<T> {
654 pub const fn new(transport: T, poll: Duration, timeout: Duration) -> Self {
656 Self {
657 transport,
658 poll,
659 timeout,
660 }
661 }
662
663 pub const fn transport(&self) -> &T {
665 &self.transport
666 }
667
668 pub const fn poll(&self) -> Duration {
670 self.poll
671 }
672
673 pub async fn workers(&self) -> Result<WorkerList, ClientError> {
679 self.call(Method::Get, "/api/v1/workers".to_owned(), None)
680 .await
681 }
682
683 pub async fn triggers(&self) -> Result<TriggerList, ClientError> {
689 self.call(Method::Get, "/api/v1/triggers".to_owned(), None)
690 .await
691 }
692
693 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 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 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 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 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 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 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 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 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 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 pub async fn deployment(&self) -> Result<DeploymentView, ClientError> {
852 self.call(Method::Get, "/api/v1/deployment".to_owned(), None)
853 .await
854 }
855
856 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 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 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 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 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 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 pub async fn connections(&self) -> Result<ConnectionList, ClientError> {
953 self.call(Method::Get, "/api/v1/connections".to_owned(), None)
954 .await
955 }
956
957 pub async fn dags(&self) -> Result<DagList, ClientError> {
963 self.call(Method::Get, "/api/v1/dags".to_owned(), None)
964 .await
965 }
966
967 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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(¤t.command_id).await?;
1428 }
1429 }
1430
1431 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 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 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 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 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 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 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 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(¤t.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 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1660pub enum WorkerAction {
1661 Drain,
1663 Resume,
1665}
1666
1667#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1669pub enum TaskAction {
1670 Cancel,
1672 Retry,
1674}
1675
1676fn instance(map_index: Option<u32>, separator: char) -> String {
1679 map_index.map_or_else(String::new, |i| format!("{separator}map_index={i}"))
1680}