remdb 0.3.2

嵌入式内存数据库
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
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
// Slave-Side Sync Receiver
//
// Receives sync data from master and applies it to the local database.

use crate::ha::protocol::{SyncAck, SyncDataBegin, SyncDataChunk, SyncDataEnd, SyncType};
use crate::ha::{HAError, Result, SyncState};
use crate::pubsub;
use crate::pubsub::topics::{
    SYNC_ACK_TOPIC, SYNC_DATA_BEGIN_TOPIC, SYNC_DATA_CHUNK_TOPIC, SYNC_DATA_END_TOPIC,
};
use alloc::vec::Vec;
use core::sync::atomic::{AtomicU32, Ordering};

#[cfg(feature = "log")]
use crate::log::{debug, error, info, warn};

/// Global sync state for callback access
static SYNC_RECEIVER_STATE: AtomicU32 = AtomicU32::new(SyncState::Idle as u32);

/// Global accumulated data for callback access
static mut SYNC_ACCUMULATED_DATA: Option<Vec<u8>> = None;
static mut SYNC_EXPECTED_CHUNKS: u32 = 0;
static mut SYNC_RECEIVED_CHUNKS: u32 = 0;
static mut SYNC_BEGIN_INFO: Option<SyncDataBegin> = None;

/// Slave-side sync receiver
pub struct SyncReceiver {
    /// Current sync state
    state: SyncState,
    /// Slave ID
    slave_id: u8,
    /// Expected chunk count
    expected_chunks: u32,
    /// Received chunk count
    received_chunks: u32,
    /// Accumulated data buffer
    accumulated_data: Vec<u8>,
    /// Sync begin info
    sync_begin_info: Option<SyncDataBegin>,
    /// Lock for thread safety
    lock: u32,
}

impl SyncReceiver {
    /// Create a new sync receiver
    pub fn new(slave_id: u8) -> Self {
        Self {
            state: SyncState::Idle,
            slave_id,
            expected_chunks: 0,
            received_chunks: 0,
            accumulated_data: Vec::new(),
            sync_begin_info: None,
            lock: 0,
        }
    }

    /// Initialize the sync receiver (subscribe to sync data topics)
    pub fn init(&mut self) -> Result<()> {
        #[cfg(feature = "log")]
        debug!("SyncReceiver: Initializing and subscribing to sync data topics");

        // Subscribe to sync data topics
        pubsub::subscribe(SYNC_DATA_BEGIN_TOPIC, Self::handle_sync_begin_callback)
            .map_err(|_| HAError::InitFailed)?;

        pubsub::subscribe(SYNC_DATA_CHUNK_TOPIC, Self::handle_sync_chunk_callback)
            .map_err(|_| HAError::InitFailed)?;

        pubsub::subscribe(SYNC_DATA_END_TOPIC, Self::handle_sync_end_callback)
            .map_err(|_| HAError::InitFailed)?;

        #[cfg(feature = "log")]
        info!("SyncReceiver: Successfully initialized");

        Ok(())
    }

    /// Start receiving sync data
    pub fn start_sync(&mut self) -> Result<()> {
        self.state = SyncState::Syncing;
        self.expected_chunks = 0;
        self.received_chunks = 0;
        self.accumulated_data.clear();
        self.sync_begin_info = None;

        SYNC_RECEIVER_STATE.store(SyncState::Syncing as u32, Ordering::SeqCst);

        // Reset global state
        unsafe {
            SYNC_ACCUMULATED_DATA = Some(Vec::new());
            SYNC_EXPECTED_CHUNKS = 0;
            SYNC_RECEIVED_CHUNKS = 0;
            SYNC_BEGIN_INFO = None;
        }

        #[cfg(feature = "log")]
        debug!("SyncReceiver: Started sync, waiting for data");

        Ok(())
    }

    /// Wait for sync to complete with timeout
    pub fn wait_for_completion(&mut self, timeout_ms: u64) -> Result<()> {
        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_millis(timeout_ms);

        while start.elapsed() < timeout {
            let current_state = SYNC_RECEIVER_STATE.load(Ordering::SeqCst);

            match SyncState::from(current_state) {
                SyncState::Synced => {
                    #[cfg(feature = "log")]
                    info!("SyncReceiver: Sync completed successfully");
                    self.state = SyncState::Synced;
                    return Ok(());
                }
                SyncState::Failed => {
                    #[cfg(feature = "log")]
                    error!("SyncReceiver: Sync failed");
                    self.state = SyncState::Failed;
                    return Err(HAError::SyncFailed);
                }
                SyncState::Syncing => {
                    // Continue waiting
                    std::thread::sleep(std::time::Duration::from_millis(10));
                }
                SyncState::Idle => {
                    // Should not happen during sync
                    break;
                }
            }
        }

        #[cfg(feature = "log")]
        error!("SyncReceiver: Sync timed out after {}ms", timeout_ms);
        self.state = SyncState::Failed;
        Err(HAError::SyncFailed)
    }

    /// Callback for handling sync begin messages
    fn handle_sync_begin_callback(topic_id: u16, data: &[u8]) -> bool {
        if topic_id != SYNC_DATA_BEGIN_TOPIC {
            return false;
        }

        #[cfg(feature = "log")]
        debug!(
            "SyncReceiver: Received SYNC_DATA_BEGIN, data len: {}",
            data.len()
        );

        let begin = match SyncDataBegin::decode(data) {
            Some(b) => b,
            None => {
                #[cfg(feature = "log")]
                error!("SyncReceiver: Failed to decode SYNC_DATA_BEGIN");
                SYNC_RECEIVER_STATE.store(SyncState::Failed as u32, Ordering::SeqCst);
                return false;
            }
        };

        #[cfg(feature = "log")]
        info!(
            "SyncReceiver: Sync begin - type: {:?}, total_size: {}, chunks: {}, tables: {}, logs: {}",
            begin.sync_type,
            begin.total_size,
            begin.chunk_count,
            begin.table_count,
            begin.log_count
        );

        // Store begin info and prepare for data
        unsafe {
            SYNC_BEGIN_INFO = Some(begin);
            SYNC_EXPECTED_CHUNKS = begin.chunk_count;
            SYNC_RECEIVED_CHUNKS = 0;
            if let Some(ref mut acc) = SYNC_ACCUMULATED_DATA {
                acc.reserve(begin.total_size as usize);
            }
        }

        true
    }

    /// Callback for handling sync chunk messages
    fn handle_sync_chunk_callback(topic_id: u16, data: &[u8]) -> bool {
        if topic_id != SYNC_DATA_CHUNK_TOPIC {
            return false;
        }

        let chunk = match SyncDataChunk::decode(data) {
            Some(c) => c,
            None => {
                #[cfg(feature = "log")]
                error!("SyncReceiver: Failed to decode SYNC_DATA_CHUNK");
                SYNC_RECEIVER_STATE.store(SyncState::Failed as u32, Ordering::SeqCst);
                return false;
            }
        };

        #[cfg(feature = "log")]
        debug!(
            "SyncReceiver: Received chunk {}/{}, size: {}",
            chunk.chunk_index + 1,
            unsafe { SYNC_EXPECTED_CHUNKS },
            chunk.data_size
        );

        // Accumulate data
        unsafe {
            if let Some(ref mut acc) = SYNC_ACCUMULATED_DATA {
                acc.extend_from_slice(&chunk.data);
            }
            SYNC_RECEIVED_CHUNKS += 1;
        }

        true
    }

    /// Callback for handling sync end messages
    fn handle_sync_end_callback(topic_id: u16, data: &[u8]) -> bool {
        if topic_id != SYNC_DATA_END_TOPIC {
            return false;
        }

        #[cfg(feature = "log")]
        debug!("SyncReceiver: Received SYNC_DATA_END");

        let end = match SyncDataEnd::decode(data) {
            Some(e) => e,
            None => {
                #[cfg(feature = "log")]
                error!("SyncReceiver: Failed to decode SYNC_DATA_END");
                SYNC_RECEIVER_STATE.store(SyncState::Failed as u32, Ordering::SeqCst);
                return false;
            }
        };

        let expected = unsafe { SYNC_EXPECTED_CHUNKS };
        let received = unsafe { SYNC_RECEIVED_CHUNKS };

        #[cfg(feature = "log")]
        info!(
            "SyncReceiver: Sync end - total_chunks: {}, checksum: {}, received: {}",
            end.total_chunks, end.checksum, received
        );

        // Verify chunk count
        if received != expected || end.total_chunks != expected {
            #[cfg(feature = "log")]
            error!(
                "SyncReceiver: Chunk count mismatch - expected: {}, received: {}, reported: {}",
                expected, received, end.total_chunks
            );
            SYNC_RECEIVER_STATE.store(SyncState::Failed as u32, Ordering::SeqCst);
            return false;
        }

        // Apply the accumulated data
        let sync_data = unsafe { SYNC_ACCUMULATED_DATA.take().unwrap_or_default() };
        let begin_info = unsafe { SYNC_BEGIN_INFO.take() };

        if let Some(begin) = begin_info {
            let result = match begin.sync_type {
                SyncType::Full => Self::apply_snapshot(&sync_data),
                SyncType::Incremental => Self::apply_wal_logs(&sync_data),
            };

            match result {
                Ok(_) => {
                    #[cfg(feature = "log")]
                    info!("SyncReceiver: Successfully applied sync data");

                    // Send acknowledgment
                    Self::send_ack(true, received);

                    SYNC_RECEIVER_STATE.store(SyncState::Synced as u32, Ordering::SeqCst);
                }
                Err(e) => {
                    #[cfg(feature = "log")]
                    error!("SyncReceiver: Failed to apply sync data: {:?}", e);

                    // Send negative acknowledgment
                    Self::send_ack(false, received);

                    SYNC_RECEIVER_STATE.store(SyncState::Failed as u32, Ordering::SeqCst);
                }
            }
        } else {
            #[cfg(feature = "log")]
            error!("SyncReceiver: No sync begin info available");
            SYNC_RECEIVER_STATE.store(SyncState::Failed as u32, Ordering::SeqCst);
        }

        true
    }

    /// Apply snapshot data to local database
    fn apply_snapshot(data: &[u8]) -> Result<()> {
        if data.is_empty() {
            #[cfg(feature = "log")]
            warn!("SyncReceiver: Empty snapshot data");
            return Ok(());
        }

        #[cfg(feature = "log")]
        info!(
            "SyncReceiver: Applying snapshot, size: {} bytes",
            data.len()
        );

        let db = unsafe { crate::get_global_db() }.ok_or(HAError::SyncFailed)?;

        unsafe {
            let mut offset = 0;

            // Read table count
            let table_count = data[offset] as usize;
            offset += 1;

            #[cfg(feature = "log")]
            debug!("SyncReceiver: Processing {} tables", table_count);

            for _ in 0..table_count {
                // Read table name
                let name_len = data[offset] as usize;
                offset += 1;
                let table_name = core::str::from_utf8(&data[offset..offset + name_len])
                    .map_err(|_| HAError::SyncFailed)?;
                offset += name_len;

                // Read record size
                let record_size = u32::from_le_bytes([
                    data[offset],
                    data[offset + 1],
                    data[offset + 2],
                    data[offset + 3],
                ]) as usize;
                offset += 4;

                // Read record count
                let _record_count = u32::from_le_bytes([
                    data[offset],
                    data[offset + 1],
                    data[offset + 2],
                    data[offset + 3],
                ]) as usize;
                offset += 4;

                // Read max records
                let _max_records = u32::from_le_bytes([
                    data[offset],
                    data[offset + 1],
                    data[offset + 2],
                    data[offset + 3],
                ]) as usize;
                offset += 4;

                // Read field count
                let field_count = data[offset] as usize;
                offset += 1;

                // Skip field definitions for now
                for _ in 0..field_count {
                    let field_name_len = data[offset] as usize;
                    offset += 1 + field_name_len; // name
                    offset += 1; // data type
                    offset += 2; // offset
                    offset += 2; // dimension
                }

                // Read primary key count
                let pk_count = data[offset] as usize;
                offset += 1;

                // Skip primary key indices
                offset += pk_count;

                #[cfg(feature = "log")]
                debug!(
                    "SyncReceiver: Processing table '{}' (record_size: {})",
                    table_name, record_size
                );

                // Find the table in the local database
                let table_id = db.tables.iter().position(|t| {
                    t.as_ref()
                        .map(|tbl| tbl.def.name == table_name)
                        .unwrap_or(false)
                });

                if let Some(tid) = table_id {
                    if let Some(table) = &mut db.tables[tid] {
                        // Read records
                        loop {
                            let used_flag = data[offset];
                            offset += 1;

                            if used_flag == 0 {
                                // End of records marker
                                break;
                            }

                            // Read record ID
                            let record_id = u32::from_le_bytes([
                                data[offset],
                                data[offset + 1],
                                data[offset + 2],
                                data[offset + 3],
                            ]) as usize;
                            offset += 4;

                            // Read record data
                            let record_data = &data[offset..offset + record_size];
                            offset += record_size;

                            // Apply record to table
                            if record_id < table.def.max_records {
                                let record_ptr = table.get_record_ptr_mut(record_id);
                                crate::platform::memcpy(
                                    record_ptr,
                                    record_data.as_ptr(),
                                    record_size,
                                );

                                // Update status
                                let status_ptr = table.get_status_ptr(record_id);
                                if (*status_ptr).status != crate::types::RecordStatus::Used {
                                    (*status_ptr).status = crate::types::RecordStatus::Used;
                                    table.record_count += 1;
                                }
                                (*status_ptr).version += 1;
                            }
                        }
                    }
                } else {
                    // Table not found, skip records
                    #[cfg(feature = "log")]
                    warn!(
                        "SyncReceiver: Table '{}' not found, skipping records",
                        table_name
                    );

                    loop {
                        let used_flag = data[offset];
                        offset += 1;

                        if used_flag == 0 {
                            break;
                        }

                        // Skip record ID and data
                        offset += 4 + record_size;
                    }
                }
            }
        }

        #[cfg(feature = "log")]
        info!("SyncReceiver: Successfully applied snapshot");

        Ok(())
    }

    /// Apply WAL logs to local database
    fn apply_wal_logs(data: &[u8]) -> Result<()> {
        if data.is_empty() {
            #[cfg(feature = "log")]
            warn!("SyncReceiver: No WAL logs to apply");
            return Ok(());
        }

        #[cfg(feature = "log")]
        info!(
            "SyncReceiver: Applying WAL logs, size: {} bytes",
            data.len()
        );

        // TODO: Implement WAL log application
        // This would parse LogItem structures from the data and apply them

        #[cfg(feature = "log")]
        info!("SyncReceiver: WAL log application not yet fully implemented");

        Ok(())
    }

    /// Send acknowledgment to master
    fn send_ack(success: bool, chunks_received: u32) {
        let slave_id = unsafe {
            crate::ha::get_ha_manager()
                .map(|m| m.get_replication_manager().get_slave_id())
                .unwrap_or(0)
        };

        let ack = SyncAck::new(slave_id, success, chunks_received);
        let ack_data = ack.encode();

        if let Err(e) = pubsub::publish(SYNC_ACK_TOPIC, &ack_data) {
            #[cfg(feature = "log")]
            error!("SyncReceiver: Failed to send ack: {:?}", e);
        } else {
            #[cfg(feature = "log")]
            debug!(
                "SyncReceiver: Sent ack - success: {}, chunks: {}",
                success, chunks_received
            );
        }
    }

    /// Shutdown the sync receiver
    pub fn shutdown(&mut self) -> Result<()> {
        self.state = SyncState::Idle;
        self.accumulated_data.clear();
        self.sync_begin_info = None;

        SYNC_RECEIVER_STATE.store(SyncState::Idle as u32, Ordering::SeqCst);

        unsafe {
            SYNC_ACCUMULATED_DATA = None;
            SYNC_BEGIN_INFO = None;
        }

        Ok(())
    }

    /// Get current state
    pub fn get_state(&self) -> SyncState {
        self.state
    }
}

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