linkrs-transaction 0.1.0

Transaction management for Linkrs
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
//! Transaction Error Type
//!
//! Transaction management related errors.
//!
//! ## Design
//!
//! `TransactionError` is a struct with boxed source error to keep size small (~24 bytes).
//! This follows the same pattern as other error types for consistency.

use std::error::Error;
use std::time::Duration;

use super::types::{SavepointId, TransactionId, TransactionState};
use linkrs_core::error::BoxedError;

/// Transaction operation result type alias
pub type TransactionResult<T> = Result<T, TransactionError>;

/// Transaction error kind enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TransactionErrorKind {
    BeginFailed,
    CommitFailed,
    AbortFailed,
    TransactionNotFound,
    TransactionNotOwner,
    SavepointFailed,
    SavepointNotFound,
    SavepointNotActive,
    NoSavepointsInTransaction,
    InvalidStateTransition,
    InvalidStateForCommit,
    InvalidStateForAbort,
    InvalidStateForExecution,
    TransactionTimeout,
    TransactionExpired,
    RollbackFailed,
    TooManyTransactions,
    ReadOnlyTransaction,
    WriteTransactionConflict,
    RecoveryFailed,
    PersistenceFailed,
    SerializationFailed,
    SyncFailed,
    CheckpointInProgress,
    CheckpointTimeout,
    TransactionBudgetExceeded,
    CommitVetoed,
    SnapshotExpired,
    Internal,
}

impl TransactionErrorKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            TransactionErrorKind::BeginFailed => "begin_failed",
            TransactionErrorKind::CommitFailed => "commit_failed",
            TransactionErrorKind::AbortFailed => "abort_failed",
            TransactionErrorKind::TransactionNotFound => "transaction_not_found",
            TransactionErrorKind::TransactionNotOwner => "transaction_not_owner",
            TransactionErrorKind::SavepointFailed => "savepoint_failed",
            TransactionErrorKind::SavepointNotFound => "savepoint_not_found",
            TransactionErrorKind::SavepointNotActive => "savepoint_not_active",
            TransactionErrorKind::NoSavepointsInTransaction => "no_savepoints_in_transaction",
            TransactionErrorKind::InvalidStateTransition => "invalid_state_transition",
            TransactionErrorKind::InvalidStateForCommit => "invalid_state_for_commit",
            TransactionErrorKind::InvalidStateForAbort => "invalid_state_for_abort",
            TransactionErrorKind::InvalidStateForExecution => "invalid_state_for_execution",
            TransactionErrorKind::TransactionTimeout => "transaction_timeout",
            TransactionErrorKind::TransactionExpired => "transaction_expired",
            TransactionErrorKind::RollbackFailed => "rollback_failed",
            TransactionErrorKind::TooManyTransactions => "too_many_transactions",
            TransactionErrorKind::ReadOnlyTransaction => "read_only_transaction",
            TransactionErrorKind::WriteTransactionConflict => "write_transaction_conflict",
            TransactionErrorKind::RecoveryFailed => "recovery_failed",
            TransactionErrorKind::PersistenceFailed => "persistence_failed",
            TransactionErrorKind::SerializationFailed => "serialization_failed",
            TransactionErrorKind::SyncFailed => "sync_failed",
            TransactionErrorKind::CheckpointInProgress => "checkpoint_in_progress",
            TransactionErrorKind::CheckpointTimeout => "checkpoint_timeout",
            TransactionErrorKind::TransactionBudgetExceeded => "transaction_budget_exceeded",
            TransactionErrorKind::CommitVetoed => "commit_vetoed",
            TransactionErrorKind::SnapshotExpired => "snapshot_expired",
            TransactionErrorKind::Internal => "internal",
        }
    }
}

/// Transaction Error Type
///
/// Design principles:
/// 1. Small size: Uses boxed errors to keep struct size minimal (~24 bytes)
/// 2. Full context: Preserves error chain
/// 3. Clone support: Can be cloned for logging/propagation
#[derive(Debug)]
pub struct TransactionError {
    kind: TransactionErrorKind,
    message: String,
    source: Option<BoxedError>,
}

impl TransactionError {
    pub fn new(kind: TransactionErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            source: None,
        }
    }

    pub fn with_source(mut self, source: BoxedError) -> Self {
        self.source = Some(source);
        self
    }

    pub fn kind(&self) -> TransactionErrorKind {
        self.kind
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    fn from_boxed<E: Error + Send + Sync + 'static>(kind: TransactionErrorKind, error: E) -> Self {
        Self {
            kind,
            message: error.to_string(),
            source: Some(Box::new(error)),
        }
    }

    // Convenience constructors
    pub fn begin_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::BeginFailed, message)
    }

    pub fn commit_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::CommitFailed, message)
    }

    pub fn commit_vetoed(reason: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::CommitVetoed, reason)
    }

    pub fn abort_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::AbortFailed, message)
    }

    pub fn transaction_not_found(id: TransactionId) -> Self {
        Self::new(
            TransactionErrorKind::TransactionNotFound,
            format!("Transaction not found: {}", id),
        )
    }

    pub fn transaction_not_owner(id: TransactionId) -> Self {
        Self::new(
            TransactionErrorKind::TransactionNotOwner,
            format!("Transaction {} is owned by another session", id),
        )
    }

    pub fn savepoint_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::SavepointFailed, message)
    }

    pub fn savepoint_not_found(id: SavepointId) -> Self {
        Self::new(
            TransactionErrorKind::SavepointNotFound,
            format!("Savepoint not found: {}", id),
        )
    }

    pub fn savepoint_not_active(id: SavepointId) -> Self {
        Self::new(
            TransactionErrorKind::SavepointNotActive,
            format!("Savepoint not active: {}", id),
        )
    }

    pub fn no_savepoints_in_transaction() -> Self {
        Self::new(
            TransactionErrorKind::NoSavepointsInTransaction,
            "No savepoints in transaction",
        )
    }

    pub fn invalid_state_transition(from: TransactionState, to: TransactionState) -> Self {
        Self::new(
            TransactionErrorKind::InvalidStateTransition,
            format!("Invalid state transition: from {} to {}", from, to),
        )
    }

    pub fn invalid_state_for_commit(state: TransactionState) -> Self {
        Self::new(
            TransactionErrorKind::InvalidStateForCommit,
            format!("Invalid state for commit: {}", state),
        )
    }

    pub fn invalid_state_for_abort(state: TransactionState) -> Self {
        Self::new(
            TransactionErrorKind::InvalidStateForAbort,
            format!("Invalid state for abort: {}", state),
        )
    }

    pub fn invalid_state_for_execution(state: TransactionState) -> Self {
        Self::new(
            TransactionErrorKind::InvalidStateForExecution,
            format!("Transaction not active, current state: {}", state),
        )
    }

    pub fn transaction_timeout() -> Self {
        Self::new(
            TransactionErrorKind::TransactionTimeout,
            "Transaction timeout",
        )
    }

    pub fn transaction_expired() -> Self {
        Self::new(
            TransactionErrorKind::TransactionExpired,
            "Transaction expired",
        )
    }

    pub fn rollback_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::RollbackFailed, message)
    }

    pub fn too_many_transactions() -> Self {
        Self::new(
            TransactionErrorKind::TooManyTransactions,
            "Too many concurrent transactions",
        )
    }

    pub fn read_only_transaction() -> Self {
        Self::new(
            TransactionErrorKind::ReadOnlyTransaction,
            "Read-only transaction",
        )
    }

    pub fn write_transaction_conflict() -> Self {
        Self::new(
            TransactionErrorKind::WriteTransactionConflict,
            "Write transaction conflict",
        )
    }

    pub fn recovery_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::RecoveryFailed, message)
    }

    pub fn persistence_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::PersistenceFailed, message)
    }

    pub fn serialization_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::SerializationFailed, message)
    }

    pub fn sync_failed(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::SyncFailed, message)
    }

    pub fn checkpoint_in_progress() -> Self {
        Self::new(
            TransactionErrorKind::CheckpointInProgress,
            "New writes are paused during checkpoint",
        )
    }

    pub fn checkpoint_timeout(active_writes: u64) -> Self {
        Self::new(
            TransactionErrorKind::CheckpointTimeout,
            format!(
                "Checkpoint timed out waiting for {} active writes to complete",
                active_writes
            ),
        )
    }

    pub fn internal(message: impl Into<String>) -> Self {
        Self::new(TransactionErrorKind::Internal, message)
    }

    pub fn transaction_budget_exceeded(resource: &str, current: u64, limit: u64) -> Self {
        Self::new(
            TransactionErrorKind::TransactionBudgetExceeded,
            format!("Transaction budget exceeded: {resource} {current} > {limit}"),
        )
    }

    pub fn snapshot_expired(holder: super::types::TransactionId, floor_ts: u64) -> Self {
        Self::new(
            TransactionErrorKind::SnapshotExpired,
            format!(
                "snapshot expired for long read txn={} floor_ts={floor_ts}; retry the read",
                holder.0,
            ),
        )
    }

    pub fn is_timeout(&self) -> bool {
        matches!(
            self.kind,
            TransactionErrorKind::TransactionTimeout | TransactionErrorKind::TransactionExpired
        )
    }

    /// Returns true when this error indicates a transient failure that the client
    /// may retry by re-executing the entire transaction.
    pub fn is_retryable(&self) -> bool {
        matches!(
            self.kind,
            TransactionErrorKind::WriteTransactionConflict
                | TransactionErrorKind::SerializationFailed
                | TransactionErrorKind::SnapshotExpired
        )
    }
}

/// Details for a retryable transaction failure.
///
/// Returned to the client when a transaction fails due to a conflict or
/// serialization error, providing enough information to implement retry logic.
#[derive(Debug, Clone)]
pub struct RetryableTransactionError {
    pub kind: TransactionErrorKind,
    pub message: String,
    /// Suggested backoff duration before retrying.
    pub suggested_backoff: Duration,
    /// Number of retries that have already been attempted.
    pub attempt: u32,
}

impl RetryableTransactionError {
    pub fn new(kind: TransactionErrorKind, message: impl Into<String>, attempt: u32) -> Self {
        let suggested_backoff = Duration::from_millis(100 * 2_u64.pow(attempt.min(6)));
        Self {
            kind,
            message: message.into(),
            suggested_backoff,
            attempt,
        }
    }

    pub fn from_transaction_error(error: &TransactionError, attempt: u32) -> Option<Self> {
        if error.is_retryable() {
            Some(Self::new(
                error.kind(),
                error.message().to_string(),
                attempt,
            ))
        } else {
            None
        }
    }
}

impl std::fmt::Display for RetryableTransactionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "[{}] {} (attempt {}, retry after {:?})",
            self.kind.as_str(),
            self.message,
            self.attempt,
            self.suggested_backoff
        )
    }
}

impl std::error::Error for RetryableTransactionError {}

impl std::fmt::Display for TransactionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}", self.kind.as_str(), self.message)?;
        if let Some(ref source) = self.source {
            write!(f, "\n  Caused by: {}", source)?;
        }
        Ok(())
    }
}

impl Clone for TransactionError {
    fn clone(&self) -> Self {
        Self {
            kind: self.kind,
            message: self.message.clone(),
            source: None,
        }
    }
}

impl std::error::Error for TransactionError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_ref()
            .map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
    }
}

impl From<std::io::Error> for TransactionError {
    fn from(e: std::io::Error) -> Self {
        Self::from_boxed(TransactionErrorKind::Internal, e)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_transaction_error_size() {
        assert!(
            std::mem::size_of::<TransactionError>() <= 64,
            "TransactionError should be small, got {} bytes",
            std::mem::size_of::<TransactionError>()
        );
    }

    #[test]
    fn test_transaction_error_creation() {
        let err = TransactionError::transaction_not_found(TransactionId(123));
        assert_eq!(err.kind(), TransactionErrorKind::TransactionNotFound);
        assert!(err.message().contains("123"));
    }
}