surreal-sync-runtime 0.6.0

Shared runtime: apply pipeline, init, SurrealDB config, and transform loading for surreal-sync
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
//! Unit tests for the checkpoint crate.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tempfile::TempDir;

use crate::checkpoint_fs::{
    Checkpoint, CheckpointFile, FilesystemStore, NullStore, SyncManager, SyncPhase,
};

/// Test checkpoint type for unit tests.
///
/// This is a simple checkpoint type that exercises the trait implementation
/// without needing actual database connections.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
struct TestCheckpoint {
    value: i64,
    timestamp: DateTime<Utc>,
}

impl Checkpoint for TestCheckpoint {
    const DATABASE_TYPE: &'static str = "test";

    fn to_cli_string(&self) -> String {
        format!("{}:{}", self.value, self.timestamp.to_rfc3339())
    }

    fn from_cli_string(s: &str) -> anyhow::Result<Self> {
        let parts: Vec<&str> = s.splitn(2, ':').collect();
        if parts.len() != 2 {
            anyhow::bail!("Invalid test checkpoint format: expected 'value:timestamp'");
        }
        Ok(Self {
            value: parts[0].parse()?,
            timestamp: DateTime::parse_from_rfc3339(parts[1])?.with_timezone(&Utc),
        })
    }
}

// ============================================================================
// CheckpointFile Tests
// ============================================================================

#[test]
fn test_checkpoint_file_serialization() {
    let cp = TestCheckpoint {
        value: 42,
        timestamp: Utc::now(),
    };
    let file = CheckpointFile::new(&cp, SyncPhase::FullSyncStart).unwrap();

    assert_eq!(file.database_type, "test");
    assert_eq!(file.phase, SyncPhase::FullSyncStart);

    let parsed: TestCheckpoint = file.parse().unwrap();
    assert_eq!(parsed.value, cp.value);
}

#[test]
fn test_checkpoint_file_roundtrip() {
    let original = TestCheckpoint {
        value: 12345,
        timestamp: Utc::now(),
    };

    // Create file
    let file = CheckpointFile::new(&original, SyncPhase::FullSyncEnd).unwrap();

    // Serialize to JSON
    let json = serde_json::to_string_pretty(&file).unwrap();

    // Deserialize back
    let loaded: CheckpointFile = serde_json::from_str(&json).unwrap();

    // Parse checkpoint
    let parsed: TestCheckpoint = loaded.parse().unwrap();

    assert_eq!(original.value, parsed.value);
    assert_eq!(original.timestamp.timestamp(), parsed.timestamp.timestamp());
}

#[test]
fn test_checkpoint_type_mismatch() {
    let cp = TestCheckpoint {
        value: 42,
        timestamp: Utc::now(),
    };
    let mut file = CheckpointFile::new(&cp, SyncPhase::FullSyncStart).unwrap();
    file.database_type = "wrong".to_string();

    let result: anyhow::Result<TestCheckpoint> = file.parse();
    assert!(result.is_err());

    let err_msg = result.unwrap_err().to_string();
    assert!(err_msg.contains("type mismatch"));
    assert!(err_msg.contains("expected 'test'"));
    assert!(err_msg.contains("found 'wrong'"));
}

#[test]
fn test_checkpoint_file_accessors() {
    let cp = TestCheckpoint {
        value: 99,
        timestamp: Utc::now(),
    };
    let file = CheckpointFile::new(&cp, SyncPhase::FullSyncEnd).unwrap();

    assert_eq!(file.database_type(), "test");
    assert_eq!(file.phase(), &SyncPhase::FullSyncEnd);
    // created_at should be close to now
    let diff = Utc::now() - file.created_at();
    assert!(diff.num_seconds() < 5);
}

// ============================================================================
// SyncPhase Tests
// ============================================================================

#[test]
fn test_sync_phase_as_str() {
    assert_eq!(SyncPhase::FullSyncStart.as_str(), "full_sync_start");
    assert_eq!(SyncPhase::FullSyncEnd.as_str(), "full_sync_end");
    assert_eq!(SyncPhase::CatchUpProgress.as_str(), "catch_up_progress");
}

#[test]
fn test_sync_phase_display() {
    assert_eq!(format!("{}", SyncPhase::FullSyncStart), "full_sync_start");
    assert_eq!(format!("{}", SyncPhase::FullSyncEnd), "full_sync_end");
}

#[test]
fn test_sync_phase_serialization() {
    let phase = SyncPhase::FullSyncStart;
    let json = serde_json::to_string(&phase).unwrap();
    let parsed: SyncPhase = serde_json::from_str(&json).unwrap();
    assert_eq!(phase, parsed);
}

// ============================================================================
// SyncConfig Tests
// ============================================================================

#[test]
fn test_sync_config_default() {
    let config = surreal_sync_core::SyncConfig::default();
    assert!(!config.incremental);
    assert!(config.emit_checkpoints);
    assert!(matches!(
        config.checkpoint_storage,
        surreal_sync_core::CheckpointStorage::Filesystem { ref dir } if dir == ".surreal-sync-checkpoints"
    ));
}

#[test]
fn test_sync_config_full_sync_with_checkpoints() {
    let config =
        surreal_sync_core::SyncConfig::full_sync_with_checkpoints("/custom/path".to_string());
    assert!(!config.incremental);
    assert!(config.emit_checkpoints);
    assert!(matches!(
        config.checkpoint_storage,
        surreal_sync_core::CheckpointStorage::Filesystem { ref dir } if dir == "/custom/path"
    ));
}

#[test]
fn test_sync_config_incremental() {
    let config = surreal_sync_core::SyncConfig::incremental();
    assert!(config.incremental);
    assert!(!config.emit_checkpoints);
    assert!(matches!(
        config.checkpoint_storage,
        surreal_sync_core::CheckpointStorage::Disabled
    ));
}

#[test]
fn test_sync_config_should_emit_checkpoints() {
    // Both enabled and dir configured
    let config1 = surreal_sync_core::SyncConfig {
        incremental: false,
        emit_checkpoints: true,
        checkpoint_storage: surreal_sync_core::CheckpointStorage::Filesystem {
            dir: "/tmp".to_string(),
        },
    };
    assert!(config1.should_emit_checkpoints());

    // Emit disabled
    let config2 = surreal_sync_core::SyncConfig {
        incremental: false,
        emit_checkpoints: false,
        checkpoint_storage: surreal_sync_core::CheckpointStorage::Filesystem {
            dir: "/tmp".to_string(),
        },
    };
    assert!(!config2.should_emit_checkpoints());

    // Dir not configured
    let config3 = surreal_sync_core::SyncConfig {
        incremental: false,
        emit_checkpoints: true,
        checkpoint_storage: surreal_sync_core::CheckpointStorage::Disabled,
    };
    assert!(!config3.should_emit_checkpoints());
}

// ============================================================================
// SyncManager Tests
// ============================================================================

#[tokio::test]
async fn test_sync_manager_emit_and_read() {
    let tmp = TempDir::new().unwrap();
    let store = FilesystemStore::new(tmp.path());
    let manager = SyncManager::new(store);

    let cp = TestCheckpoint {
        value: 123,
        timestamp: Utc::now(),
    };

    manager
        .emit_checkpoint(&cp, SyncPhase::FullSyncStart)
        .await
        .unwrap();

    let read: TestCheckpoint = manager
        .read_checkpoint(SyncPhase::FullSyncStart)
        .await
        .unwrap();

    assert_eq!(read.value, 123);
}

#[tokio::test]
async fn test_sync_manager_emit_disabled() {
    let tmp = TempDir::new().unwrap();
    let store = FilesystemStore::new(tmp.path());
    let manager = SyncManager::new_without_emit(store);

    let cp = TestCheckpoint {
        value: 456,
        timestamp: Utc::now(),
    };

    // Should succeed but not write anything
    manager
        .emit_checkpoint(&cp, SyncPhase::FullSyncStart)
        .await
        .unwrap();

    // Should fail to read (no file written)
    let result: anyhow::Result<TestCheckpoint> =
        manager.read_checkpoint(SyncPhase::FullSyncStart).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_sync_manager_null_store() {
    let manager = SyncManager::new(NullStore);

    let cp = TestCheckpoint {
        value: 789,
        timestamp: Utc::now(),
    };

    // Should succeed (NullStore does nothing)
    manager
        .emit_checkpoint(&cp, SyncPhase::FullSyncStart)
        .await
        .unwrap();

    // Should fail to read (NullStore returns None)
    let result: anyhow::Result<TestCheckpoint> =
        manager.read_checkpoint(SyncPhase::FullSyncStart).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("No checkpoint"));
}

#[tokio::test]
async fn test_sync_manager_reads_latest_checkpoint() {
    let tmp = TempDir::new().unwrap();
    let store = FilesystemStore::new(tmp.path());
    let manager = SyncManager::new(store);

    // Write first checkpoint
    let cp1 = TestCheckpoint {
        value: 100,
        timestamp: Utc::now(),
    };
    manager
        .emit_checkpoint(&cp1, SyncPhase::FullSyncStart)
        .await
        .unwrap();

    // Wait a bit to ensure different modification times
    tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

    // Write second checkpoint
    let cp2 = TestCheckpoint {
        value: 200,
        timestamp: Utc::now(),
    };
    manager
        .emit_checkpoint(&cp2, SyncPhase::FullSyncStart)
        .await
        .unwrap();

    // Should read the second (latest) checkpoint
    let read: TestCheckpoint = manager
        .read_checkpoint(SyncPhase::FullSyncStart)
        .await
        .unwrap();

    assert_eq!(read.value, 200);
}

#[tokio::test]
async fn test_sync_manager_separate_phases() {
    let tmp = TempDir::new().unwrap();
    let store = FilesystemStore::new(tmp.path());
    let manager = SyncManager::new(store);

    // Write start checkpoint
    let cp_start = TestCheckpoint {
        value: 1000,
        timestamp: Utc::now(),
    };
    manager
        .emit_checkpoint(&cp_start, SyncPhase::FullSyncStart)
        .await
        .unwrap();

    // Write end checkpoint
    let cp_end = TestCheckpoint {
        value: 2000,
        timestamp: Utc::now(),
    };
    manager
        .emit_checkpoint(&cp_end, SyncPhase::FullSyncEnd)
        .await
        .unwrap();

    // Read each phase separately
    let read_start: TestCheckpoint = manager
        .read_checkpoint(SyncPhase::FullSyncStart)
        .await
        .unwrap();
    let read_end: TestCheckpoint = manager
        .read_checkpoint(SyncPhase::FullSyncEnd)
        .await
        .unwrap();

    assert_eq!(read_start.value, 1000);
    assert_eq!(read_end.value, 2000);
}

// ============================================================================
// Checkpoint CLI String Tests
// ============================================================================

#[test]
fn test_checkpoint_cli_string_roundtrip() {
    let cp = TestCheckpoint {
        value: 999,
        timestamp: Utc::now(),
    };
    let cli_str = cp.to_cli_string();
    let parsed = TestCheckpoint::from_cli_string(&cli_str).unwrap();
    assert_eq!(parsed.value, cp.value);
    // Compare seconds to avoid nanosecond precision issues
    assert_eq!(parsed.timestamp.timestamp(), cp.timestamp.timestamp());
}

#[test]
fn test_checkpoint_cli_string_invalid_format() {
    // Missing separator
    let result = TestCheckpoint::from_cli_string("123");
    assert!(result.is_err());

    // Invalid value
    let result = TestCheckpoint::from_cli_string("notanumber:2024-01-01T00:00:00Z");
    assert!(result.is_err());

    // Invalid timestamp
    let result = TestCheckpoint::from_cli_string("123:invalid-timestamp");
    assert!(result.is_err());
}

#[test]
fn test_checkpoint_cli_string_specific_value() {
    let cli_str = "42:2024-06-15T14:30:00Z";
    let cp = TestCheckpoint::from_cli_string(cli_str).unwrap();

    assert_eq!(cp.value, 42);
    assert_eq!(cp.timestamp.year(), 2024);
    assert_eq!(cp.timestamp.month(), 6);
    assert_eq!(cp.timestamp.day(), 15);
    assert_eq!(cp.timestamp.hour(), 14);
    assert_eq!(cp.timestamp.minute(), 30);
}

// Need Datelike and Timelike traits for year(), month(), etc.
use chrono::{Datelike, Timelike};