Skip to main content

gaman_core/runner/
protocol.rs

1use serde::{Deserialize, Serialize, Serializer};
2
3use super::diagnostics::CommandError;
4use super::selector::EntityFilter;
5use crate::clarifier::Decision;
6use crate::drift::{DriftFinding, VerificationReport};
7use crate::migration_engine::{MigrationArtifact, MigrationMovement};
8use crate::operations::Operation;
9use crate::states::Schema;
10/// Resolved lifecycle command accepted by [`MigrationRunner`].
11#[derive(Debug, Clone, Serialize, Deserialize)]
12#[serde(tag = "command", content = "arguments", rename_all = "snake_case")]
13pub enum Command {
14    /// Generate, inspect, or check a desired schema against migration history.
15    Make(MakeCommand),
16    /// Apply, plan, or check migration movement.
17    Apply(ApplyCommand),
18    /// Return migration application state.
19    Status {
20        reverse: bool,
21        search: Option<String>,
22    },
23    /// Return canonical migration content.
24    Show {
25        id: Option<String>,
26        reverse: bool,
27        search: Option<String>,
28    },
29    /// Render forward or rollback migration SQL.
30    Sql { id: Option<String>, backwards: bool },
31    /// Prepare SQL source segments without executing them.
32    CheckSchema { inputs: Vec<SchemaCheckInput> },
33    /// Reflect selected database namespaces.
34    Inspect {
35        schemas: Vec<String>,
36        /// Root entities selected from catalog inspection.
37        #[serde(default)]
38        filters: Vec<EntityFilter>,
39        /// Legacy single-table selector retained for protocol-v2 consumers.
40        #[serde(default)]
41        table: Option<String>,
42    },
43    /// Compare replayed migration ownership against live inspection.
44    Verify { schemas: Vec<String> },
45    /// Plan or apply one-off repair SQL from verified drift.
46    Repair {
47        schemas: Vec<String>,
48        options: RepairOptions,
49    },
50}
51
52impl Command {
53    /// Returns the clarification decisions already attached to this command.
54    pub fn decisions(&self) -> Option<&[Decision]> {
55        match self {
56            Self::Make(MakeCommand::Generate { decisions, .. })
57            | Self::Make(MakeCommand::Check { decisions, .. }) => Some(decisions),
58            _ => None,
59        }
60    }
61
62    /// Returns a retry command with additional clarification decisions attached.
63    pub fn with_decisions(&self, additional: Vec<Decision>) -> Result<Self, CommandError> {
64        let mut command = self.clone();
65        match &mut command {
66            Self::Make(MakeCommand::Generate { decisions, .. })
67            | Self::Make(MakeCommand::Check { decisions, .. }) => {
68                decisions.extend(additional);
69                Ok(command)
70            }
71            _ => Err(CommandError::Invalid(
72                "this command does not accept clarification decisions".to_string(),
73            )),
74        }
75    }
76}
77
78/// Portable command vocabulary used by textual, WASM, and other hosts.
79pub type CommandRequest = Command;
80
81/// Current version of the portable command request and response protocol.
82pub const COMMAND_PROTOCOL_VERSION: u32 = 6;
83
84/// Versioned portable command request envelope.
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct CommandEnvelope {
87    /// Protocol version used to encode the request.
88    pub protocol_version: u32,
89    /// Resolved lifecycle command.
90    pub command: CommandRequest,
91}
92
93/// Requested migration-generation behavior.
94#[derive(Debug, Clone, Serialize, Deserialize)]
95#[serde(tag = "mode", rename_all = "snake_case")]
96pub enum MakeCommand {
97    /// Generate a normal migration, optionally persisting it.
98    Generate {
99        schema: Schema,
100        name: Option<String>,
101        dry_run: bool,
102        decisions: Vec<Decision>,
103        /// Invocation-scoped root filters; empty preserves complete generation.
104        #[serde(default)]
105        filters: Vec<EntityFilter>,
106    },
107    /// Create a named empty migration.
108    Empty { name: String },
109    /// Create a named merge migration.
110    Merge { name: String },
111    /// Report whether the prepared schema has unapplied changes.
112    Check {
113        schema: Schema,
114        decisions: Vec<Decision>,
115    },
116}
117
118/// Requested migration-application behavior.
119#[derive(Debug, Clone, Serialize, Deserialize)]
120#[serde(tag = "mode", rename_all = "snake_case")]
121pub enum ApplyCommand {
122    /// Execute pending migrations, optionally converging on a target.
123    Execute {
124        target: Option<String>,
125        fake: bool,
126        /// Verifies candidate owned state against the live database before faking.
127        #[serde(default)]
128        fake_verified: bool,
129        /// Namespaces used only by verified fake application.
130        #[serde(default)]
131        schemas: Vec<String>,
132    },
133    /// Return pending migration identifiers without mutation.
134    Plan,
135    /// Fail when pending migrations exist without mutating state.
136    Check,
137}
138
139/// One in-memory SQL source supplied by a host for database preparation.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141pub struct SqlInput {
142    /// Host-visible label used in check results.
143    pub name: String,
144    /// SQL source to segment and prepare.
145    pub sql: String,
146}
147
148/// One host-resolved input participating in SQL schema validation.
149#[derive(Debug, Clone, Serialize, Deserialize)]
150#[serde(tag = "type", rename_all = "snake_case")]
151pub enum SchemaCheckInput {
152    /// SQL source that should be segmented and prepared against the live target.
153    Sql(SqlInput),
154    /// Non-SQL schema input retained in the report without opening a connection.
155    Ignored {
156        /// Host-visible input label.
157        name: String,
158        /// Concise reason the input is not prepared as SQL.
159        reason: String,
160    },
161}
162
163/// Options that control one-off drift repair.
164#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
165pub struct RepairOptions {
166    /// Execute rendered repair SQL instead of returning a dry-run plan.
167    pub apply: bool,
168    /// Allow repair while migrations remain pending.
169    pub allow_pending: bool,
170    /// Apply supported repair operations and retain unsupported findings.
171    pub allow_partial: bool,
172    /// Request SQL-oriented host presentation.
173    pub sql_only: bool,
174}
175
176/// Structured result of one lifecycle command.
177#[derive(Debug, Clone, Serialize)]
178#[serde(tag = "result", content = "value", rename_all = "snake_case")]
179pub enum CommandResult {
180    /// Result of normal, empty, merge, or check migration generation.
181    Make(MakeResult),
182    /// Applied or reverted migration counts.
183    Movement(MigrationMovement),
184    /// Pending migration identifiers.
185    Pending(Vec<String>),
186    /// Migration identifiers with applied flags.
187    Status(Vec<MigrationStatus>),
188    /// Canonical migration YAML artifacts.
189    Show(Vec<MigrationArtifact>),
190    /// Rendered SQL statements.
191    Sql(Vec<String>),
192    /// Per-source database preparation results.
193    SchemaCheck(Vec<SchemaCheckResult>),
194    /// High-fidelity inspected schema.
195    Inspect(Schema),
196    /// Semantic drift report.
197    Verify(VerificationReport),
198    /// One-off repair plan or application report.
199    Repair(RepairReport),
200}
201
202/// Versioned portable command response envelope.
203#[derive(Debug, Clone, Serialize)]
204pub struct CommandResponse {
205    /// Protocol version used to encode the response.
206    pub protocol_version: u32,
207    /// Structured lifecycle result.
208    pub result: CommandResult,
209}
210
211impl CommandResponse {
212    /// Wraps one command result in the current protocol version.
213    pub fn new(result: CommandResult) -> Self {
214        Self {
215            protocol_version: COMMAND_PROTOCOL_VERSION,
216            result,
217        }
218    }
219}
220
221/// Outcome of migration generation with persistence semantics preserved for hosts.
222#[derive(Debug, Clone, Serialize)]
223#[serde(tag = "outcome", content = "migration", rename_all = "snake_case")]
224pub enum MakeResult {
225    /// A generated migration was persisted to the configured migration store.
226    Created(#[serde(serialize_with = "serialize_migration_with_id")] crate::migrations::Migration),
227    /// A generated migration was returned without being persisted.
228    Preview(#[serde(serialize_with = "serialize_migration_with_id")] crate::migrations::Migration),
229    /// Desired schema already matches committed migration history.
230    NoChanges,
231    /// Schema-check mode confirmed that no migration is required.
232    CheckPassed,
233}
234
235/// Serializes a command-result migration with its filename-derived identifier included.
236fn serialize_migration_with_id<S>(
237    migration: &crate::migrations::Migration,
238    serializer: S,
239) -> Result<S::Ok, S::Error>
240where
241    S: Serializer,
242{
243    #[derive(Serialize)]
244    struct MigrationValue<'a> {
245        id: &'a str,
246        dependencies: &'a [String],
247        operations: &'a [Operation],
248        atomic: bool,
249    }
250
251    MigrationValue {
252        id: &migration.id,
253        dependencies: &migration.dependencies,
254        operations: &migration.operations,
255        atomic: migration.atomic,
256    }
257    .serialize(serializer)
258}
259
260/// One migration id and its tracked application state.
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262pub struct MigrationStatus {
263    /// Migration identifier.
264    pub id: String,
265    /// Whether target tracking state marks this migration as applied.
266    pub applied: bool,
267}
268
269/// Database preparation outcome for one supplied SQL source.
270#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
271pub struct SchemaCheckResult {
272    /// Host-visible schema input name.
273    pub name: String,
274    /// Structured validation status for this input.
275    pub status: SchemaCheckStatus,
276}
277
278/// Result category for one schema-check input.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(tag = "status", rename_all = "snake_case")]
281pub enum SchemaCheckStatus {
282    /// SQL source was segmented and each segment was prepared independently.
283    Checked {
284        /// Number of statements prepared successfully.
285        passed: usize,
286        /// Segmentation or statement preparation failures.
287        failures: Vec<SchemaCheckFailure>,
288    },
289    /// Input is not SQL and was intentionally excluded from live preparation.
290    Ignored {
291        /// Host-provided explanation for the exclusion.
292        reason: String,
293    },
294}
295
296/// One structured SQL schema validation failure.
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(tag = "type", rename_all = "snake_case")]
299pub enum SchemaCheckFailure {
300    /// SQL source could not be segmented safely.
301    Segmentation {
302        /// One-based source line when available.
303        line: Option<usize>,
304        /// One-based source column when available.
305        column: Option<usize>,
306        /// Segmentation diagnostic.
307        message: String,
308    },
309    /// One segmented statement could not be prepared by the target database.
310    Statement {
311        /// One-based statement ordinal in the input.
312        ordinal: usize,
313        /// One-based source line where the segment begins.
314        line: usize,
315        /// One-based source column where the segment begins.
316        column: usize,
317        /// Driver-provided preparation diagnostic.
318        message: String,
319    },
320}
321
322/// Result of planning or applying one-off repair SQL.
323#[derive(Debug, Clone, Serialize)]
324pub struct RepairReport {
325    /// Verification report before a dry-run or after an applied repair.
326    pub verification: VerificationReport,
327    /// Repair operations selected from verified findings.
328    pub operations: Vec<Operation>,
329    /// SQL rendered from repair operations.
330    pub sql: Vec<String>,
331    /// Whether SQL was applied to the target database.
332    pub applied: bool,
333    /// Findings that were intentionally left for manual handling.
334    pub skipped_findings: Vec<DriftFinding>,
335}