dprint 0.53.2

Binary for dprint code formatter—a pluggable and configurable code formatting platform.
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
use anyhow::Result;
use anyhow::bail;
use parking_lot::RwLock;
use std::path::PathBuf;

use dprint_core::plugins::PluginInfo;

use super::PluginCacheManifest;
use super::PluginCacheManifestItem;
use super::cache_fs_locks::CacheFsLockPool;
use super::implementations::cleanup_plugin;
use super::implementations::get_file_path_from_plugin_info;
use super::implementations::setup_plugin;
use super::read_manifest;
use super::write_manifest;
use crate::environment::Environment;
use crate::plugins::PluginSourceReference;
use crate::utils::PathSource;
use crate::utils::PluginKind;
use crate::utils::get_bytes_hash;
use crate::utils::get_sha256_checksum;
use crate::utils::verify_sha256_checksum;

pub struct PluginCacheItem {
  pub file_path: PathBuf,
  pub info: PluginInfo,
}

pub struct PluginCache<TEnvironment: Environment> {
  environment: TEnvironment,
  manifest: ConcurrentPluginCacheManifest<TEnvironment>,
  fs_locks: CacheFsLockPool<TEnvironment>,
}

impl<TEnvironment> PluginCache<TEnvironment>
where
  TEnvironment: Environment,
{
  pub fn new(environment: TEnvironment) -> Self {
    PluginCache {
      manifest: ConcurrentPluginCacheManifest::new(environment.clone()),
      fs_locks: CacheFsLockPool::new(environment.clone()),
      environment,
    }
  }

  pub async fn forget_and_recreate(&self, source_reference: &PluginSourceReference) -> Result<PluginCacheItem> {
    let _setup_guard = self.fs_locks.lock(&source_reference.path_source).await;
    self.forget(source_reference).await?;
    self.get_plugin_cache_item(source_reference).await
  }

  pub async fn forget(&self, source_reference: &PluginSourceReference) -> Result<()> {
    let _setup_guard = self.fs_locks.lock(&source_reference.path_source).await;
    let removed_cache_item = self.manifest.remove(&source_reference.path_source)?;

    if let Some(cache_item) = removed_cache_item
      && let Err(err) = cleanup_plugin(&source_reference.path_source, &cache_item.info, &self.environment)
    {
      log_warn!(self.environment, "Error forgetting plugin: {:#}", err);
    }

    Ok(())
  }

  pub async fn get_plugin_cache_item(&self, source_reference: &PluginSourceReference) -> Result<PluginCacheItem> {
    // for local plugins, check if the file changed since it was cached
    match &source_reference.path_source {
      PathSource::Remote(_) => {}
      PathSource::Local(local) => {
        if let Some(manifest_item) = self.manifest.get(&source_reference.path_source)? {
          let file_bytes = self.environment.read_file_bytes(&local.path)?;
          let file_hash = get_bytes_hash(&file_bytes);
          let cache_file_hash = match &manifest_item.file_hash {
            Some(file_hash) => *file_hash,
            None => bail!("Expected to have the plugin file hash stored in the cache."),
          };

          if file_hash == cache_file_hash {
            return Ok(PluginCacheItem {
              file_path: get_file_path_from_plugin_info(&source_reference.path_source, &manifest_item.info, &self.environment)?,
              info: manifest_item.info,
            });
          } else {
            self.forget(source_reference).await?;
          }
        }
      }
    }

    self.get_plugin(source_reference).await
  }

  async fn get_plugin(&self, source_reference: &PluginSourceReference) -> Result<PluginCacheItem> {
    if let Some(item) = self.get_plugin_cache_item_from_cache(&source_reference.path_source)? {
      return Ok(item);
    }

    // prevent multiple processes from downloading the same plugin at the same time
    let _setup_guard = self.fs_locks.lock(&source_reference.path_source).await;

    // once in the lock, attempt to reload and see if the item is in the cache now
    self.manifest.reload_from_disk();
    if let Some(item) = self.get_plugin_cache_item_from_cache(&source_reference.path_source)? {
      return Ok(item);
    }

    // get bytes (resolved_source may differ from the original due to redirects)
    let (file_bytes, resolved_source) = match &source_reference.path_source {
      PathSource::Remote(remote) => {
        let (url, file) = self.environment.download_file_err_404(&remote.url).await?;
        (file.content, PathSource::new_remote(url.into_owned()))
      }
      PathSource::Local(local) => {
        let bytes = self.environment.read_file_bytes(&local.path)?;
        (bytes, source_reference.path_source.clone())
      }
    };

    // check checksum only if provided (not required for Wasm plugins)
    if let Some(checksum) = &source_reference.checksum {
      if let Err(err) = verify_sha256_checksum(&file_bytes, checksum) {
        bail!(
          "Invalid checksum specified in configuration file. Check the plugin's release notes for what the expected checksum is.\n\n{:#}",
          err
        );
      }
    } else if source_reference.path_source.plugin_kind() != Some(PluginKind::Wasm) {
      bail!(
        concat!(
          "The plugin must have a checksum specified for security reasons ",
          "since it is not a Wasm plugin. Check the plugin's release notes for what ",
          "the checksum is or if you trust the source, you may specify: {}@{}"
        ),
        source_reference.path_source.display(),
        get_sha256_checksum(&file_bytes),
      );
    }

    let file_hash = match &resolved_source {
      PathSource::Local(_) => Some(get_bytes_hash(&file_bytes)),
      PathSource::Remote(_) => None,
    };
    let setup_result = setup_plugin(&source_reference.path_source, &resolved_source, file_bytes, &self.environment).await?;
    let cache_item = PluginCacheManifestItem {
      info: setup_result.plugin_info.clone(),
      file_hash,
      created_time: self.environment.get_time_secs(),
    };

    self.manifest.add(&source_reference.path_source, cache_item)?;

    Ok(PluginCacheItem {
      file_path: setup_result.file_path,
      info: setup_result.plugin_info,
    })
  }

  fn get_plugin_cache_item_from_cache(&self, path_source: &PathSource) -> Result<Option<PluginCacheItem>> {
    if let Some(item) = self.manifest.get(path_source)? {
      Ok(Some(PluginCacheItem {
        file_path: get_file_path_from_plugin_info(path_source, &item.info, &self.environment)?,
        info: item.info,
      }))
    } else {
      Ok(None)
    }
  }
}

struct ConcurrentPluginCacheManifest<TEnvironment: Environment> {
  environment: TEnvironment,
  manifest: RwLock<PluginCacheManifest>,
}

impl<TEnvironment: Environment> ConcurrentPluginCacheManifest<TEnvironment> {
  pub fn new(environment: TEnvironment) -> Self {
    let manifest = RwLock::new(read_manifest(&environment));
    Self { environment, manifest }
  }

  pub fn get(&self, path_source: &PathSource) -> Result<Option<PluginCacheManifestItem>> {
    let cache_key = self.get_cache_key(path_source)?;
    Ok(self.manifest.read().get_item(&cache_key).map(|x| x.to_owned()))
  }

  pub fn add(&self, path_source: &PathSource, cache_item: PluginCacheManifestItem) -> Result<()> {
    let mut manifest = self.manifest.write();
    manifest.add_item(self.get_cache_key(path_source)?, cache_item);
    write_manifest(&manifest, &self.environment)?;
    Ok(())
  }

  pub fn remove(&self, path_source: &PathSource) -> Result<Option<PluginCacheManifestItem>> {
    let cache_key = self.get_cache_key(path_source)?;
    let mut manifest = self.manifest.write();
    let cache_item = manifest.remove_item(&cache_key);
    write_manifest(&manifest, &self.environment)?;
    Ok(cache_item)
  }

  pub fn reload_from_disk(&self) {
    // ensure the lock is held while reading from the file system
    // in order to prevent another thread writing to the file system
    // at the same time
    let mut manifest = self.manifest.write();
    *manifest = read_manifest(&self.environment);
  }

  fn get_cache_key(&self, path_source: &PathSource) -> Result<String> {
    Ok(match path_source {
      PathSource::Remote(remote_source) => format!("remote:{}", remote_source.url.as_str()),
      PathSource::Local(local_source) => {
        let absolute_path = self.environment.canonicalize(&local_source.path)?;
        format!("local:{}", absolute_path.to_string_lossy())
      }
    })
  }
}

#[cfg(test)]
mod test {
  use super::*;
  use crate::environment::TestEnvironment;
  use crate::plugins::PluginSourceReference;
  use crate::plugins::implementations::WASMER_COMPILER_VERSION;
  use crate::test_helpers::WASM_PLUGIN_0_1_0_BYTES;
  use crate::test_helpers::WASM_PLUGIN_BYTES;
  use anyhow::Result;
  use pretty_assertions::assert_eq;
  use std::path::PathBuf;

  #[tokio::test]
  async fn should_download_remote_file() -> Result<()> {
    let environment = TestEnvironment::new();
    environment.add_remote_file("https://plugins.dprint.dev/test.wasm", WASM_PLUGIN_BYTES);
    environment.set_cpu_arch("aarch64");

    let plugin_cache = PluginCache::new(environment.clone());
    let plugin_source = PluginSourceReference::new_remote_from_str("https://plugins.dprint.dev/test.wasm");
    let file_path = plugin_cache.get_plugin_cache_item(&plugin_source).await?.file_path;
    let expected_file_path = PathBuf::from("/cache")
      .join("plugins")
      .join("test-plugin")
      .join(format!("0.2.0-{WASMER_COMPILER_VERSION}-aarch64"));

    assert_eq!(file_path, expected_file_path);
    assert_eq!(environment.take_stderr_messages(), vec!["Compiling https://plugins.dprint.dev/test.wasm"]);

    // should be the same when requesting it again
    let file_path = plugin_cache.get_plugin_cache_item(&plugin_source).await?.file_path;
    assert_eq!(file_path, expected_file_path);

    // should have saved the manifest
    assert_eq!(
      environment.read_file(&environment.get_cache_dir().join("plugin-cache-manifest.json")).unwrap(),
      serde_json::json!({
        "schemaVersion": 8,
        "wasmCacheVersion": WASMER_COMPILER_VERSION,
        "plugins": {
          "remote:https://plugins.dprint.dev/test.wasm": {
            "createdTime": 123456,
            "info": {
              "name": "test-plugin",
              "version": "0.2.0",
              "configKey": "test-plugin",
              "helpUrl": "https://dprint.dev/plugins/test",
              "configSchemaUrl": "https://plugins.dprint.dev/test/schema.json",
              "updateUrl": "https://plugins.dprint.dev/dprint/test-plugin/latest.json"
            }
          }
        }
      })
      .to_string(),
    );

    // should forget it afterwards
    plugin_cache.forget(&plugin_source).await.unwrap();

    assert_eq!(environment.path_exists(&file_path), false);
    // should have saved the manifest
    assert_eq!(
      environment.read_file(&environment.get_cache_dir().join("plugin-cache-manifest.json")).unwrap(),
      serde_json::json!({
        "schemaVersion": 8,
        "wasmCacheVersion": WASMER_COMPILER_VERSION,
        "plugins": {}
      })
      .to_string(),
    );

    Ok(())
  }

  #[tokio::test]
  async fn should_cache_local_file() -> Result<()> {
    let environment = TestEnvironment::new();
    let original_file_path = PathBuf::from("/test.wasm");
    environment.write_file_bytes(&original_file_path, &WASM_PLUGIN_BYTES).unwrap();

    let plugin_cache = PluginCache::new(environment.clone());
    let plugin_source = PluginSourceReference::new_local(original_file_path.clone());
    let file_path = plugin_cache.get_plugin_cache_item(&plugin_source).await?.file_path;
    let expected_file_path = PathBuf::from("/cache")
      .join("plugins")
      .join("test-plugin")
      .join(format!("0.2.0-{WASMER_COMPILER_VERSION}-x86_64"));

    assert_eq!(file_path, expected_file_path);

    assert_eq!(environment.take_stderr_messages(), vec!["Compiling /test.wasm"]);

    // should be the same when requesting it again
    let file_path = plugin_cache.get_plugin_cache_item(&plugin_source).await?.file_path;
    assert_eq!(file_path, expected_file_path);

    // should have saved the manifest
    let expected_text = serde_json::json!({
      "schemaVersion": 8,
      "wasmCacheVersion": WASMER_COMPILER_VERSION,
      "plugins": {
        "local:/test.wasm": {
          "createdTime": 123456,
          "fileHash": get_bytes_hash(&WASM_PLUGIN_BYTES),
          "info": {
            "name": "test-plugin",
            "version": "0.2.0",
            "configKey": "test-plugin",
            "helpUrl": "https://dprint.dev/plugins/test",
            "configSchemaUrl": "https://plugins.dprint.dev/test/schema.json",
            "updateUrl": "https://plugins.dprint.dev/dprint/test-plugin/latest.json"
          }
        }
      }
    });
    assert_eq!(
      environment.read_file(&environment.get_cache_dir().join("plugin-cache-manifest.json")).unwrap(),
      expected_text.to_string(),
    );

    assert_eq!(environment.take_stderr_messages().len(), 0); // no logs, nothing changed

    // update the file bytes
    environment.write_file_bytes(&original_file_path, &WASM_PLUGIN_0_1_0_BYTES).unwrap();

    // should update the cache with the new file
    let expected_file_path = PathBuf::from("/cache")
      .join("plugins")
      .join("test-plugin")
      .join(format!("0.1.0-{WASMER_COMPILER_VERSION}-x86_64"));
    let file_path = plugin_cache
      .get_plugin_cache_item(&PluginSourceReference::new_local(original_file_path.clone()))
      .await?
      .file_path;
    assert_eq!(file_path, expected_file_path);

    let expected_text = serde_json::json!({
      "schemaVersion": 8,
      "wasmCacheVersion": WASMER_COMPILER_VERSION,
      "plugins": {
        "local:/test.wasm": {
          "createdTime": 123456,
          "fileHash": get_bytes_hash(&WASM_PLUGIN_0_1_0_BYTES),
          "info": {
            "name": "test-plugin",
            "version": "0.1.0",
            "configKey": "test-plugin",
            "helpUrl": "https://dprint.dev/plugins/test",
            "configSchemaUrl": "https://plugins.dprint.dev/test/schema.json",
            "updateUrl": "https://plugins.dprint.dev/dprint/test-plugin/latest.json"
          }
        }
      }
    });
    assert_eq!(
      environment.read_file(&environment.get_cache_dir().join("plugin-cache-manifest.json")).unwrap(),
      expected_text.to_string()
    );

    assert_eq!(environment.take_stderr_messages(), vec!["Compiling /test.wasm"]);

    // should forget it afterwards
    plugin_cache.forget(&plugin_source).await.unwrap();

    assert_eq!(environment.path_exists(&file_path), false);
    // should have saved the manifest
    assert_eq!(
      environment.read_file(&environment.get_cache_dir().join("plugin-cache-manifest.json")).unwrap(),
      serde_json::json!({
        "schemaVersion": 8,
        "wasmCacheVersion": WASMER_COMPILER_VERSION,
        "plugins": {}
      })
      .to_string(),
    );

    Ok(())
  }

  #[tokio::test]
  async fn should_resolve_redirected_process_plugin_with_relative_urls() -> Result<()> {
    let environment = TestEnvironment::new();

    // create a plugin.json that uses a relative path for the zip reference
    let zip_bytes = &*crate::test_helpers::PROCESS_PLUGIN_ZIP_BYTES;
    let zip_checksum = crate::test_helpers::PROCESS_PLUGIN_ZIP_CHECKSUM.as_str();
    let plugin_json = format!(
      r#"{{
  "schemaVersion": 2,
  "name": "test-process-plugin",
  "version": "0.1.0",
  "linux-x86_64": {{ "reference": "./test-process-plugin.zip", "checksum": "{zip_checksum}" }},
  "linux-aarch64": {{ "reference": "./test-process-plugin.zip", "checksum": "{zip_checksum}" }},
  "darwin-x86_64": {{ "reference": "./test-process-plugin.zip", "checksum": "{zip_checksum}" }},
  "darwin-aarch64": {{ "reference": "./test-process-plugin.zip", "checksum": "{zip_checksum}" }},
  "windows-x86_64": {{ "reference": "./test-process-plugin.zip", "checksum": "{zip_checksum}" }},
  "windows-aarch64": {{ "reference": "./test-process-plugin.zip", "checksum": "{zip_checksum}" }}
}}"#,
    );

    // host the plugin.json at the CDN (redirect target)
    let cdn_plugin_url = "https://cdn.example.com/plugins/v1/test-process.json";
    environment.add_remote_file_bytes(cdn_plugin_url, plugin_json.as_bytes().to_vec());
    // host the zip relative to the plugin.json on the CDN
    environment.add_remote_file_bytes("https://cdn.example.com/plugins/v1/test-process-plugin.zip", zip_bytes.to_vec());
    // the original URL redirects to the CDN
    let original_url = "https://plugins.example.com/test-process.json";
    environment.add_remote_file_redirect(original_url, cdn_plugin_url);

    let plugin_json_checksum = crate::utils::get_sha256_checksum(plugin_json.as_bytes());
    let plugin_cache = PluginCache::new(environment.clone());
    let plugin_source = PluginSourceReference {
      path_source: PathSource::new_remote(url::Url::parse(original_url).unwrap()),
      checksum: Some(plugin_json_checksum),
    };
    let cache_item = plugin_cache.get_plugin_cache_item(&plugin_source).await?;
    assert_eq!(cache_item.info.name, "test-process-plugin");
    assert_eq!(cache_item.info.version, "0.1.0");

    Ok(())
  }
}