solidb 1.0.1

A lightweight, high-performance structured database server written in Rust.
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
// ==================== Transaction Handlers ====================

use axum::{
    extract::{Path, State},
    http::StatusCode,
    Json,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::handlers::AppState;
use crate::error::DbError;
use crate::storage::query_cache;
use crate::transaction::{IsolationLevel, TransactionId};

#[derive(Debug, Deserialize)]
pub struct BeginTransactionRequest {
    #[serde(rename = "isolationLevel", default)]
    pub isolation_level: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct BeginTransactionResponse {
    pub id: String,
    #[serde(rename = "isolationLevel")]
    pub isolation_level: String,
    pub status: String,
}

pub async fn begin_transaction(
    State(state): State<AppState>,
    Path(db_name): Path<String>,
    Json(req): Json<BeginTransactionRequest>,
) -> Result<Json<BeginTransactionResponse>, DbError> {
    // Ensure database exists
    let _ = state.storage.get_database(&db_name)?;

    // Initialize transaction manager if needed
    let tx_manager = state.storage.transaction_manager()?;

    // Parse isolation level
    let isolation_level = match req.isolation_level.as_deref() {
        Some("read_uncommitted") => IsolationLevel::ReadUncommitted,
        Some("read_committed") | None => IsolationLevel::ReadCommitted,
        Some("repeatable_read") => IsolationLevel::RepeatableRead,
        Some("serializable") => IsolationLevel::Serializable,
        Some(level) => {
            return Err(DbError::InvalidDocument(format!(
                "Unknown isolation level: {}",
                level
            )))
        }
    };

    // Begin transaction
    let tx_id = tx_manager.begin(isolation_level)?;

    Ok(Json(BeginTransactionResponse {
        id: tx_id.to_string(),
        isolation_level: format!("{:?}", isolation_level),
        status: "active".to_string(),
    }))
}

#[derive(Debug, Serialize)]
pub struct CommitTransactionResponse {
    pub id: String,
    pub status: String,
}

pub async fn commit_transaction(
    State(state): State<AppState>,
    Path((_db_name, tx_id_str)): Path<(String, String)>,
) -> Result<Json<CommitTransactionResponse>, DbError> {
    // Parse transaction ID
    let tx_id_value: u64 = tx_id_str
        .strip_prefix("tx:")
        .unwrap_or(&tx_id_str)
        .parse()
        .map_err(|_| DbError::InvalidDocument("Invalid transaction ID".to_string()))?;
    let tx_id = TransactionId::from_u64(tx_id_value);

    // Commit transaction
    state.storage.commit_transaction(tx_id)?;

    // Invalidate query cache since committed data is now visible
    query_cache::get_query_cache().invalidate_all();

    Ok(Json(CommitTransactionResponse {
        id: tx_id.to_string(),
        status: "committed".to_string(),
    }))
}

pub async fn rollback_transaction(
    State(state): State<AppState>,
    Path((_db_name, tx_id_str)): Path<(String, String)>,
) -> Result<Json<CommitTransactionResponse>, DbError> {
    // Parse transaction ID
    let tx_id_value: u64 = tx_id_str
        .strip_prefix("tx:")
        .unwrap_or(&tx_id_str)
        .parse()
        .map_err(|_| DbError::InvalidDocument("Invalid transaction ID".to_string()))?;
    let tx_id = TransactionId::from_u64(tx_id_value);

    // Rollback transaction
    state.storage.rollback_transaction(tx_id)?;

    Ok(Json(CommitTransactionResponse {
        id: tx_id.to_string(),
        status: "aborted".to_string(),
    }))
}

// Transaction document operations

/// Resolve a collection for a transactional document operation.
///
/// SEC-179: these handlers used to discard the `{db}` path segment and pass the
/// bare collection name to `StorageEngine::get_collection`, which resolves a
/// column family by literal name and then falls back to `_system:{name}`. A
/// principal scoped to one database could therefore write into `_system`
/// collections — authorization had already run against the `{db}` it ignored —
/// while ordinary collections were unreachable, because `{db}:{collection}` was
/// never tried.
///
/// Going through `Database` applies the `{db}:` prefix and the
/// credential-collection guard, exactly as every non-transactional handler does.
fn collection_in_database(
    state: &AppState,
    db_name: &str,
    coll_name: &str,
) -> Result<crate::storage::Collection, DbError> {
    state
        .storage
        .get_database(db_name)?
        .get_collection(coll_name)
}

pub async fn insert_document_tx(
    State(state): State<AppState>,
    Path((db_name, tx_id_str, coll_name)): Path<(String, String, String)>,
    Json(data): Json<Value>,
) -> Result<Json<Value>, DbError> {
    // Parse transaction ID
    let tx_id_value: u64 = tx_id_str
        .strip_prefix("tx:")
        .unwrap_or(&tx_id_str)
        .parse()
        .map_err(|_| DbError::InvalidDocument("Invalid transaction ID".to_string()))?;
    let tx_id = TransactionId::from_u64(tx_id_value);

    // Get transaction manager
    let tx_manager = state.storage.transaction_manager()?;

    // Get transaction
    let tx_arc = tx_manager.get(tx_id)?;
    let mut tx = tx_arc.write().unwrap();

    // Get collection, scoped to the database named in the path (SEC-179).
    let collection = collection_in_database(&state, &db_name, &coll_name)?;

    // Perform transactional insert
    let wal = tx_manager.wal().clone();
    let lock_manager = tx_manager.lock_manager().clone();
    let doc = collection.insert_tx(&mut tx, &wal, &lock_manager, data)?;

    Ok(Json(doc.to_value()))
}

pub async fn update_document_tx(
    State(state): State<AppState>,
    Path((db_name, tx_id_str, coll_name, key)): Path<(String, String, String, String)>,
    Json(data): Json<Value>,
) -> Result<Json<Value>, DbError> {
    // Parse transaction ID
    let tx_id_value: u64 = tx_id_str
        .strip_prefix("tx:")
        .unwrap_or(&tx_id_str)
        .parse()
        .map_err(|_| DbError::InvalidDocument("Invalid transaction ID".to_string()))?;
    let tx_id = TransactionId::from_u64(tx_id_value);

    // Get transaction manager
    let tx_manager = state.storage.transaction_manager()?;

    // Get transaction
    let tx_arc = tx_manager.get(tx_id)?;
    let mut tx = tx_arc.write().unwrap();

    // Get collection, scoped to the database named in the path (SEC-179).
    let collection = collection_in_database(&state, &db_name, &coll_name)?;

    // Perform transactional update
    let wal = tx_manager.wal().clone();
    let lock_manager = tx_manager.lock_manager().clone();
    let doc = collection.update_tx(&mut tx, &wal, &lock_manager, &key, data)?;

    Ok(Json(doc.to_value()))
}

pub async fn delete_document_tx(
    State(state): State<AppState>,
    Path((db_name, tx_id_str, coll_name, key)): Path<(String, String, String, String)>,
) -> Result<StatusCode, DbError> {
    // Parse transaction ID
    let tx_id_value: u64 = tx_id_str
        .strip_prefix("tx:")
        .unwrap_or(&tx_id_str)
        .parse()
        .map_err(|_| DbError::InvalidDocument("Invalid transaction ID".to_string()))?;
    let tx_id = TransactionId::from_u64(tx_id_value);

    // Get transaction manager
    let tx_manager = state.storage.transaction_manager()?;

    // Get transaction
    let tx_arc = tx_manager.get(tx_id)?;
    let mut tx = tx_arc.write().unwrap();

    // Get collection, scoped to the database named in the path (SEC-179).
    let collection = collection_in_database(&state, &db_name, &coll_name)?;

    // Perform transactional delete
    let wal = tx_manager.wal().clone();
    let lock_manager = tx_manager.lock_manager().clone();
    collection.delete_tx(&mut tx, &wal, &lock_manager, &key)?;

    Ok(StatusCode::NO_CONTENT)
}

// Transactional SDBQL execution

#[derive(Debug, Deserialize)]
pub struct ExecuteSdbqlTransactionalRequest {
    pub query: String,
    #[serde(default)]
    pub bind_vars: std::collections::HashMap<String, Value>,
}

pub async fn execute_transactional_sdbql(
    State(state): State<AppState>,
    Path((db_name, tx_id_str)): Path<(String, String)>,
    axum::Extension(claims): axum::Extension<crate::server::auth::Claims>,
    Json(req): Json<ExecuteSdbqlTransactionalRequest>,
) -> Result<Json<Value>, DbError> {
    use crate::sdbql::ast::BodyClause;
    use crate::sdbql::{parse, QueryExecutor};

    // The authz middleware only required Read for the /query suffix; upgrade
    // to Write when the transactional query mutates.
    {
        let parsed = parse(&req.query)?;
        if parsed.has_mutations() {
            crate::server::authz_middleware::enforce(
                &claims,
                &state,
                crate::server::authorization::PermissionAction::Write,
                Some(&db_name),
            )
            .await?;
        }
    }

    // Parse transaction ID
    let tx_id_value: u64 = tx_id_str
        .strip_prefix("tx:")
        .unwrap_or(&tx_id_str)
        .parse()
        .map_err(|_| DbError::InvalidDocument("Invalid transaction ID".to_string()))?;
    let tx_id = TransactionId::from_u64(tx_id_value);

    // Get transaction manager
    let tx_manager = state.storage.transaction_manager()?;

    // Get transaction
    let tx_arc = tx_manager.get(tx_id)?;
    let mut tx = tx_arc.write().unwrap();
    let wal = tx_manager.wal().clone();
    let lock_manager = tx_manager.lock_manager().clone();

    // Parse SDBQL query
    let query = parse(&req.query)?;

    // For transactional SDBQL, we need to intercept mutations (INSERT/UPDATE/REMOVE)
    // and execute them transactionally. For now, we support queries with a single mutation operation.

    // Check if query contains mutation operations
    let mut has_insert = false;
    let mut has_update = false;
    let mut has_remove = false;

    for clause in &query.body_clauses {
        match clause {
            BodyClause::Insert(_) => has_insert = true,
            BodyClause::Update(_) => has_update = true,
            BodyClause::Remove(_) => has_remove = true,
            BodyClause::Join(_) => {}   // JOIN is read-only
            BodyClause::Window(_) => {} // Window does not mutate
            BodyClause::Search(_) => {} // SEARCH is a filter
            _ => {}
        }
    }

    if !has_insert && !has_update && !has_remove {
        // No mutations - just execute normally (read operations)
        let executor = QueryExecutor::with_database_and_bind_vars(
            &state.storage,
            db_name.clone(),
            req.bind_vars.clone(),
        )
        .with_principal(crate::server::handlers::query::principal_from_claims(
            &claims,
        ));
        let results = executor.execute(&query)?;
        return Ok(Json(serde_json::json!({"result": results})));
    }

    // For mutation operations, we need to handle them specially
    // Create executor and execute to get the data to mutate
    let executor = QueryExecutor::with_database_and_bind_vars(
        &state.storage,
        db_name.clone(),
        req.bind_vars.clone(),
    )
    .with_principal(crate::server::handlers::query::principal_from_claims(
        &claims,
    ));

    // Execute body clauses manually to intercept mutations
    let mut initial_bindings = std::collections::HashMap::new();

    // Merge bind variables
    for (key, value) in &req.bind_vars {
        initial_bindings.insert(format!("@{}", key), value.clone());
    }

    // Process LET clauses
    for let_clause in &query.let_clauses {
        let value =
            executor.evaluate_expr_with_context(&let_clause.expression, &initial_bindings)?;
        initial_bindings.insert(let_clause.variable.clone(), value);
    }

    // Process body clauses to build row contexts (FOR, LET, FILTER)
    // Then apply mutations (INSERT/UPDATE/REMOVE) transactionally for each row

    let mut rows: Vec<std::collections::HashMap<String, Value>> = vec![initial_bindings.clone()];
    let mut mutation_count = 0;

    // Process body clauses in order
    for clause in &query.body_clauses {
        match clause {
            BodyClause::For(for_clause) => {
                // Build new rows by iterating over the source
                let mut new_rows = Vec::new();
                for ctx in &rows {
                    // Get documents from the FOR source
                    let docs = if let Some(ref expr) = for_clause.source_expression {
                        // Expression-based source (e.g., range, array)
                        let value = executor.evaluate_expr_with_context(expr, ctx)?;
                        match value {
                            Value::Array(arr) => arr,
                            other => vec![other],
                        }
                    } else {
                        // Collection source
                        let source_name = for_clause
                            .source_variable
                            .as_ref()
                            .unwrap_or(&for_clause.collection);

                        // Check if it's a variable in context first
                        if let Some(value) = ctx.get(source_name) {
                            match value {
                                Value::Array(arr) => arr.clone(),
                                other => vec![other.clone()],
                            }
                        } else {
                            // It's a collection - scan it
                            let full_coll_name = format!("{}:{}", db_name, for_clause.collection);
                            let collection = state.storage.get_collection(&full_coll_name)?;
                            collection
                                .scan(None)
                                .into_iter()
                                .map(|d| d.to_value())
                                .collect()
                        }
                    };

                    // Create new context for each document
                    for doc in docs {
                        let mut new_ctx = ctx.clone();
                        new_ctx.insert(for_clause.variable.clone(), doc);
                        new_rows.push(new_ctx);
                    }
                }
                rows = new_rows;
            }
            BodyClause::Let(let_clause) => {
                // Evaluate LET expression for each row
                for ctx in &mut rows {
                    let value = executor.evaluate_expr_with_context(&let_clause.expression, ctx)?;
                    ctx.insert(let_clause.variable.clone(), value);
                }
            }
            BodyClause::Filter(filter_clause) | BodyClause::Search(filter_clause) => {
                // Filter rows based on condition
                rows.retain(|ctx| {
                    executor
                        .evaluate_filter_with_context(&filter_clause.expression, ctx)
                        .unwrap_or(false)
                });
            }
            BodyClause::Insert(insert_clause) => {
                // Get collection
                let full_coll_name = format!("{}:{}", db_name, insert_clause.collection);
                let collection = state.storage.get_collection(&full_coll_name)?;

                // Insert for each row context
                for ctx in &rows {
                    let doc_value =
                        executor.evaluate_expr_with_context(&insert_clause.document, ctx)?;
                    collection.insert_tx(&mut tx, &wal, &lock_manager, doc_value)?;
                    mutation_count += 1;
                }
            }
            BodyClause::Update(update_clause) => {
                // Get collection
                let full_coll_name = format!("{}:{}", db_name, update_clause.collection);
                let collection = state.storage.get_collection(&full_coll_name)?;

                // Update for each row context
                for ctx in &rows {
                    let selector_value =
                        executor.evaluate_expr_with_context(&update_clause.selector, ctx)?;
                    let key = match &selector_value {
                        Value::String(s) => s.clone(),
                        Value::Object(obj) => obj
                            .get("_key")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
                            .ok_or_else(|| {
                                DbError::ExecutionError(
                                    "UPDATE: selector object must have a _key field".to_string(),
                                )
                            })?,
                        _ => return Err(DbError::ExecutionError(
                            "UPDATE: selector must be a string key or an object with _key field"
                                .to_string(),
                        )),
                    };

                    let changes_value =
                        executor.evaluate_expr_with_context(&update_clause.changes, ctx)?;
                    collection.update_tx(&mut tx, &wal, &lock_manager, &key, changes_value)?;
                    mutation_count += 1;
                }
            }
            BodyClause::Remove(remove_clause) => {
                // Get collection
                let full_coll_name = format!("{}:{}", db_name, remove_clause.collection);
                let collection = state.storage.get_collection(&full_coll_name)?;

                // Remove for each row context
                for ctx in &rows {
                    let selector_value =
                        executor.evaluate_expr_with_context(&remove_clause.selector, ctx)?;
                    let key = match &selector_value {
                        Value::String(s) => s.clone(),
                        Value::Object(obj) => obj
                            .get("_key")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string())
                            .ok_or_else(|| {
                                DbError::ExecutionError(
                                    "REMOVE: selector object must have a _key field".to_string(),
                                )
                            })?,
                        _ => return Err(DbError::ExecutionError(
                            "REMOVE: selector must be a string key or an object with _key field"
                                .to_string(),
                        )),
                    };

                    collection.delete_tx(&mut tx, &wal, &lock_manager, &key)?;
                    mutation_count += 1;
                }
            }
            BodyClause::Upsert(upsert_clause) => {
                let full_coll_name = format!("{}:{}", db_name, upsert_clause.collection);
                let collection = state.storage.get_collection(&full_coll_name)?;

                for ctx in &rows {
                    let search_value =
                        executor.evaluate_expr_with_context(&upsert_clause.search, ctx)?;

                    let mut found_doc_key: Option<String> = None;
                    // Simple key lookup logic
                    if let Some(s) = search_value.as_str() {
                        if collection.get(s).is_ok() {
                            found_doc_key = Some(s.to_string());
                        }
                    } else if let Some(obj) = search_value.as_object() {
                        if let Some(k) = obj.get("_key").or_else(|| obj.get("_id")) {
                            if let Some(ks) = k.as_str() {
                                if collection.get(ks).is_ok() {
                                    found_doc_key = Some(ks.to_string());
                                }
                            }
                        }
                    }

                    if let Some(key) = found_doc_key {
                        let update_value =
                            executor.evaluate_expr_with_context(&upsert_clause.update, ctx)?;
                        collection.update_tx(&mut tx, &wal, &lock_manager, &key, update_value)?;
                    } else {
                        let insert_value =
                            executor.evaluate_expr_with_context(&upsert_clause.insert, ctx)?;
                        collection.insert_tx(&mut tx, &wal, &lock_manager, insert_value)?;
                    }
                    mutation_count += 1;
                }
            }
            // JOIN clause - not yet supported in transactions (read-only for now)
            BodyClause::Join(_) => {
                return Err(DbError::ExecutionError(
                    "JOIN operations not yet supported in transactions".to_string(),
                ));
            }
            // Graph traversal clauses - not yet supported in transactions
            BodyClause::GraphTraversal(_) | BodyClause::ShortestPath(_) => {
                return Err(DbError::ExecutionError(
                    "Graph traversals not yet supported in transactions".to_string(),
                ));
            }
            // COLLECT clause - not yet supported in transactions
            BodyClause::Collect(_) => {
                return Err(DbError::ExecutionError(
                    "COLLECT aggregation not yet supported in transactions".to_string(),
                ));
            }
            BodyClause::Window(_) => {
                return Err(DbError::ExecutionError(
                    "Window operations are not supported in transactions".to_string(),
                ));
            }
        }
    }

    // Return success (mutations are staged in transaction)
    Ok(Json(serde_json::json!({
        "result": [],
        "mutationCount": mutation_count,
        "message": format!("{} operation(s) staged in transaction. Commit to apply changes.", mutation_count)
    })))
}

// ==================== Distributed Transaction Handlers ====================

use crate::transaction::distributed::{
    DistributedTransactionCoordinator, DistributedTransactionId, ShardParticipantInfo,
};

pub struct DistributedTxState {
    pub coordinator: std::sync::Arc<tokio::sync::RwLock<DistributedTransactionCoordinator>>,
}

impl DistributedTxState {
    pub fn new() -> Self {
        Self {
            coordinator: std::sync::Arc::new(tokio::sync::RwLock::new(
                DistributedTransactionCoordinator::new(),
            )),
        }
    }
}

impl Default for DistributedTxState {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Deserialize)]
pub struct BeginDistributedTransactionRequest {
    pub participants: Vec<ParticipantRequest>,
}

#[derive(Debug, Deserialize)]
pub struct ParticipantRequest {
    #[serde(rename = "shardId")]
    pub shard_id: u16,
    #[serde(rename = "nodeId")]
    pub node_id: String,
    pub address: String,
}

#[derive(Debug, Serialize)]
pub struct BeginDistributedTransactionResponse {
    pub id: String,
    pub status: String,
    #[serde(rename = "participantCount")]
    pub participant_count: usize,
}

pub async fn begin_distributed_transaction(
    State(_state): State<AppState>,
    Json(req): Json<BeginDistributedTransactionRequest>,
) -> Result<Json<BeginDistributedTransactionResponse>, DbError> {
    let participants: Vec<ShardParticipantInfo> = req
        .participants
        .into_iter()
        .map(|p| ShardParticipantInfo {
            shard_id: p.shard_id,
            node_id: p.node_id,
            address: p.address,
        })
        .collect();

    let coordinator = DistributedTransactionCoordinator::new();
    let tx_id = coordinator.begin_transaction(participants.clone()).await?;

    Ok(Json(BeginDistributedTransactionResponse {
        id: tx_id.to_string(),
        status: "active".to_string(),
        participant_count: participants.len(),
    }))
}

#[derive(Debug, Serialize)]
pub struct PrepareDistributedTransactionResponse {
    pub id: String,
    pub status: String,
    pub success: bool,
}

pub async fn prepare_distributed_transaction(
    State(_state): State<AppState>,
    Path(tx_id): Path<String>,
) -> Result<Json<PrepareDistributedTransactionResponse>, DbError> {
    let coordinator = DistributedTransactionCoordinator::new();
    let dtx_id = DistributedTransactionId(tx_id);

    let success = coordinator.prepare(&dtx_id).await?;

    Ok(Json(PrepareDistributedTransactionResponse {
        id: dtx_id.to_string(),
        status: "prepared".to_string(),
        success,
    }))
}

#[derive(Debug, Serialize)]
pub struct CommitDistributedTransactionResponse {
    pub id: String,
    pub status: String,
}

pub async fn commit_distributed_transaction(
    State(_state): State<AppState>,
    Path(tx_id): Path<String>,
) -> Result<Json<CommitDistributedTransactionResponse>, DbError> {
    let coordinator = DistributedTransactionCoordinator::new();
    let dtx_id = DistributedTransactionId(tx_id);

    coordinator.commit(&dtx_id).await?;

    Ok(Json(CommitDistributedTransactionResponse {
        id: dtx_id.to_string(),
        status: "committed".to_string(),
    }))
}

pub async fn abort_distributed_transaction(
    State(_state): State<AppState>,
    Path(tx_id): Path<String>,
) -> Result<Json<CommitDistributedTransactionResponse>, DbError> {
    let coordinator = DistributedTransactionCoordinator::new();
    let dtx_id = DistributedTransactionId(tx_id);

    coordinator.abort(&dtx_id).await?;

    Ok(Json(CommitDistributedTransactionResponse {
        id: dtx_id.to_string(),
        status: "aborted".to_string(),
    }))
}

// ==================== Distributed Transaction Participant Handlers ====================
// These handlers run on each shard node to receive prepare/commit/abort from coordinator

#[derive(Debug, Serialize)]
pub struct ParticipantResponse {
    pub status: String,
    #[serde(rename = "shardId")]
    pub shard_id: u16,
    pub message: Option<String>,
}

pub async fn participant_prepare(
    State(_state): State<AppState>,
    Path(_tx_id): Path<String>,
) -> Result<Json<ParticipantResponse>, DbError> {
    Ok(Json(ParticipantResponse {
        status: "prepared".to_string(),
        shard_id: 0,
        message: None,
    }))
}

pub async fn participant_commit(
    State(_state): State<AppState>,
    Path(_tx_id): Path<String>,
) -> Result<Json<ParticipantResponse>, DbError> {
    Ok(Json(ParticipantResponse {
        status: "committed".to_string(),
        shard_id: 0,
        message: None,
    }))
}

pub async fn participant_abort(
    State(_state): State<AppState>,
    Path(_tx_id): Path<String>,
) -> Result<Json<ParticipantResponse>, DbError> {
    Ok(Json(ParticipantResponse {
        status: "aborted".to_string(),
        shard_id: 0,
        message: None,
    }))
}