1use std::error::Error as StdError;
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6use super::adapters::InspectionError;
7use super::protocol::COMMAND_PROTOCOL_VERSION;
8use crate::clarifier::Clarification;
9use crate::graphs::GraphError;
10use crate::migration_engine::{EngineError, ExecutorError, StoreError, TrackingError};
11use crate::offline_planner::OfflineError;
12use crate::redact_diagnostic_text;
13use crate::sql_plan::SqlPlanError;
14use crate::states::ReplayError;
15#[derive(Debug, Error)]
17pub enum CommandError {
18 #[error("unsupported command protocol version {observed}; expected {expected}")]
20 UnsupportedProtocolVersion {
21 expected: u32,
23 observed: u32,
25 },
26 #[error("migration generation needs clarification input")]
28 NeedsInput(Vec<Clarification>),
29 #[error(transparent)]
31 Migration(EngineError),
32 #[error(transparent)]
34 Store(StoreError),
35 #[error(transparent)]
37 Tracking(TrackingError),
38 #[error(transparent)]
40 Execution(ExecutorError),
41 #[error("SQL parsing failed: {0}")]
43 Parse(String),
44 #[error(transparent)]
46 Inspection(#[from] InspectionError),
47 #[error("invalid command: {0}")]
49 Invalid(String),
50}
51
52impl From<EngineError> for CommandError {
53 fn from(error: EngineError) -> Self {
55 match error {
56 EngineError::NeedsInput(clarifications) => Self::NeedsInput(clarifications),
57 EngineError::Store(error) => Self::Store(error),
58 EngineError::Tracking(error) => Self::Tracking(error),
59 EngineError::Executor(error) => Self::Execution(error),
60 error => Self::Migration(error),
61 }
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum DiagnosticCode {
69 UnsupportedProtocolVersion,
71 ClarificationRequired,
73 InvalidCommand,
75 MigrationStoreFailed,
77 TrackingFailed,
79 ExecutionFailed,
81 InspectionFailed,
83 MigrationFailed,
85 ParseFailed,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct CommandDiagnostic {
92 pub code: DiagnosticCode,
94 pub summary: String,
96 pub hint: Option<String>,
98 pub details: Vec<String>,
100 pub retryable: bool,
102}
103
104#[derive(Debug, Clone, Serialize)]
106pub struct CommandFailure {
107 pub protocol_version: u32,
109 pub diagnostic: CommandDiagnostic,
111 pub clarifications: Vec<Clarification>,
113}
114
115impl CommandError {
116 pub fn diagnostic(&self) -> CommandDiagnostic {
118 match self {
119 Self::UnsupportedProtocolVersion { expected, observed } => command_diagnostic(
120 DiagnosticCode::UnsupportedProtocolVersion,
121 format!("unsupported command protocol version {observed}; expected {expected}"),
122 Some("update the host binding and retry the command".to_string()),
123 Vec::new(),
124 false,
125 ),
126 Self::NeedsInput(_) | Self::Migration(EngineError::NeedsInput(_)) => {
127 command_diagnostic(
128 DiagnosticCode::ClarificationRequired,
129 "migration generation needs clarification input".to_string(),
130 Some("supply decisions and run the command again".to_string()),
131 Vec::new(),
132 true,
133 )
134 }
135 Self::Invalid(message) => command_diagnostic(
136 DiagnosticCode::InvalidCommand,
137 message.clone(),
138 None,
139 Vec::new(),
140 false,
141 ),
142 Self::Inspection(error) => inspection_diagnostic(error),
143 Self::Store(error) => adapter_diagnostic(
144 DiagnosticCode::MigrationStoreFailed,
145 "migration storage failed",
146 error,
147 "check the migration directory and resolve any conflicting migration id",
148 ),
149 Self::Tracking(error) => adapter_diagnostic(
150 DiagnosticCode::TrackingFailed,
151 "migration tracking failed",
152 error,
153 "check database connectivity, tracking-table permissions, and migration lock state",
154 ),
155 Self::Execution(error) => adapter_diagnostic(
156 DiagnosticCode::ExecutionFailed,
157 "database operation failed",
158 error,
159 "check database connectivity, permissions, and the reported database error",
160 ),
161 Self::Parse(error) => diagnostic_with_detail(
162 DiagnosticCode::ParseFailed,
163 "SQL parsing failed",
164 error,
165 "correct the SQL input and retry the command",
166 false,
167 ),
168 Self::Migration(error) => migration_diagnostic(error),
169 }
170 }
171
172 pub fn verbose_causes(&self) -> Vec<String> {
174 let mut causes = Vec::new();
175 let mut current: &(dyn StdError + 'static) = self;
176 while let Some(source) = current.source() {
177 let rendered = redact_diagnostic_text(&source.to_string());
178 if causes.last() != Some(&rendered) {
179 causes.push(rendered);
180 }
181 current = source;
182 }
183 if causes.is_empty() {
184 causes.push(redact_diagnostic_text(&self.to_string()));
185 }
186 causes
187 }
188
189 pub fn failure(&self) -> CommandFailure {
191 let clarifications = match self {
192 Self::NeedsInput(clarifications)
193 | Self::Migration(EngineError::NeedsInput(clarifications)) => clarifications.clone(),
194 _ => Vec::new(),
195 };
196 CommandFailure {
197 protocol_version: COMMAND_PROTOCOL_VERSION,
198 diagnostic: self.diagnostic(),
199 clarifications,
200 }
201 }
202}
203
204fn migration_diagnostic(error: &EngineError) -> CommandDiagnostic {
206 match error {
207 EngineError::MigrationExecution {
208 migration,
209 direction,
210 statement_ordinal,
211 statement,
212 source,
213 } => execution_diagnostic(migration, direction, *statement_ordinal, statement, source),
214 EngineError::Graph(error) => graph_diagnostic(error),
215 EngineError::Offline(error) => offline_diagnostic(error),
216 EngineError::SqlPlan(error) => sql_plan_diagnostic(error),
217 EngineError::Config(message) => diagnostic_with_detail(
218 DiagnosticCode::MigrationFailed,
219 "migration command cannot run",
220 message,
221 "correct the migration configuration and retry the command",
222 false,
223 ),
224 EngineError::NeedsInput(_) => command_diagnostic(
225 DiagnosticCode::ClarificationRequired,
226 "migration generation needs clarification input".to_string(),
227 Some("supply decisions and run the command again".to_string()),
228 Vec::new(),
229 true,
230 ),
231 EngineError::Store(error) => adapter_diagnostic(
232 DiagnosticCode::MigrationStoreFailed,
233 "migration storage failed",
234 error,
235 "check the migration directory and resolve any conflicting migration id",
236 ),
237 EngineError::Tracking(error) => adapter_diagnostic(
238 DiagnosticCode::TrackingFailed,
239 "migration tracking failed",
240 error,
241 "check database connectivity, tracking-table permissions, and migration lock state",
242 ),
243 EngineError::Executor(error) => adapter_diagnostic(
244 DiagnosticCode::ExecutionFailed,
245 "database operation failed",
246 error,
247 "check database connectivity, permissions, and the reported database error",
248 ),
249 }
250}
251
252fn execution_diagnostic(
254 migration: &str,
255 direction: &str,
256 statement_ordinal: usize,
257 statement: &crate::migration_engine::execution_diagnostic::StatementDiagnostic,
258 source: &ExecutorError,
259) -> CommandDiagnostic {
260 let mut details = vec![
261 format!("migration: {migration}"),
262 format!(
263 "{direction} statement {statement_ordinal}: {}",
264 statement.signature
265 ),
266 database_failure_detail(source),
267 ];
268 if let Some(location) = &statement.location {
269 details.push(format!(
270 "at {} line {}, column {}",
271 location.source.label(),
272 location.line,
273 location.column
274 ));
275 details.push(format!(" {}", location.excerpt));
276 details.push(format!(" {}^", " ".repeat(location.caret_offset)));
277 }
278 command_diagnostic(
279 DiagnosticCode::ExecutionFailed,
280 "database operation failed".to_string(),
281 Some(format!(
282 "inspect migration '{migration}' with `gaman show {migration}`"
283 )),
284 details,
285 false,
286 )
287}
288
289fn database_failure_detail(error: &ExecutorError) -> String {
291 match error.database_failure() {
292 Some(failure) => match &failure.code {
293 Some(code) => format!("execute failed [{code}]: {}", failure.message),
294 None => format!("execute failed: {}", failure.message),
295 },
296 None => error.to_string(),
297 }
298}
299
300fn offline_diagnostic(error: &OfflineError) -> CommandDiagnostic {
302 match error {
303 OfflineError::Graph(error) => graph_diagnostic(error),
304 OfflineError::Replay(error) => replay_diagnostic(error),
305 OfflineError::SqlPlan(error) => sql_plan_diagnostic(error),
306 OfflineError::Schema(message) => diagnostic_with_detail(
307 DiagnosticCode::MigrationFailed,
308 "schema validation failed during migration planning",
309 message,
310 "correct the schema or migration history and retry the command",
311 false,
312 ),
313 OfflineError::NeedsInput(_) => command_diagnostic(
314 DiagnosticCode::ClarificationRequired,
315 "migration generation needs clarification input".to_string(),
316 Some("supply decisions and run the command again".to_string()),
317 Vec::new(),
318 true,
319 ),
320 _ => diagnostic_with_detail(
321 DiagnosticCode::MigrationFailed,
322 "migration planning failed",
323 error,
324 "correct the reported schema or migration definition and retry the command",
325 false,
326 ),
327 }
328}
329
330fn sql_plan_diagnostic(error: &SqlPlanError) -> CommandDiagnostic {
332 match error {
333 SqlPlanError::Graph(error) => graph_diagnostic(error),
334 SqlPlanError::Replay(error) => replay_diagnostic(error),
335 _ => diagnostic_with_detail(
336 DiagnosticCode::MigrationFailed,
337 "migration SQL planning failed",
338 error,
339 "correct the reported migration or use explicit SQL for unsupported changes",
340 false,
341 ),
342 }
343}
344
345fn replay_diagnostic(error: &ReplayError) -> CommandDiagnostic {
347 match error {
348 ReplayError::WithContext {
349 migration,
350 op_num,
351 operation,
352 inner,
353 } => command_diagnostic(
354 DiagnosticCode::MigrationFailed,
355 format!("cannot replay migration '{migration}'"),
356 Some(replay_hint(inner)),
357 vec![format!("operation {op_num} ({operation}): {}", inner)],
358 false,
359 ),
360 _ => diagnostic_with_detail(
361 DiagnosticCode::MigrationFailed,
362 "cannot replay migration history",
363 error,
364 "correct the reported migration definition and retry the command",
365 false,
366 ),
367 }
368}
369
370fn replay_hint(error: &ReplayError) -> String {
371 match error {
372 ReplayError::InvalidOpaqueCreate { .. } => {
373 "replace the opaque source with one plain CREATE statement; Gaman owns existence and replacement"
374 .to_string()
375 }
376 _ => "correct the migration order or restore the missing prerequisite migration".to_string(),
377 }
378}
379
380fn graph_diagnostic(error: &GraphError) -> CommandDiagnostic {
382 diagnostic_with_detail(
383 DiagnosticCode::MigrationFailed,
384 "migration graph is invalid",
385 error,
386 graph_hint(error),
387 false,
388 )
389}
390
391fn graph_hint(error: &GraphError) -> &'static str {
393 match error {
394 GraphError::DuplicateId(_) => "rename or remove the duplicate migration id",
395 GraphError::CycleDetected => "remove the dependency cycle between migrations",
396 GraphError::Conflict => "run make --merge after resolving the competing migration heads",
397 GraphError::UnknownDependency { .. } => {
398 "restore the referenced dependency or correct the migration dependencies"
399 }
400 GraphError::InvalidId(_) => "rename the migration using a valid lowercase id",
401 GraphError::UnknownId(_) | GraphError::AmbiguousId { .. } => {
402 "use one exact migration id or an unambiguous prefix"
403 }
404 GraphError::Empty => "create a migration before requesting this operation",
405 }
406}
407
408fn inspection_diagnostic(error: &InspectionError) -> CommandDiagnostic {
410 diagnostic_with_detail(
411 DiagnosticCode::InspectionFailed,
412 "database inspection failed",
413 error,
414 "check database connectivity, selected namespaces, and catalog permissions",
415 true,
416 )
417}
418
419fn adapter_diagnostic(
421 code: DiagnosticCode,
422 summary: &str,
423 error: &impl std::fmt::Display,
424 hint: &str,
425) -> CommandDiagnostic {
426 diagnostic_with_detail(code, summary, error, hint, false)
427}
428
429fn diagnostic_with_detail(
431 code: DiagnosticCode,
432 summary: &str,
433 detail: &impl std::fmt::Display,
434 hint: &str,
435 retryable: bool,
436) -> CommandDiagnostic {
437 command_diagnostic(
438 code,
439 summary.to_string(),
440 Some(hint.to_string()),
441 vec![detail.to_string()],
442 retryable,
443 )
444}
445
446fn command_diagnostic(
448 code: DiagnosticCode,
449 summary: String,
450 hint: Option<String>,
451 details: Vec<String>,
452 retryable: bool,
453) -> CommandDiagnostic {
454 CommandDiagnostic {
455 code,
456 summary: redact_diagnostic_text(&summary),
457 hint: hint.map(|value| redact_diagnostic_text(&value)),
458 details: details
459 .into_iter()
460 .map(|value| redact_diagnostic_text(&value))
461 .collect(),
462 retryable,
463 }
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469
470 #[test]
472 fn protocol_mismatch_is_structured() {
473 let failure = CommandError::UnsupportedProtocolVersion {
474 expected: COMMAND_PROTOCOL_VERSION,
475 observed: 1,
476 }
477 .failure();
478
479 assert_eq!(failure.protocol_version, 6);
480 assert_eq!(
481 failure.diagnostic.code,
482 DiagnosticCode::UnsupportedProtocolVersion
483 );
484 assert!(!failure.diagnostic.retryable);
485 }
486
487 #[test]
489 fn replay_failure_is_actionable() {
490 let error = CommandError::Migration(EngineError::Offline(OfflineError::Replay(
491 ReplayError::WithContext {
492 migration: "0002_add_posts".to_string(),
493 op_num: 2,
494 operation: "add foreign key posts.author_id".to_string(),
495 inner: Box::new(ReplayError::TableNotFound("posts".to_string())),
496 },
497 )));
498
499 let diagnostic = error.diagnostic();
500 assert_eq!(diagnostic.code, DiagnosticCode::MigrationFailed);
501 assert_eq!(
502 diagnostic.summary,
503 "cannot replay migration '0002_add_posts'"
504 );
505 assert_eq!(
506 diagnostic.details,
507 ["operation 2 (add foreign key posts.author_id): table 'posts' not found"]
508 );
509 assert!(
510 diagnostic
511 .hint
512 .as_deref()
513 .is_some_and(|hint| hint.contains("migration order"))
514 );
515 }
516
517 #[test]
519 fn opaque_create_replay_failure_has_specific_hint() {
520 let error = CommandError::Migration(EngineError::Offline(OfflineError::Replay(
521 ReplayError::WithContext {
522 migration: "0003_active_users".to_string(),
523 op_num: 1,
524 operation: "create view active_users".to_string(),
525 inner: Box::new(ReplayError::InvalidOpaqueCreate {
526 entity: "active_users".to_string(),
527 reason: "CREATE OR REPLACE is not accepted; Gaman owns replacement".to_string(),
528 }),
529 },
530 )));
531
532 let diagnostic = error.diagnostic();
533 assert!(diagnostic.details[0].contains("CREATE OR REPLACE"));
534 assert!(
535 diagnostic
536 .hint
537 .as_deref()
538 .is_some_and(|hint| hint.contains("plain CREATE"))
539 );
540 }
541
542 #[test]
544 fn diagnostics_redact_sensitive_adapter_text() {
545 let error = CommandError::Execution(ExecutorError::Connect(
546 "postgres://gaman:secret@localhost/app password=hunter2 token=abc".to_string(),
547 ));
548
549 let diagnostic = error.diagnostic();
550 let detail = &diagnostic.details[0];
551 assert!(!detail.contains("secret"));
552 assert!(!detail.contains("hunter2"));
553 assert!(!detail.contains("abc"));
554 assert!(detail.contains("gaman:***@localhost"));
555 let failure = serde_json::to_string(&error.failure()).expect("serialize command failure");
556 assert!(!failure.contains("secret"));
557 assert!(!error.verbose_causes().join(" ").contains("hunter2"));
558 }
559
560 #[test]
562 fn migration_execution_failure_is_compact_and_actionable() {
563 let error = CommandError::Migration(EngineError::MigrationExecution {
564 migration: "0012_reports".to_string(),
565 direction: "apply",
566 statement_ordinal: 1,
567 statement: Box::new(crate::migration_engine::execution_diagnostic::StatementDiagnostic {
568 signature: "CREATE OR REPLACE FUNCTION dynrs_daily_report()".to_string(),
569 location: Some(
570 crate::migration_engine::execution_diagnostic::StatementLocation {
571 source: crate::migration_engine::execution_diagnostic::StatementLocationSource::Internal,
572 line: 18,
573 column: 9,
574 excerpt: "SELECT session_type_provider_tip".to_string(),
575 caret_offset: 8,
576 },
577 ),
578 }),
579 source: Box::new(ExecutorError::ExecuteDatabase(
580 crate::migration_engine::DatabaseFailure::message(
581 "column reference is ambiguous",
582 )
583 .with_code("42702"),
584 )),
585 });
586 let diagnostic = error.diagnostic();
587 assert_eq!(diagnostic.summary, "database operation failed");
588 assert!(
589 diagnostic
590 .details
591 .iter()
592 .any(|detail| detail == "migration: 0012_reports")
593 );
594 assert!(
595 diagnostic.details.iter().any(|detail| {
596 detail == "execute failed [42702]: column reference is ambiguous"
597 })
598 );
599 assert!(
600 diagnostic
601 .hint
602 .as_deref()
603 .is_some_and(|hint| hint.contains("gaman show 0012_reports"))
604 );
605 }
606}