steamroom-client 0.1.0

High-level Steam depot download orchestration and delta patching
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
use crate::download::BoxError;
use crate::download::ChunkFetcher;
use crate::download::DepotJob;
use crate::download::FileFilter;
use crate::event::DownloadEvent;
use bytes::Bytes;
use std::collections::HashMap;
use std::sync::Arc;
use steamroom::depot::ChunkId;
use steamroom::depot::DepotId;
use steamroom::depot::DepotKey;
use steamroom::depot::manifest::DepotManifest;
use steamroom::depot::manifest::ManifestChunk;
use steamroom::depot::manifest::ManifestFile;
use steamroom::util::checksum::SteamAdler32;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

struct NullFetcher;

impl ChunkFetcher for NullFetcher {
    async fn fetch_chunk(
        &self,
        _depot_id: DepotId,
        _chunk_id: &ChunkId,
    ) -> Result<Bytes, BoxError> {
        panic!("NullFetcher should not be called");
    }
}

/// A mock fetcher that returns pre-encrypted chunk data keyed by ChunkId.
struct MockFetcher {
    chunks: HashMap<ChunkId, Bytes>,
}

impl ChunkFetcher for MockFetcher {
    async fn fetch_chunk(&self, _depot_id: DepotId, chunk_id: &ChunkId) -> Result<Bytes, BoxError> {
        self.chunks
            .get(chunk_id)
            .cloned()
            .ok_or_else(|| format!("chunk {:?} not found in mock", chunk_id).into())
    }
}

/// Build an encrypted chunk from plaintext using the given depot key.
/// Format: ECB(IV) ++ CBC(plaintext, key, IV)
fn encrypt_chunk(plaintext: &[u8], key: &DepotKey) -> Vec<u8> {
    let iv = [0x42u8; 16];
    let encrypted_iv = steamroom::crypto::symmetric_encrypt_ecb_nopad(&iv, &key.0).unwrap();
    let encrypted_body = steamroom::crypto::symmetric_encrypt_cbc(plaintext, &key.0, &iv).unwrap();
    let mut chunk = Vec::with_capacity(encrypted_iv.len() + encrypted_body.len());
    chunk.extend_from_slice(&encrypted_iv);
    chunk.extend_from_slice(&encrypted_body);
    chunk
}

fn empty_file(name: &str) -> ManifestFile {
    ManifestFile::new(name.to_string(), 0)
}

fn manifest_with(files: &[&str]) -> DepotManifest {
    DepotManifest::new(files.iter().map(|n| empty_file(n)).collect())
}

fn file_with_chunks(name: &str, chunks: Vec<ManifestChunk>) -> ManifestFile {
    let size: u64 = chunks.iter().map(|c| c.uncompressed_size as u64).sum();
    let mut f = ManifestFile::new(name.to_string(), size);
    f.chunks = chunks;
    f
}

// ---------------------------------------------------------------------------
// FileFilter tests
// ---------------------------------------------------------------------------

#[test]
fn filter_none_matches_everything() {
    let f = FileFilter::None;
    assert!(f.matches("anything.txt"));
    assert!(f.matches(""));
}

#[test]
fn filter_regex_matches_pattern() {
    let f = FileFilter::Regex(regex::Regex::new(r"\.dll$").unwrap());
    assert!(f.matches("bin/game.dll"));
    assert!(!f.matches("bin/game.exe"));
}

#[test]
fn filelist_literal_case_insensitive() {
    let f = FileFilter::from_filelist(&["Game\\Bin\\Server.dll".into()]).unwrap();
    assert!(f.matches("game\\bin\\server.dll"));
    assert!(f.matches("Game\\Bin\\Server.dll"));
}

#[test]
fn filelist_normalizes_separators() {
    let f = FileFilter::from_filelist(&["game/bin/server.dll".into()]).unwrap();
    assert!(f.matches("game\\bin\\server.dll"));
}

#[test]
fn filelist_regex_prefix() {
    let f = FileFilter::from_filelist(&["regex:.*\\.idx$".into()]).unwrap();
    assert!(f.matches("bin/123/idx/foo.idx"));
    assert!(!f.matches("bin/123/idx/foo.txt"));
}

#[test]
fn filelist_mixed_literal_and_regex() {
    let f = FileFilter::from_filelist(&["exact_file.txt".into(), "regex:^maps/.*\\.vpk$".into()])
        .unwrap();
    assert!(f.matches("exact_file.txt"));
    assert!(f.matches("maps/de_dust2.vpk"));
    assert!(!f.matches("other.txt"));
}

#[test]
fn filelist_invalid_regex_returns_error() {
    let result = FileFilter::from_filelist(&["regex:[invalid".into()]);
    assert!(result.is_err());
}

#[test]
fn filelist_empty_gives_no_matches() {
    let f = FileFilter::from_filelist(&[]).unwrap();
    assert!(!f.matches("anything"));
}

// ---------------------------------------------------------------------------
// Download pipeline: actual chunk fetch + decrypt
// ---------------------------------------------------------------------------

#[tokio::test]
async fn download_single_file_with_one_chunk() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();
    let key = DepotKey([0xAA; 32]);
    let plaintext = b"hello steam depot";
    let checksum = SteamAdler32::compute(plaintext);

    let chunk_id = ChunkId([1; 20]);
    let encrypted = encrypt_chunk(plaintext, &key);

    let mut chunks = HashMap::new();
    chunks.insert(chunk_id.clone(), Bytes::from(encrypted));

    let mut chunk = ManifestChunk::new(chunk_id, checksum.0, plaintext.len() as u32);
    chunk.offset = Some(0);
    let manifest = DepotManifest::new(vec![file_with_chunks("test.txt", vec![chunk])]);

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(key)
        .install_dir(install.to_path_buf())
        .build()
        .unwrap();

    let stats = job
        .download(&manifest, Arc::new(MockFetcher { chunks }))
        .await
        .unwrap();

    assert_eq!(stats.files_completed, 1);
    assert_eq!(std::fs::read(install.join("test.txt")).unwrap(), plaintext);
}

#[tokio::test]
async fn download_multi_chunk_file_reassembles_in_order() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();
    let key = DepotKey([0xBB; 32]);

    let part_a = b"AAAA";
    let part_b = b"BBBB";
    let combined: Vec<u8> = [&part_a[..], &part_b[..]].concat();

    let id_a = ChunkId([0xA0; 20]);
    let id_b = ChunkId([0xB0; 20]);

    let mut chunks = HashMap::new();
    chunks.insert(id_a.clone(), Bytes::from(encrypt_chunk(part_a, &key)));
    chunks.insert(id_b.clone(), Bytes::from(encrypt_chunk(part_b, &key)));

    let mut chunk_a =
        ManifestChunk::new(id_a, SteamAdler32::compute(part_a).0, part_a.len() as u32);
    chunk_a.offset = Some(0);
    let mut chunk_b =
        ManifestChunk::new(id_b, SteamAdler32::compute(part_b).0, part_b.len() as u32);
    chunk_b.offset = Some(part_a.len() as u64);
    let manifest = DepotManifest::new(vec![file_with_chunks("multi.bin", vec![chunk_a, chunk_b])]);

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(key)
        .install_dir(install.to_path_buf())
        .build()
        .unwrap();

    let stats = job
        .download(&manifest, Arc::new(MockFetcher { chunks }))
        .await
        .unwrap();

    assert_eq!(stats.files_completed, 1);
    assert_eq!(std::fs::read(install.join("multi.bin")).unwrap(), combined);
}

#[tokio::test]
async fn download_skips_filtered_files() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();
    let key = DepotKey([0xCC; 32]);

    let manifest = manifest_with(&["include.txt", "exclude.dat"]);

    let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel();

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(key)
        .install_dir(install.to_path_buf())
        .file_filter(FileFilter::Regex(regex::Regex::new(r"\.txt$").unwrap()))
        .event_sender(event_tx)
        .build()
        .unwrap();

    let stats = job
        .download(&manifest, Arc::new(NullFetcher))
        .await
        .unwrap();

    assert_eq!(stats.files_completed, 1);
    assert_eq!(stats.files_skipped, 1);
    assert!(install.join("include.txt").exists());
    assert!(!install.join("exclude.dat").exists());

    drop(job);
    let mut skipped = vec![];
    while let Ok(event) = event_rx.try_recv() {
        if let DownloadEvent::FileSkipped { filename } = event {
            skipped.push(filename);
        }
    }
    assert_eq!(skipped, vec!["exclude.dat"]);
}

#[tokio::test]
async fn download_emits_progress_events() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();
    let key = DepotKey([0xDD; 32]);
    let plaintext = b"event test data!";
    let checksum = SteamAdler32::compute(plaintext);
    let chunk_id = ChunkId([0xEE; 20]);

    let mut chunks = HashMap::new();
    chunks.insert(
        chunk_id.clone(),
        Bytes::from(encrypt_chunk(plaintext, &key)),
    );

    let mut chunk = ManifestChunk::new(chunk_id, checksum.0, plaintext.len() as u32);
    chunk.offset = Some(0);
    let manifest = DepotManifest::new(vec![file_with_chunks("evented.bin", vec![chunk])]);

    let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel();

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(key)
        .install_dir(install.to_path_buf())
        .event_sender(event_tx)
        .build()
        .unwrap();

    job.download(&manifest, Arc::new(MockFetcher { chunks }))
        .await
        .unwrap();
    drop(job);

    let mut saw_started = false;
    let mut saw_chunk = false;
    let mut saw_completed = false;
    while let Ok(event) = event_rx.try_recv() {
        match event {
            DownloadEvent::FileStarted { filename } if filename == "evented.bin" => {
                saw_started = true
            }
            DownloadEvent::ChunkCompleted { bytes } if bytes == plaintext.len() as u64 => {
                saw_chunk = true
            }
            DownloadEvent::FileCompleted { filename } if filename == "evented.bin" => {
                saw_completed = true
            }
            _ => {}
        }
    }
    assert!(saw_started, "missing FileStarted event");
    assert!(saw_chunk, "missing ChunkCompleted event");
    assert!(saw_completed, "missing FileCompleted event");
}

// ---------------------------------------------------------------------------
// Delta removal tests (from original file)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn delta_removes_files_not_in_new_manifest() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();

    std::fs::write(install.join("keep.txt"), b"keep").unwrap();
    std::fs::write(install.join("remove_me.txt"), b"old").unwrap();
    std::fs::write(install.join("also_gone.dat"), b"old").unwrap();

    let old_files = vec![
        "keep.txt".to_string(),
        "remove_me.txt".to_string(),
        "also_gone.dat".to_string(),
    ];

    let new_manifest = manifest_with(&["keep.txt", "new_file.txt"]);

    let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel();

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(DepotKey([0; 32]))
        .install_dir(install.to_path_buf())
        .old_manifest_files(old_files)
        .event_sender(event_tx)
        .build()
        .unwrap();

    let stats = job
        .download(&new_manifest, Arc::new(NullFetcher))
        .await
        .unwrap();

    assert_eq!(stats.files_removed, 2);
    assert!(!install.join("remove_me.txt").exists());
    assert!(!install.join("also_gone.dat").exists());
    assert!(install.join("keep.txt").exists());
    assert!(install.join("new_file.txt").exists());

    drop(job);
    let mut removed = vec![];
    while let Ok(event) = event_rx.try_recv() {
        if let DownloadEvent::FileRemoved { filename } = event {
            removed.push(filename);
        }
    }
    removed.sort();
    assert_eq!(removed, vec!["also_gone.dat", "remove_me.txt"]);
}

#[tokio::test]
async fn delta_no_removal_without_old_manifest() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();
    std::fs::write(install.join("stale.txt"), b"should survive").unwrap();

    let new_manifest = manifest_with(&["new.txt"]);

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(DepotKey([0; 32]))
        .install_dir(install.to_path_buf())
        .build()
        .unwrap();

    let stats = job
        .download(&new_manifest, Arc::new(NullFetcher))
        .await
        .unwrap();

    assert_eq!(stats.files_removed, 0);
    assert!(install.join("stale.txt").exists());
}

#[tokio::test]
async fn delta_skips_already_missing_files() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();

    let old_files = vec!["gone.txt".to_string()];
    let new_manifest = manifest_with(&["new.txt"]);

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(DepotKey([0; 32]))
        .install_dir(install.to_path_buf())
        .old_manifest_files(old_files)
        .build()
        .unwrap();

    let stats = job
        .download(&new_manifest, Arc::new(NullFetcher))
        .await
        .unwrap();

    assert_eq!(stats.files_removed, 0);
}

#[tokio::test]
async fn delta_removes_empty_directories() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();

    let sub = install.join("old_subdir");
    std::fs::create_dir_all(&sub).unwrap();

    let old_files = vec!["old_subdir".to_string()];
    let new_manifest = manifest_with(&["file.txt"]);

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(DepotKey([0; 32]))
        .install_dir(install.to_path_buf())
        .old_manifest_files(old_files)
        .build()
        .unwrap();

    let stats = job
        .download(&new_manifest, Arc::new(NullFetcher))
        .await
        .unwrap();

    assert_eq!(stats.files_removed, 1);
    assert!(!sub.exists());
}

#[tokio::test]
async fn delta_does_not_remove_nonempty_directories() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();

    let sub = install.join("subdir");
    std::fs::create_dir_all(&sub).unwrap();
    std::fs::write(sub.join("child.txt"), b"content").unwrap();

    let old_files = vec!["subdir".to_string()];
    let new_manifest = manifest_with(&["other.txt"]);

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(DepotKey([0; 32]))
        .install_dir(install.to_path_buf())
        .old_manifest_files(old_files)
        .build()
        .unwrap();

    let stats = job
        .download(&new_manifest, Arc::new(NullFetcher))
        .await
        .unwrap();

    assert_eq!(stats.files_removed, 0);
    assert!(sub.exists());
}

#[tokio::test]
async fn delta_handles_nested_paths() {
    let dir = tempfile::tempdir().unwrap();
    let install = dir.path();

    let nested = install.join("game").join("bin");
    std::fs::create_dir_all(&nested).unwrap();
    std::fs::write(nested.join("old.dll"), b"old").unwrap();
    std::fs::write(nested.join("keep.dll"), b"keep").unwrap();

    let old_files = vec![
        "game\\bin\\old.dll".to_string(),
        "game\\bin\\keep.dll".to_string(),
    ];
    let new_manifest = manifest_with(&["game\\bin\\keep.dll"]);

    let job = DepotJob::builder()
        .depot_id(DepotId(481))
        .depot_key(DepotKey([0; 32]))
        .install_dir(install.to_path_buf())
        .old_manifest_files(old_files)
        .build()
        .unwrap();

    let stats = job
        .download(&new_manifest, Arc::new(NullFetcher))
        .await
        .unwrap();

    assert_eq!(stats.files_removed, 1);
    assert!(!nested.join("old.dll").exists());
    assert!(nested.join("keep.dll").exists());
}