rspack_core 0.101.2

rspack core
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
mod hash_helper;
mod package_helper;

use std::sync::Arc;

use rspack_cacheable::cacheable;
use rspack_fs::ReadableFileSystem;
use rspack_paths::{ArcPath, AssertUtf8};

use self::{
  hash_helper::{ContentHash, HashHelper, TimestampHash},
  package_helper::PackageHelper,
};
use super::{SnapshotOptions, SnapshotStrategyOptions};

/// Snapshot check strategy
#[cacheable]
#[derive(Debug)]
pub enum Strategy {
  /// Check by package version
  ///
  /// This strategy will find the package.json in the parent directory, and
  /// compares the version field.
  PackageVersion(String),

  /// Check by file hash
  ///
  /// This strategy will compare the file hash.
  FileHash { hash: u64 },

  /// Check by file timestamp
  FileTimestamp { mtime: u64 },

  /// Check by file timestamp and hash
  ///
  /// This strategy will first compare the modified time,
  /// and then compare the file hash when the modified time changed.
  FileTimestampAndHash { mtime: u64, hash: u64 },

  /// Check by dir hash
  ///
  /// This strategy will compare the content hash of all files within the directory.
  DirHash { hash: u64 },

  /// Check by dir timestamp hash
  DirTimestamp { timestamp_hash: u64 },

  /// Check by dir timestamp hash and content hash
  DirTimestampAndHash { timestamp_hash: u64, hash: u64 },

  /// Check missing file
  ///
  /// This strategy indicates that the current file is in a missing state,
  /// and will return ValidateResult::Modified if it exists.
  Missing,

  /// Check failed snapshot
  ///
  /// This strategy represents a snapshot that could not be created or
  /// validated correctly and should be treated as invalid.
  Failed,
}

impl PartialEq for Strategy {
  fn eq(&self, other: &Self) -> bool {
    match (self, other) {
      (Self::PackageVersion(v1), Self::PackageVersion(v2)) => v1 == v2,
      (Self::FileHash { hash: h1, .. }, Self::FileHash { hash: h2, .. }) => h1 == h2,
      (Self::FileTimestamp { mtime: m1 }, Self::FileTimestamp { mtime: m2 }) => m1 == m2,
      (
        Self::FileTimestampAndHash { hash: h1, .. },
        Self::FileTimestampAndHash { hash: h2, .. },
      ) => h1 == h2,
      (Self::DirHash { hash: h1, .. }, Self::DirHash { hash: h2, .. }) => h1 == h2,
      (Self::DirTimestamp { timestamp_hash: h1 }, Self::DirTimestamp { timestamp_hash: h2 }) => {
        h1 == h2
      }
      (Self::DirTimestampAndHash { hash: h1, .. }, Self::DirTimestampAndHash { hash: h2, .. }) => {
        h1 == h2
      }
      (Self::Missing, Self::Missing) => true,
      (Self::Failed, Self::Failed) => true,
      _ => false,
    }
  }
}

/// Validate Result
#[derive(Debug)]
pub enum ValidateResult {
  /// The target file has been deleted
  Deleted,
  /// The target file has been modified
  Modified,
  /// The target file has no changed
  NoChanged,
}

pub struct StrategyHelper {
  fs: Arc<dyn ReadableFileSystem>,
  package_helper: Arc<PackageHelper>,
  hash_helper: HashHelper,
}

impl StrategyHelper {
  pub fn new(fs: Arc<dyn ReadableFileSystem>, snapshot_options: Arc<SnapshotOptions>) -> Self {
    let package_helper = Arc::new(PackageHelper::new(fs.clone()));
    Self {
      fs: fs.clone(),
      hash_helper: HashHelper::new(fs, snapshot_options, package_helper.clone()),
      package_helper,
    }
  }

  /// get path file modified time
  async fn modified_time(&self, path: &ArcPath) -> Option<u64> {
    if let Ok(info) = self.fs.metadata(path.assert_utf8()).await {
      // return the larger of ctime and mtime
      if info.ctime_ms > info.mtime_ms {
        Some(info.ctime_ms)
      } else {
        Some(info.mtime_ms)
      }
    } else {
      None
    }
  }

  /// get path file package version strategy
  pub async fn package_version(&self, path: &ArcPath) -> Option<Strategy> {
    self
      .package_helper
      .package_version(path)
      .await
      .map(Strategy::PackageVersion)
  }

  /// get path file hash strategy
  pub async fn file_hash(&self, path: &ArcPath) -> Strategy {
    if let Some(ContentHash { hash, mtime }) = self.hash_helper.file_hash(path).await {
      Strategy::FileTimestampAndHash { mtime, hash }
    } else {
      Strategy::Missing
    }
  }

  /// get path file strategy
  pub async fn file_strategy(
    &self,
    path: &ArcPath,
    strategy_options: SnapshotStrategyOptions,
  ) -> Strategy {
    match (strategy_options.hash, strategy_options.timestamp) {
      (true, true) => self.file_hash(path).await,
      (true, false) => {
        if let Some(ContentHash { hash, .. }) = self.hash_helper.file_hash(path).await {
          Strategy::FileHash { hash }
        } else {
          Strategy::Missing
        }
      }
      (false, true) => {
        if let Some(mtime) = self.modified_time(path).await {
          Strategy::FileTimestamp { mtime }
        } else {
          Strategy::Missing
        }
      }
      (false, false) => Strategy::Failed,
    }
  }

  /// get path context hash strategy
  pub async fn dir_hash(&self, path: &ArcPath) -> Strategy {
    if let Some(ContentHash { hash, .. }) = self.hash_helper.dir_hash(path).await {
      Strategy::DirHash { hash }
    } else {
      Strategy::Failed
    }
  }

  /// get path context strategy
  pub async fn dir_strategy(
    &self,
    path: &ArcPath,
    strategy_options: SnapshotStrategyOptions,
  ) -> Strategy {
    match (strategy_options.hash, strategy_options.timestamp) {
      (true, true) => {
        let Some(TimestampHash {
          hash: timestamp_hash,
          ..
        }) = self.hash_helper.dir_timestamp_hash(path).await
        else {
          return Strategy::Failed;
        };
        if let Some(ContentHash { hash, .. }) = self.hash_helper.dir_hash(path).await {
          Strategy::DirTimestampAndHash {
            timestamp_hash,
            hash,
          }
        } else {
          Strategy::Failed
        }
      }
      (true, false) => self.dir_hash(path).await,
      (false, true) => {
        if let Some(TimestampHash {
          hash: timestamp_hash,
          ..
        }) = self.hash_helper.dir_timestamp_hash(path).await
        {
          Strategy::DirTimestamp { timestamp_hash }
        } else {
          Strategy::Failed
        }
      }
      (false, false) => Strategy::Failed,
    }
  }

  /// validate path file by target strategy
  pub async fn validate(&self, path: &ArcPath, strategy: &Strategy) -> ValidateResult {
    match strategy {
      Strategy::PackageVersion(version) => {
        let Some(ref cur_version) = self.package_helper.package_version(path).await else {
          return ValidateResult::Deleted;
        };
        if cur_version == version {
          ValidateResult::NoChanged
        } else {
          ValidateResult::Modified
        }
      }
      Strategy::FileHash { hash } => {
        let Some(ContentHash { hash: cur_hash, .. }) = self.hash_helper.file_hash(path).await
        else {
          return ValidateResult::Deleted;
        };
        if &cur_hash == hash {
          ValidateResult::NoChanged
        } else {
          ValidateResult::Modified
        }
      }
      Strategy::FileTimestamp { mtime } => {
        let Some(modified_time) = self.modified_time(path).await else {
          return ValidateResult::Deleted;
        };
        if &modified_time == mtime {
          ValidateResult::NoChanged
        } else {
          ValidateResult::Modified
        }
      }
      Strategy::FileTimestampAndHash { mtime, hash } => {
        let Some(modified_time) = self.modified_time(path).await else {
          return ValidateResult::Deleted;
        };
        if &modified_time == mtime {
          return ValidateResult::NoChanged;
        }
        let Some(ContentHash { hash: cur_hash, .. }) = self.hash_helper.file_hash(path).await
        else {
          return ValidateResult::Deleted;
        };
        if &cur_hash == hash {
          ValidateResult::NoChanged
        } else {
          ValidateResult::Modified
        }
      }
      Strategy::DirHash { hash } => {
        let Some(ContentHash { hash: cur_hash, .. }) = self.hash_helper.dir_hash(path).await else {
          return ValidateResult::Deleted;
        };
        if &cur_hash == hash {
          ValidateResult::NoChanged
        } else {
          ValidateResult::Modified
        }
      }
      Strategy::DirTimestamp { timestamp_hash } => {
        let Some(TimestampHash {
          hash: cur_timestamp_hash,
          ..
        }) = self.hash_helper.dir_timestamp_hash(path).await
        else {
          return ValidateResult::Deleted;
        };
        if &cur_timestamp_hash == timestamp_hash {
          ValidateResult::NoChanged
        } else {
          ValidateResult::Modified
        }
      }
      Strategy::DirTimestampAndHash {
        timestamp_hash,
        hash,
      } => {
        let Some(TimestampHash {
          hash: cur_timestamp_hash,
          ..
        }) = self.hash_helper.dir_timestamp_hash(path).await
        else {
          return ValidateResult::Deleted;
        };
        if &cur_timestamp_hash == timestamp_hash {
          return ValidateResult::NoChanged;
        }
        let Some(ContentHash { hash: cur_hash, .. }) = self.hash_helper.dir_hash(path).await else {
          return ValidateResult::Deleted;
        };
        if &cur_hash == hash {
          ValidateResult::NoChanged
        } else {
          ValidateResult::Modified
        }
      }
      Strategy::Missing => {
        if self.modified_time(path).await.is_some() {
          ValidateResult::Modified
        } else {
          ValidateResult::NoChanged
        }
      }
      Strategy::Failed => ValidateResult::Modified,
    }
  }
}

#[cfg(test)]
mod tests {
  use std::sync::Arc;

  use rspack_fs::{MemoryFileSystem, WritableFileSystem};
  use rspack_paths::ArcPath;

  use super::{Strategy, StrategyHelper, ValidateResult};

  #[tokio::test]
  async fn validate_package_version() {
    let fs = Arc::new(MemoryFileSystem::default());
    fs.create_dir_all("/packages/lib".into()).await.unwrap();
    fs.write(
      "/packages/lib/package.json".into(),
      r#"{"version": "1.0.0"}"#.as_bytes(),
    )
    .await
    .unwrap();
    fs.write("/packages/lib/file.js".into(), "abc".as_bytes())
      .await
      .unwrap();

    let strategy = Strategy::PackageVersion("1.0.0".into());
    let helper = StrategyHelper::new(fs.clone(), Default::default());
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/packages/lib/file.js"), &strategy)
        .await,
      ValidateResult::NoChanged
    ));

    let helper = StrategyHelper::new(fs.clone(), Default::default());
    fs.write(
      "/packages/lib/package.json".into(),
      r#"{"version": "1.2.0"}"#.as_bytes(),
    )
    .await
    .unwrap();
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/packages/lib/file.js"), &strategy)
        .await,
      ValidateResult::Modified
    ));

    let helper = StrategyHelper::new(fs.clone(), Default::default());
    fs.remove_file("/packages/lib/package.json".into())
      .await
      .unwrap();
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/packages/lib/file.js"), &strategy)
        .await,
      ValidateResult::Deleted
    ));
  }

  #[tokio::test]
  async fn validate_file_hash() {
    let fs = Arc::new(MemoryFileSystem::default());
    fs.create_dir_all("/".into()).await.unwrap();
    fs.write("/file1.js".into(), "abc".as_bytes())
      .await
      .unwrap();

    std::thread::sleep(std::time::Duration::from_millis(100));
    let helper = StrategyHelper::new(fs.clone(), Default::default());
    let strategy = helper.file_hash(&ArcPath::from("/file1.js")).await;
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/file1.js"), &strategy)
        .await,
      ValidateResult::NoChanged
    ));

    std::thread::sleep(std::time::Duration::from_millis(100));
    let helper = StrategyHelper::new(fs.clone(), Default::default());
    fs.write("/file1.js".into(), "abc".as_bytes())
      .await
      .unwrap();
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/file1.js"), &strategy)
        .await,
      ValidateResult::NoChanged
    ));

    std::thread::sleep(std::time::Duration::from_millis(100));
    let helper = StrategyHelper::new(fs.clone(), Default::default());
    fs.write("/file1.js".into(), "abcd".as_bytes())
      .await
      .unwrap();
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/file1.js"), &strategy)
        .await,
      ValidateResult::Modified
    ));

    std::thread::sleep(std::time::Duration::from_millis(100));
    let helper = StrategyHelper::new(fs.clone(), Default::default());
    fs.remove_file("/file1.js".into()).await.unwrap();
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/file1.js"), &strategy)
        .await,
      ValidateResult::Deleted
    ));
  }

  #[tokio::test]
  async fn validate_missing() {
    let fs = Arc::new(MemoryFileSystem::default());
    fs.create_dir_all("/".into()).await.unwrap();
    fs.write("/file1.js".into(), "abc".as_bytes())
      .await
      .unwrap();

    let helper = StrategyHelper::new(fs.clone(), Default::default());
    let strategy = Strategy::Missing;
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/file1.js"), &strategy)
        .await,
      ValidateResult::Modified
    ));

    std::thread::sleep(std::time::Duration::from_millis(100));
    fs.write("/file1.js".into(), "abcd".as_bytes())
      .await
      .unwrap();
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/file1.js"), &strategy)
        .await,
      ValidateResult::Modified
    ));

    std::thread::sleep(std::time::Duration::from_millis(100));
    fs.remove_file("/file1.js".into()).await.unwrap();
    assert!(matches!(
      helper
        .validate(&ArcPath::from("/file1.js"), &strategy)
        .await,
      ValidateResult::NoChanged
    ));
  }
}