1use std::path::PathBuf;
8use std::sync::Arc;
9use std::time::Duration;
10
11use schedr_model::commands::{ConnectionReport, SecretReport, SecretState};
12use schedr_model::connection::Registry;
13use schedr_model::runner::{ErrorSummary, RunInfo};
14use serde_json::json;
15
16use crate::attempt::AttemptSpec;
17use crate::secrets::{AttemptSecrets, SecretError, SecretStores};
18
19#[cfg(test)]
20mod tests;
21
22pub const CANCEL_GRACE: Duration = Duration::from_secs(5);
25
26#[derive(Debug, Clone)]
28pub struct ConnectionJob {
29 pub root: String,
31 pub code_dir: Option<PathBuf>,
33 pub registry: Arc<Registry>,
35 pub test: Option<(String, Duration)>,
37 pub cancel_grace: Duration,
39 pub attempt_id: String,
41 pub deadline: tokio::time::Instant,
43}
44
45pub async fn check(stores: &Arc<SecretStores>, registry: &Arc<Registry>) -> Vec<ConnectionReport> {
48 let mut reports = Vec::new();
49 for (name, why) in ®istry.refused {
50 reports.push(failed(name, why.clone()));
51 }
52 for (name, def) in ®istry.connections {
53 let mut secrets = Vec::new();
54 for secret in def.secrets() {
55 let (state, message) = match stores.fetch(secret).await {
56 Ok(_) => (SecretState::Present, None),
57 Err(SecretError::NotFound(_))
59 if secret.default.is_some() && stores.storage_of(secret).is_ok() =>
60 {
61 (SecretState::Default, None)
62 }
63 Err(SecretError::NotFound(_)) => (SecretState::Missing, None),
64 Err(SecretError::Denied(why)) => (SecretState::Denied, Some(why)),
65 Err(SecretError::Unavailable(why)) => (SecretState::Unavailable, Some(why)),
66 };
67 secrets.push(SecretReport {
68 secret: secret.to_string(),
69 state,
70 message,
71 });
72 }
73 let attempt = AttemptSecrets::none(Arc::clone(stores))
74 .with_connections(Arc::clone(registry), vec![name.clone()]);
75 let error = attempt
76 .connection(name)
77 .await
78 .err()
79 .map(|e| attempt.mask.mask_text(&e.to_string()));
80 let all_there = secrets
82 .iter()
83 .all(|s| matches!(s.state, SecretState::Present | SecretState::Default));
84 let error = error.or_else(|| {
85 (!all_there).then(|| format!("connection `{name}`: a secret it names isn't there"))
86 });
87 reports.push(ConnectionReport {
88 name: name.clone(),
89 ok: error.is_none(),
90 secrets,
91 error,
92 duration_ms: None,
93 });
94 }
95 reports
96}
97
98pub fn test_spec(
105 job: &ConnectionJob,
106 name: &str,
107 timeout: Duration,
108 attempt_id: String,
109) -> Result<AttemptSpec, String> {
110 if let Some(why) = job.registry.refused.get(name) {
111 return Err(why.clone());
112 }
113 let Some(path) = job.registry.files.get(name) else {
114 return Err(format!(
115 "connection `{name}`: no file of root `{}` defines it",
116 job.root
117 ));
118 };
119 let inside = std::path::Path::new(path)
121 .components()
122 .all(|c| matches!(c, std::path::Component::Normal(_)));
123 if path.is_empty() || !inside {
124 return Err(format!(
125 "connection `{name}`: `{path}` isn't a path inside root `{}`",
126 job.root
127 ));
128 }
129 let timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
130 let task = serde_json::from_value(json!({
132 "id": name,
133 "kind": "python",
134 "connections": [name],
135 "settings": {"retries": 0, "retry_delay_ms": 0, "timeout_ms": timeout_ms,
136 "queue": "default", "max_output_size": 65_536, "preload": false,
137 "fresh_process": false},
138 "output_type": {"type": "none"},
139 }))
140 .map_err(|e| format!("connection `{name}` can't be tested by this name: {e}"))?;
141 let now = jiff::Timestamp::now();
142 Ok(AttemptSpec {
143 attempt_id,
144 task,
145 dag_root: job.root.clone(),
146 dag_path: path.clone(),
147 run: RunInfo {
148 dag_id: String::new(),
149 run_id: String::new(),
150 kind: schedr_model::RunKind::Manual,
151 planned_for: now,
152 since: now,
153 try_number: 1,
154 map_index: None,
155 params: json!({}),
156 event: None,
157 first_started: None,
158 },
159 inputs: std::collections::BTreeMap::new(),
160 outcomes: std::collections::BTreeMap::new(),
161 cancel_grace: job.cancel_grace,
162 secrets: std::collections::BTreeMap::new(),
163 mask: crate::mask::Mask::default(),
164 code_dir: job.code_dir.clone(),
165 script_dir: None,
166 root_copies: std::collections::BTreeMap::new(),
167 connections: Arc::clone(&job.registry),
168 trigger: None,
169 connection_env: std::collections::BTreeMap::new(),
170 connection_test: Some(name.to_owned()),
171 cleanup_handles: None,
172 moved_cleanup: false,
173 journal: None,
174 handle_sink: None,
175 api: None,
176 cleanup_gate: None,
177 })
178}
179
180#[must_use]
182pub fn test_report(
183 name: &str,
184 finished: &schedr_proto::pb::Finished,
185 took: Duration,
186) -> ConnectionReport {
187 use schedr_proto::pb::AttemptStatus;
188 let status = AttemptStatus::try_from(finished.status).unwrap_or(AttemptStatus::Unspecified);
189 let summary: Option<ErrorSummary> = serde_json::from_slice(&finished.error_summary_json).ok();
190 let error = match status {
191 AttemptStatus::Success => None,
192 AttemptStatus::TimedOut => Some(format!(
193 "stopped after its timeout ({:.1} s)",
194 took.as_secs_f64()
195 )),
196 _ => Some(
197 summary
198 .map(|e| {
199 if e.exception.is_empty() {
200 e.message
201 } else {
202 format!("{}: {}", e.exception, e.message)
203 }
204 })
205 .filter(|m| !m.is_empty())
206 .unwrap_or_else(|| format!("the test ended {}", status.as_str_name())),
207 ),
208 };
209 ConnectionReport {
210 name: name.to_owned(),
211 ok: error.is_none(),
212 secrets: Vec::new(),
213 error,
214 duration_ms: Some(u64::try_from(took.as_millis()).unwrap_or(u64::MAX)),
215 }
216}
217
218#[must_use]
220pub fn out_of_time(what: &str) -> String {
221 format!("its time was up during its {what}")
222}
223
224#[must_use]
226pub fn failed(name: &str, why: String) -> ConnectionReport {
227 ConnectionReport {
228 name: name.to_owned(),
229 ok: false,
230 secrets: Vec::new(),
231 error: Some(why),
232 duration_ms: None,
233 }
234}