restic-123pan 0.3.1

Restic REST API backend server using 123pan cloud storage
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
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
//! Integration tests for 123pan API operations.
//!
//! These tests require the following environment variables:
//! - PAN123_USERNAME
//! - PAN123_PASSWORD

use bytes::Bytes;
use rand::Rng;
use restic_123pan::error::AppError;
use restic_123pan::pan123::Pan123Client;
use std::env;

/// Get test credentials from environment.
fn get_test_credentials() -> Option<(String, String)> {
    let client_id = env::var("PAN123_USERNAME").ok()?;
    let client_secret = env::var("PAN123_PASSWORD").ok()?;
    Some((client_id, client_secret))
}

/// Skip test if credentials are not available.
macro_rules! skip_if_no_credentials {
    () => {
        if get_test_credentials().is_none() {
            eprintln!("Skipping test: PAN123_USERNAME and PAN123_PASSWORD not set");
            return;
        }
    };
}

/// Retry an operation on 429 rate limiting with exponential backoff up to 60s.
async fn retry_on_rate_limit<F, Fut, T>(mut f: F) -> Result<T, AppError>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<T, AppError>>,
{
    let mut delay = std::time::Duration::from_millis(200);
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);

    loop {
        match f().await {
            Ok(value) => return Ok(value),
            Err(AppError::Pan123Api { code: 429, .. }) => {
                if std::time::Instant::now() >= deadline {
                    return Err(AppError::Internal(
                        "Rate limited for over 60s during test operation".to_string(),
                    ));
                }
                tokio::time::sleep(delay).await;
                delay = std::cmp::min(delay * 2, std::time::Duration::from_secs(5));
            }
            Err(AppError::Auth(msg)) if msg.contains("code: 429") => {
                if std::time::Instant::now() >= deadline {
                    return Err(AppError::Internal(
                        "Rate limited for over 60s during test operation".to_string(),
                    ));
                }
                tokio::time::sleep(delay).await;
                delay = std::cmp::min(delay * 2, std::time::Duration::from_secs(5));
            }
            Err(e) => return Err(e),
        }
    }
}

#[tokio::test]
async fn test_authentication() {
    skip_if_no_credentials!();

    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let (username, password) = get_test_credentials().unwrap();
    let client = Pan123Client::new(username, password, "/auth-test".to_string(), &db_url)
        .await
        .expect("Failed to create client");

    let root_files = retry_on_rate_limit(|| client.list_files(0))
        .await
        .expect("Failed to list root");
    println!("Root files count: {}", root_files.len());
}

#[tokio::test]
async fn test_list_root_directory() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();
    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create test path");
    let files = retry_on_rate_limit(|| client.list_files(0))
        .await
        .expect("Failed to list root");
    assert!(!files.is_empty(), "Root should contain at least one directory");
    let _ = client.delete_file(0, dir_id).await;
}

#[tokio::test]
async fn test_create_and_delete_directory() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create directory");
    client
        .delete_file(0, dir_id)
        .await
        .expect("Failed to delete directory");

    let found = client
        .find_path_id(&repo_path)
        .await
        .expect("find_path_id failed");
    assert!(found.is_none(), "Directory should be deleted");
}

// ============================================================================
// Cache Consistency Tests
// ============================================================================

/// Helper to create a unique test directory name
fn unique_test_path() -> String {
    let suffix: String = rand::thread_rng()
        .sample_iter(&rand::distributions::Alphanumeric)
        .take(8)
        .map(char::from)
        .collect();
    format!("/cache-test-{}", suffix)
}

/// Helper to create a Pan123Client for testing
async fn create_test_client(repo_path: &str, db_url: &str) -> Option<Pan123Client> {
    let (client_id, client_secret) = get_test_credentials()?;
    Pan123Client::new(client_id, client_secret, repo_path.to_string(), db_url)
        .await
        .ok()
}

/// Scenario 1: Basic cache hit - verify listing directory uses cache on second call
#[tokio::test]
async fn test_cache_scenario1_basic_cache_hit() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    // Create test directory
    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create test directory");

    // First call - should fetch from API and cache
    let files1 = client
        .list_files(dir_id)
        .await
        .expect("First list_files failed");

    // Second call - should use cache (we can verify by checking debug logs or timing)
    let files2 = client
        .list_files(dir_id)
        .await
        .expect("Second list_files failed");

    // Results should be identical
    assert_eq!(
        files1.len(),
        files2.len(),
        "Cache should return same number of files"
    );

    // Clean up
    let _ = client.delete_file(0, dir_id).await;

    println!("Scenario 1 passed: Basic cache hit works correctly");
}

/// Scenario 2: Upload new file updates cache
#[tokio::test]
async fn test_cache_scenario2_upload_new_file() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    // Create test directory
    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create test directory");

    // Initialize cache with empty directory
    let files_before = client.list_files(dir_id).await.expect("list_files failed");
    assert!(files_before.is_empty(), "Directory should start empty");

    // Upload a file
    let test_data = Bytes::from("test content for scenario 2");
    let file_id = client
        .upload_file(dir_id, "test-file.txt", test_data.clone())
        .await
        .expect("upload_file failed");

    // List files again - should include new file from cache
    let files_after = client
        .list_files(dir_id)
        .await
        .expect("list_files after upload failed");

    assert_eq!(
        files_after.len(),
        1,
        "Should have exactly one file after upload"
    );
    assert_eq!(
        files_after[0].filename, "test-file.txt",
        "Filename should match"
    );
    assert_eq!(
        files_after[0].size,
        test_data.len() as i64,
        "Size should match"
    );
    assert_eq!(files_after[0].file_id, file_id, "File ID should match");

    // Clean up
    let _ = client.delete_file(dir_id, file_id).await;
    let _ = client.delete_file(0, dir_id).await;

    println!("Scenario 2 passed: Upload new file updates cache correctly");
}

/// Scenario 3: Overwrite upload updates cache (duplicate=2)
#[tokio::test]
async fn test_cache_scenario3_overwrite_upload() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    // Create test directory
    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create test directory");

    // Initialize cache
    let _ = client.list_files(dir_id).await.expect("list_files failed");

    // Upload initial version
    let data_v1 = Bytes::from("version 1 content - 100 bytes padding xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    let file_id_v1 = client
        .upload_file(dir_id, "config", data_v1.clone())
        .await
        .expect("first upload failed");

    let files_v1 = client
        .list_files(dir_id)
        .await
        .expect("list after v1 failed");
    assert_eq!(files_v1.len(), 1, "Should have one file after first upload");
    assert_eq!(
        files_v1[0].size,
        data_v1.len() as i64,
        "Size should match v1"
    );

    // Upload new version (overwrite)
    let data_v2 = Bytes::from("version 2 - different size content with more padding xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    let file_id_v2 = client
        .upload_file(dir_id, "config", data_v2.clone())
        .await
        .expect("second upload failed");

    let files_v2 = client
        .list_files(dir_id)
        .await
        .expect("list after v2 failed");

    // Should still have exactly one file (not duplicated)
    assert_eq!(
        files_v2.len(),
        1,
        "Should still have exactly one file after overwrite"
    );
    assert_eq!(
        files_v2[0].filename, "config",
        "Filename should be unchanged"
    );
    assert_eq!(
        files_v2[0].size,
        data_v2.len() as i64,
        "Size should be updated to v2"
    );
    assert_eq!(files_v2[0].file_id, file_id_v2, "File ID should be updated");
    assert_ne!(
        file_id_v1, file_id_v2,
        "File IDs should differ between versions"
    );

    // Clean up
    let _ = client.delete_file(dir_id, file_id_v2).await;
    let _ = client.delete_file(0, dir_id).await;

    println!("Scenario 3 passed: Overwrite upload updates cache correctly (no duplicates)");
}

/// Scenario 4: Delete file removes from cache
#[tokio::test]
async fn test_cache_scenario4_delete_removes_from_cache() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    // Create test directory
    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create test directory");

    // Initialize cache
    let _ = client.list_files(dir_id).await.expect("list_files failed");

    // Upload a file
    let test_data = Bytes::from("to be deleted");
    let file_id = client
        .upload_file(dir_id, "to_delete.txt", test_data)
        .await
        .expect("upload_file failed");

    // Verify file is in cache
    let files_before = client
        .list_files(dir_id)
        .await
        .expect("list before delete failed");
    assert_eq!(files_before.len(), 1, "Should have one file before delete");

    // Delete the file
    client
        .delete_file(dir_id, file_id)
        .await
        .expect("delete_file failed");

    // Verify file is removed from cache
    let files_after = client
        .list_files(dir_id)
        .await
        .expect("list after delete failed");
    assert!(files_after.is_empty(), "Cache should be empty after delete");

    // Verify find_file returns None
    let found = client
        .find_file(dir_id, "to_delete.txt")
        .await
        .expect("find_file failed");
    assert!(
        found.is_none(),
        "find_file should return None for deleted file"
    );

    // Clean up directory
    let _ = client.delete_file(0, dir_id).await;

    println!("Scenario 4 passed: Delete removes file from cache correctly");
}

/// Scenario 5: Deleting non-existent file doesn't affect cache (idempotent delete)
#[tokio::test]
async fn test_cache_scenario5_idempotent_delete() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    // Create test directory
    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create test directory");

    // Upload a file and initialize cache
    let test_data = Bytes::from("existing file");
    let file_id = client
        .upload_file(dir_id, "existing.txt", test_data)
        .await
        .expect("upload_file failed");

    // List to populate cache
    let files_before = client.list_files(dir_id).await.expect("list_files failed");
    assert_eq!(files_before.len(), 1, "Should have one file");

    // Try to delete a non-existent file ID (use a fake ID)
    let non_existent_id = 999999999i64;
    // Note: This may fail at the 123pan API level, but cache should not be corrupted
    let _ = client.delete_file(dir_id, non_existent_id).await;

    // Cache should still have the existing file
    let files_after = client
        .list_files(dir_id)
        .await
        .expect("list after failed delete");
    assert_eq!(files_after.len(), 1, "Cache should still have one file");
    assert_eq!(
        files_after[0].filename, "existing.txt",
        "Original file should be intact"
    );

    // Clean up
    let _ = client.delete_file(dir_id, file_id).await;
    let _ = client.delete_file(0, dir_id).await;

    println!("Scenario 5 passed: Idempotent delete doesn't corrupt cache");
}

/// Scenario 6: Multiple directories have isolated caches
#[tokio::test]
async fn test_cache_scenario6_multi_directory_isolation() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    // Create two subdirectories
    let path_a = format!("{}/dir_a", repo_path);
    let path_b = format!("{}/dir_b", repo_path);

    let dir_a_id = retry_on_rate_limit(|| client.ensure_path(&path_a))
        .await
        .expect("Failed to create dir_a");

    let dir_b_id = retry_on_rate_limit(|| client.ensure_path(&path_b))
        .await
        .expect("Failed to create dir_b");

    // Initialize caches for both
    let _ = client
        .list_files(dir_a_id)
        .await
        .expect("list dir_a failed");
    let _ = client
        .list_files(dir_b_id)
        .await
        .expect("list dir_b failed");

    // Upload to dir_a
    let data_a = Bytes::from("file in dir_a");
    let file_a_id = client
        .upload_file(dir_a_id, "file_a.txt", data_a)
        .await
        .expect("upload to dir_a failed");

    // Upload to dir_b
    let data_b = Bytes::from("file in dir_b");
    let file_b_id = client
        .upload_file(dir_b_id, "file_b.txt", data_b)
        .await
        .expect("upload to dir_b failed");

    // Verify isolation
    let files_a = client
        .list_files(dir_a_id)
        .await
        .expect("list dir_a after upload");
    let files_b = client
        .list_files(dir_b_id)
        .await
        .expect("list dir_b after upload");

    assert_eq!(files_a.len(), 1, "dir_a should have 1 file");
    assert_eq!(files_b.len(), 1, "dir_b should have 1 file");
    assert_eq!(
        files_a[0].filename, "file_a.txt",
        "dir_a should have file_a.txt"
    );
    assert_eq!(
        files_b[0].filename, "file_b.txt",
        "dir_b should have file_b.txt"
    );

    // Upload more to dir_a, should not affect dir_b
    let data_a2 = Bytes::from("another file in dir_a");
    let file_a2_id = client
        .upload_file(dir_a_id, "file_a2.txt", data_a2)
        .await
        .expect("second upload to dir_a failed");

    let files_a_after = client.list_files(dir_a_id).await.expect("list dir_a final");
    let files_b_after = client.list_files(dir_b_id).await.expect("list dir_b final");

    assert_eq!(files_a_after.len(), 2, "dir_a should have 2 files");
    assert_eq!(
        files_b_after.len(),
        1,
        "dir_b should still have 1 file (not polluted)"
    );

    // Clean up
    let _ = client.delete_file(dir_a_id, file_a_id).await;
    let _ = client.delete_file(dir_a_id, file_a2_id).await;
    let _ = client.delete_file(dir_b_id, file_b_id).await;
    let _ = client.delete_file(0, dir_a_id).await;
    let _ = client.delete_file(0, dir_b_id).await;
    let repo_id = client.find_path_id(&repo_path).await.ok().flatten();
    if let Some(id) = repo_id {
        let _ = client.delete_file(0, id).await;
    }

    println!("Scenario 6 passed: Multi-directory caches are properly isolated");
}

/// Scenario 7: Upload without prior cache initialization
#[tokio::test]
async fn test_cache_scenario7_upload_without_cache_init() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    // Create test directory
    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create test directory");

    // Upload WITHOUT calling list_files first (cache not initialized)
    let test_data = Bytes::from("uploaded without cache");
    let file_id = client
        .upload_file(dir_id, "first.txt", test_data.clone())
        .await
        .expect("upload_file failed");

    // Now list files - should call API and include the uploaded file
    let files = client.list_files(dir_id).await.expect("list_files failed");

    assert_eq!(files.len(), 1, "Should find the uploaded file");
    assert_eq!(files[0].filename, "first.txt", "Filename should match");
    assert_eq!(files[0].size, test_data.len() as i64, "Size should match");

    // Clean up
    let _ = client.delete_file(dir_id, file_id).await;
    let _ = client.delete_file(0, dir_id).await;

    println!("Scenario 7 passed: Upload without prior cache init works correctly");
}

/// Scenario 8: Consecutive rapid operations maintain cache consistency
#[tokio::test]
async fn test_cache_scenario8_rapid_consecutive_operations() {
    skip_if_no_credentials!();

    let repo_path = unique_test_path();
    let db_file = tempfile::NamedTempFile::new().unwrap();
    let db_url = format!("sqlite:{}?mode=rwc", db_file.path().display());
    let client = create_test_client(&repo_path, &db_url).await.unwrap();

    // Create test directory
    let dir_id = retry_on_rate_limit(|| client.ensure_path(&repo_path))
        .await
        .expect("Failed to create test directory");

    // Initialize cache
    let _ = client.list_files(dir_id).await.expect("list_files failed");

    // Rapid operations: upload a, upload b, delete a, upload c
    let data_a = Bytes::from("file a");
    let file_a_id = client
        .upload_file(dir_id, "a.txt", data_a)
        .await
        .expect("upload a failed");

    let data_b = Bytes::from("file b");
    let file_b_id = client
        .upload_file(dir_id, "b.txt", data_b)
        .await
        .expect("upload b failed");

    client
        .delete_file(dir_id, file_a_id)
        .await
        .expect("delete a failed");

    let data_c = Bytes::from("file c");
    let file_c_id = client
        .upload_file(dir_id, "c.txt", data_c)
        .await
        .expect("upload c failed");

    // Final state should have b.txt and c.txt only
    let files = client.list_files(dir_id).await.expect("final list failed");

    assert_eq!(files.len(), 2, "Should have exactly 2 files (b and c)");

    let filenames: Vec<&str> = files.iter().map(|f| f.filename.as_str()).collect();
    assert!(filenames.contains(&"b.txt"), "Should contain b.txt");
    assert!(filenames.contains(&"c.txt"), "Should contain c.txt");
    assert!(
        !filenames.contains(&"a.txt"),
        "Should NOT contain a.txt (deleted)"
    );

    // Clean up
    let _ = client.delete_file(dir_id, file_b_id).await;
    let _ = client.delete_file(dir_id, file_c_id).await;
    let _ = client.delete_file(0, dir_id).await;

    println!("Scenario 8 passed: Rapid consecutive operations maintain cache consistency");
}