datacraft-core 0.1.2

Headless domain model, command bus and application state for DataCraft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Journaled write profile (step 11.11, item M2).
//!
//! A write batch is previewed as a diff, applied only after the caller
//! confirms the token, and carries the inverse operations for a rollback.
//! The profile restricts the batch to qualified field families — anything
//! else is refused precisely instead of being guessed (BACKLOG M2).
//! Backends apply the batch through
//! [`StoragePort::write_row_ops`](crate::port::StoragePort::write_row_ops)
//! ([`crate::port::StoragePort`]), which is atomic on the Jet backend.

use serde::{Deserialize, Serialize};

use crate::core::failed;
use crate::event::Event;
use crate::failure::FailureCode;
use crate::port::{DriverCapabilities, RowRange, RowWriteOp};
use crate::schema::{AutoKind, BinaryKind, FieldKind, FieldValue, TableDef};

/// One row operation of a journaled batch. Indices address the row set as
/// it evolves through the batch (sequential application).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum WriteOp {
    /// Appends a row (`Null` on an AutoNumber field = engine-assigned).
    Insert {
        /// Full positional value list.
        values: Vec<FieldValue>,
    },
    /// Replaces the row at `row`.
    Update {
        /// Zero-based live-row index in the evolving row set.
        row: usize,
        /// Full positional value list.
        values: Vec<FieldValue>,
    },
    /// Removes the row at `row`.
    Delete {
        /// Zero-based live-row index in the evolving row set.
        row: usize,
    },
}

/// Kind of one previewed change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChangeKind {
    /// A row is appended.
    Insert,
    /// A row is replaced.
    Update,
    /// A row is removed.
    Delete,
}

/// One diff entry of a previewed batch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RowChange {
    /// Operation kind.
    pub kind: ChangeKind,
    /// Row index (insert position, update/delete target).
    pub row: Option<usize>,
    /// Values before the change (update/delete).
    pub before: Option<Vec<FieldValue>>,
    /// Values after the change (insert/update).
    pub after: Option<Vec<FieldValue>>,
}

/// Qualification of a table for journaled writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct WriteProfile {
    /// True when every column is fixed-width (updates stay in place).
    pub fixed_width: bool,
}

/// Journal stored between preview and apply.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PendingWrite {
    /// Canonical table name.
    pub table: String,
    /// Confirmation token of this journal.
    pub token: u64,
    /// The previewed operations.
    pub ops: Vec<WriteOp>,
    /// The previewed diff (apply requires it to still match).
    pub changes: Vec<RowChange>,
}

/// Applied journal kept for rollback.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AppliedWrite {
    /// Canonical table name.
    pub table: String,
    /// Token of the applied journal.
    pub token: u64,
    /// Inverse operations, in reverse application order.
    pub rollback: Vec<WriteOp>,
}

/// The table's write profile: qualified families only, with the precise
/// reason for every refusal.
pub fn write_profile(table: &TableDef) -> Result<WriteProfile, String> {
    for field in &table.fields {
        match &field.kind {
            FieldKind::Binary(BinaryKind::Attachment) => {
                return Err(format!(
                    "table {:?}: column {:?} (attachment) is outside the write profile — \
                     complex values are not qualified yet (BACKLOG M4)",
                    table.name, field.name
                ));
            }
            FieldKind::AutoNumber(AutoKind::ReplicationId) => {
                return Err(format!(
                    "table {:?}: column {:?} (GUID AutoNumber) is outside the write profile — \
                     the counter is not maintained yet (BACKLOG M8)",
                    table.name, field.name
                ));
            }
            _ => {}
        }
    }
    Ok(WriteProfile {
        fixed_width: table.fields.iter().all(|field| is_fixed_width(&field.kind)),
    })
}

fn is_fixed_width(kind: &FieldKind) -> bool {
    !matches!(
        kind,
        FieldKind::Text { .. } | FieldKind::Memo | FieldKind::Binary(_)
    )
}

/// Simulates the batch over `rows` and returns the **prepared** operations
/// (defaults filled, calculated computed, rules enforced) plus the diff.
/// Read-only; the caller applies only after confirmation — the prepared
/// batch is the contract, so apply writes exactly what the preview showed.
pub fn preview(
    table: &TableDef,
    rows: &[Vec<FieldValue>],
    ops: &[WriteOp],
) -> Result<(Vec<WriteOp>, Vec<RowChange>), String> {
    write_profile(table)?;
    let mut state = rows.to_vec();
    let mut prepared = Vec::with_capacity(ops.len());
    let mut changes = Vec::with_capacity(ops.len());
    for op in ops {
        match op {
            WriteOp::Insert { values } => {
                let values = crate::field_expressions::prepare_insert(table, values)?;
                let row = state.len();
                state.push(values.clone());
                changes.push(RowChange {
                    kind: ChangeKind::Insert,
                    row: Some(row),
                    before: None,
                    after: Some(values.clone()),
                });
                prepared.push(WriteOp::Insert { values });
            }
            WriteOp::Update { row, values } => {
                let Some(current) = state.get(*row) else {
                    return Err(out_of_range(table, *row, state.len()));
                };
                let values = crate::field_expressions::prepare_update(table, current, values)?;
                let before = state[*row].clone();
                state[*row] = values.clone();
                changes.push(RowChange {
                    kind: ChangeKind::Update,
                    row: Some(*row),
                    before: Some(before),
                    after: Some(values.clone()),
                });
                prepared.push(WriteOp::Update { row: *row, values });
            }
            WriteOp::Delete { row } => {
                if *row >= state.len() {
                    return Err(out_of_range(table, *row, state.len()));
                }
                let before = state.remove(*row);
                changes.push(RowChange {
                    kind: ChangeKind::Delete,
                    row: Some(*row),
                    before: Some(before),
                    after: None,
                });
                prepared.push(op.clone());
            }
        }
    }
    Ok((prepared, changes))
}

/// The inverse operations of a previewed diff, in reverse application
/// order. Deletes are undone by appending the before image (the port has
/// no insert-at-index), so a rolled-back delete returns at the end.
pub fn rollback_ops(changes: &[RowChange]) -> Vec<WriteOp> {
    changes
        .iter()
        .rev()
        .map(|change| match change.kind {
            ChangeKind::Insert => WriteOp::Delete {
                row: change.row.expect("inserts carry their index"),
            },
            ChangeKind::Update => WriteOp::Update {
                row: change.row.expect("updates carry their index"),
                values: change
                    .before
                    .clone()
                    .expect("updates carry the before image"),
            },
            ChangeKind::Delete => WriteOp::Insert {
                values: change
                    .before
                    .clone()
                    .expect("deletes carry the before image"),
            },
        })
        .collect()
}

/// Maps journal operations onto the port's batch vocabulary.
pub fn to_row_write_ops(ops: &[WriteOp]) -> Vec<RowWriteOp> {
    ops.iter()
        .map(|op| match op {
            WriteOp::Insert { values } => RowWriteOp::Insert(values.clone()),
            WriteOp::Update { row, values } => RowWriteOp::Update {
                row: *row,
                values: values.clone(),
            },
            WriteOp::Delete { row } => RowWriteOp::Delete { row: *row },
        })
        .collect()
}

/// One sentence for a batch the driver cannot apply atomically (step 33.1,
/// item M20): non-atomic drivers accept single-operation batches only.
fn atomic_batch_reason(db: &crate::state::DatabaseState, ops: usize) -> Option<String> {
    (!db.capabilities.atomic_batch && ops > 1).then(|| {
        format!(
            "unsupported: the {} driver applies journal batches one operation at a time — a multi-op batch would not be atomic (split it into single-operation batches)",
            db.driver
        )
    })
}

fn out_of_range(table: &TableDef, row: usize, count: usize) -> String {
    format!(
        "row {row} of {:?} is out of range ({count} rows)",
        table.name
    )
}

impl crate::core::Core {
    /// Previews a write batch and stores it as the pending journal.
    pub(crate) fn preview_write(&mut self, table: &str, ops: Vec<WriteOp>) -> Vec<Event> {
        let Some(db) = self.state.database.as_ref() else {
            return failed(
                FailureCode::NoDatabase,
                "no database is open — open a database first",
            );
        };
        // ADR-7: the dispatcher refuses before the port is asked (L14).
        if !db.capabilities.write_rows {
            return failed(
                FailureCode::Capability(crate::availability::DisabledReason::WriteRows),
                DriverCapabilities::unsupported(&db.driver, "write rows for this source"),
            );
        }
        if let Some(reason) = atomic_batch_reason(db, ops.len()) {
            return failed(FailureCode::Unsupported, reason);
        }
        let Some(def) = db
            .tables
            .iter()
            .find(|candidate| candidate.name.eq_ignore_ascii_case(table))
        else {
            return failed(
                FailureCode::NotFound,
                crate::port::PortError::TableNotFound(table.to_owned()).to_string(),
            );
        };
        let def = def.clone();
        let rows = match self.port.read_rows(
            &def.name,
            RowRange {
                start: 0,
                len: usize::MAX,
            },
        ) {
            Ok(rows) => rows,
            Err(e) => return failed(FailureCode::Port, e.to_string()),
        };
        let (prepared, changes) = match preview(&def, &rows, &ops) {
            Ok(result) => result,
            Err(reason) => return failed(FailureCode::InvalidInput, reason),
        };
        let token = self.state.next_write_token;
        self.state.next_write_token += 1;
        self.state.pending_write = Some(PendingWrite {
            table: def.name.clone(),
            token,
            ops: prepared,
            changes: changes.clone(),
        });
        vec![Event::WritePreviewed {
            table: def.name,
            token,
            changes,
        }]
    }

    /// Applies the pending journal after re-validating its preview.
    pub(crate) fn apply_write(&mut self, token: u64) -> Vec<Event> {
        let Some(db) = self.state.database.as_ref() else {
            return failed(
                FailureCode::NoDatabase,
                "no database is open — open a database first",
            );
        };
        if !db.capabilities.write_rows {
            return failed(
                FailureCode::Capability(crate::availability::DisabledReason::WriteRows),
                DriverCapabilities::unsupported(&db.driver, "write rows for this source"),
            );
        }
        let Some(pending) = self.state.pending_write.clone() else {
            return failed(
                FailureCode::Lifecycle,
                "no pending write journal — preview a batch first",
            );
        };
        if pending.token != token {
            return failed(
                FailureCode::Stale,
                format!(
                    "stale write token {token} (pending journal is {})",
                    pending.token
                ),
            );
        }
        if let Some(db) = self.state.database.as_ref()
            && let Some(reason) = atomic_batch_reason(db, pending.ops.len())
        {
            return failed(FailureCode::Unsupported, reason);
        }
        let Some(def) = self
            .state
            .database
            .as_ref()
            .and_then(|db| {
                db.tables
                    .iter()
                    .find(|candidate| candidate.name.eq_ignore_ascii_case(&pending.table))
            })
            .cloned()
        else {
            return failed(
                FailureCode::NotFound,
                crate::port::PortError::TableNotFound(pending.table.clone()).to_string(),
            );
        };
        let rows = match self.port.read_rows(
            &def.name,
            RowRange {
                start: 0,
                len: usize::MAX,
            },
        ) {
            Ok(rows) => rows,
            Err(e) => return failed(FailureCode::Port, e.to_string()),
        };
        let fresh = match preview(&def, &rows, &pending.ops) {
            Ok((_, changes)) => changes,
            Err(reason) => {
                return failed(
                    FailureCode::Stale,
                    format!("the table changed since the preview: {reason}"),
                );
            }
        };
        if fresh != pending.changes {
            return failed(
                FailureCode::Stale,
                "the table changed since the preview — preview the batch again",
            );
        }
        let rollback = rollback_ops(&pending.changes);
        let ops = to_row_write_ops(&pending.ops);
        match self.port.write_row_ops(&pending.table, &ops) {
            Err(e) => failed(FailureCode::Port, e.to_string()),
            Ok(()) => {
                let count = |kind: ChangeKind| {
                    pending
                        .changes
                        .iter()
                        .filter(|change| change.kind == kind)
                        .count()
                };
                self.state.pending_write = None;
                self.state.last_applied = Some(AppliedWrite {
                    table: pending.table.clone(),
                    token,
                    rollback: rollback.clone(),
                });
                vec![Event::WriteApplied {
                    table: pending.table,
                    token,
                    inserted: count(ChangeKind::Insert),
                    updated: count(ChangeKind::Update),
                    deleted: count(ChangeKind::Delete),
                    rollback,
                }]
            }
        }
    }

    /// Rolls the last applied journal back (inverse operations).
    pub(crate) fn rollback_write(&mut self, token: u64) -> Vec<Event> {
        let Some(db) = self.state.database.as_ref() else {
            return failed(
                FailureCode::NoDatabase,
                "no database is open — open a database first",
            );
        };
        if !db.capabilities.write_rows {
            return failed(
                FailureCode::Capability(crate::availability::DisabledReason::WriteRows),
                DriverCapabilities::unsupported(&db.driver, "write rows for this source"),
            );
        }
        let Some(applied) = self.state.last_applied.clone() else {
            return failed(
                FailureCode::Lifecycle,
                "no applied write journal to roll back",
            );
        };
        if applied.token != token {
            return failed(
                FailureCode::Stale,
                format!(
                    "stale rollback token {token} (last applied journal is {})",
                    applied.token
                ),
            );
        }
        let ops = to_row_write_ops(&applied.rollback);
        match self.port.write_row_ops(&applied.table, &ops) {
            Err(e) => failed(FailureCode::Port, e.to_string()),
            Ok(()) => {
                self.state.last_applied = None;
                vec![Event::WriteRolledBack {
                    table: applied.table,
                    token,
                }]
            }
        }
    }

    /// Discards the pending journal without writing anything.
    pub(crate) fn discard_write(&mut self, token: u64) -> Vec<Event> {
        let Some(pending) = self.state.pending_write.as_ref() else {
            return failed(
                FailureCode::Lifecycle,
                "no pending write journal to discard",
            );
        };
        if pending.token != token {
            return failed(
                FailureCode::Stale,
                format!(
                    "stale write token {token} (pending journal is {})",
                    pending.token
                ),
            );
        }
        self.state.pending_write = None;
        vec![Event::WriteDiscarded { token }]
    }
}