-
-
Notifications
You must be signed in to change notification settings - Fork 222
/
file_upload.rs
643 lines (555 loc) · 19.5 KB
/
file_upload.rs
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Searches, processes and uploads release files.
use std::collections::HashMap;
use std::fmt;
use std::io::BufWriter;
use std::path::PathBuf;
use std::str;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{anyhow, bail, Result};
use console::style;
use parking_lot::RwLock;
use rayon::prelude::*;
use rayon::ThreadPoolBuilder;
use sentry::types::DebugId;
use sha1_smol::Digest;
use symbolic::common::ByteView;
use symbolic::debuginfo::sourcebundle::{SourceBundleWriter, SourceFileInfo, SourceFileType};
use url::Url;
use crate::api::NewRelease;
use crate::api::{Api, ChunkUploadCapability, ChunkUploadOptions, ProgressBarMode};
use crate::constants::DEFAULT_MAX_WAIT;
use crate::utils::chunks::{upload_chunks, Chunk, ASSEMBLE_POLL_INTERVAL};
use crate::utils::fs::{get_sha1_checksum, get_sha1_checksums, TempFile};
use crate::utils::progress::{ProgressBar, ProgressStyle};
/// Fallback concurrency for release file uploads.
static DEFAULT_CONCURRENCY: usize = 4;
/// Old versions of Sentry cannot assemble artifact bundles straight away, they require
/// that those bundles are associated to a release.
///
/// This function checks whether the configured server supports artifact bundles
/// and only creates a release if the server requires that.
pub fn initialize_legacy_release_upload(context: &UploadContext) -> Result<()> {
// if the remote sentry service supports artifact bundles, we don't
// need to do anything here. Artifact bundles will also only work
// if a project is provided which is technically unnecessary for the
// legacy upload though it will unlikely to be what users want.
if context.project.is_some()
&& context.chunk_upload_options.map_or(false, |x| {
x.supports(ChunkUploadCapability::ArtifactBundles)
|| x.supports(ChunkUploadCapability::ArtifactBundlesV2)
})
{
return Ok(());
}
// TODO: make this into an error later down the road
if context.project.is_none() {
eprintln!(
"{}",
style(
"warning: no project specified. \
While this upload will succeed it will be unlikely that \
this is what you wanted. Future versions of sentry will \
require a project to be set."
)
.red()
);
}
if let Some(version) = context.release {
let api = Api::current();
api.new_release(
context.org,
&NewRelease {
version: version.to_string(),
projects: context.project.map(|x| x.to_string()).into_iter().collect(),
..Default::default()
},
)?;
} else {
bail!("This version of Sentry does not support artifact bundles. A release slug is required (provide with --release)");
}
Ok(())
}
#[derive(Debug, Clone)]
pub struct UploadContext<'a> {
pub org: &'a str,
pub project: Option<&'a str>,
pub release: Option<&'a str>,
pub dist: Option<&'a str>,
pub note: Option<&'a str>,
pub wait: bool,
pub dedupe: bool,
pub chunk_upload_options: Option<&'a ChunkUploadOptions>,
}
impl<'a> UploadContext<'a> {
pub fn release(&self) -> Result<&str> {
self.release
.ok_or_else(|| anyhow!("A release slug is required (provide with --release)"))
}
}
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
pub enum LogLevel {
Warning,
Error,
}
impl fmt::Display for LogLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
LogLevel::Warning => write!(f, "warning"),
LogLevel::Error => write!(f, "error"),
}
}
}
#[derive(Clone, Debug)]
pub struct SourceFile {
pub url: String,
pub path: PathBuf,
pub contents: Vec<u8>,
pub ty: SourceFileType,
pub headers: Vec<(String, String)>,
pub messages: Vec<(LogLevel, String)>,
pub already_uploaded: bool,
}
impl SourceFile {
/// Calculates and returns the SHA1 checksum of the file.
pub fn checksum(&self) -> Result<Digest> {
get_sha1_checksum(&*self.contents)
}
pub fn log(&mut self, level: LogLevel, msg: String) {
self.messages.push((level, msg));
}
pub fn warn(&mut self, msg: String) {
self.log(LogLevel::Warning, msg);
}
pub fn error(&mut self, msg: String) {
self.log(LogLevel::Error, msg);
}
}
pub type SourceFiles = HashMap<String, SourceFile>;
pub struct FileUpload<'a> {
context: &'a UploadContext<'a>,
files: SourceFiles,
}
impl<'a> FileUpload<'a> {
pub fn new(context: &'a UploadContext) -> Self {
FileUpload {
context,
files: HashMap::new(),
}
}
pub fn files(&mut self, files: &SourceFiles) -> &mut Self {
for (k, v) in files {
if !v.already_uploaded {
self.files.insert(k.to_owned(), v.to_owned());
}
}
self
}
pub fn upload(&self) -> Result<()> {
initialize_legacy_release_upload(self.context)?;
if let Some(chunk_options) = self.context.chunk_upload_options {
if chunk_options.supports(ChunkUploadCapability::ReleaseFiles) {
return upload_files_chunked(self.context, &self.files, chunk_options);
}
}
// Do not permit uploads of more than 20k files if the server does not
// support artifact bundles. This is a termporary downside protection to
// protect users from uploading more sources than we support.
if self.files.len() > 20_000 {
bail!(
"Too many sources: {} exceeds maximum allowed files per release",
&self.files.len()
);
}
let concurrency = self
.context
.chunk_upload_options
.map_or(DEFAULT_CONCURRENCY, |o| usize::from(o.concurrency));
upload_files_parallel(self.context, &self.files, concurrency)
}
pub fn build_jvm_bundle(&self, debug_id: Option<DebugId>) -> Result<TempFile> {
build_artifact_bundle(self.context, &self.files, debug_id)
}
}
fn upload_files_parallel(
context: &UploadContext,
files: &SourceFiles,
num_threads: usize,
) -> Result<()> {
let api = Api::current();
let release = context.release()?;
// get a list of release files first so we know the file IDs of
// files that already exist.
let release_files: HashMap<_, _> = api
.list_release_files(context.org, context.project, release)?
.into_iter()
.map(|artifact| ((artifact.dist, artifact.name), artifact.id))
.collect();
println!(
"{} Uploading source maps for release {}",
style(">").dim(),
style(release).cyan()
);
let progress_style = ProgressStyle::default_bar().template(&format!(
"{} Uploading {} source map{}...\
\n{{wide_bar}} {{bytes}}/{{total_bytes}} ({{eta}})",
style(">").dim(),
style(files.len().to_string()).yellow(),
if files.len() == 1 { "" } else { "s" }
));
let total_bytes = files.values().map(|file| file.contents.len()).sum();
let files = files.iter().collect::<Vec<_>>();
let pb = Arc::new(ProgressBar::new(total_bytes));
pb.set_style(progress_style);
let pool = ThreadPoolBuilder::new().num_threads(num_threads).build()?;
let bytes = Arc::new(RwLock::new(vec![0u64; files.len()]));
pool.install(|| {
files
.into_par_iter()
.enumerate()
.map(|(index, (_, file))| -> Result<()> {
let api = Api::current();
let mode = ProgressBarMode::Shared((
pb.clone(),
file.contents.len() as u64,
index,
bytes.clone(),
));
if let Some(old_id) =
release_files.get(&(context.dist.map(|x| x.into()), file.url.clone()))
{
api.delete_release_file(context.org, context.project, release, old_id)
.ok();
}
api.upload_release_file(
context,
&file.contents,
&file.url,
Some(file.headers.as_slice()),
mode,
)?;
Ok(())
})
.collect::<Result<(), _>>()
})?;
pb.finish_and_clear();
print_upload_context_details(context);
Ok(())
}
fn poll_assemble(
checksum: Digest,
chunks: &[Digest],
context: &UploadContext,
options: &ChunkUploadOptions,
) -> Result<()> {
let progress_style = ProgressStyle::default_spinner().template("{spinner} Processing files...");
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(100);
pb.set_style(progress_style);
let assemble_start = Instant::now();
let max_wait = match options.max_wait {
0 => DEFAULT_MAX_WAIT,
secs => Duration::from_secs(secs),
};
let api = Api::current();
let use_artifact_bundle = (options.supports(ChunkUploadCapability::ArtifactBundles)
|| options.supports(ChunkUploadCapability::ArtifactBundlesV2))
&& context.project.is_some();
let response = loop {
// prefer standalone artifact bundle upload over legacy release based upload
let response = if use_artifact_bundle {
api.assemble_artifact_bundle(
context.org,
vec![context.project.unwrap().to_string()],
checksum,
chunks,
context.release,
context.dist,
)?
} else {
api.assemble_release_artifacts(context.org, context.release()?, checksum, chunks)?
};
// Poll until there is a response, unless the user has specified to skip polling. In
// that case, we return the potentially partial response from the server. This might
// still contain a cached error.
if !context.wait || response.state.is_finished() {
break response;
}
if assemble_start.elapsed() > max_wait {
break response;
}
std::thread::sleep(ASSEMBLE_POLL_INTERVAL);
};
if response.state.is_err() {
let message = response.detail.as_deref().unwrap_or("unknown error");
bail!("Failed to process uploaded files: {}", message);
}
pb.finish_with_duration("Processing");
if response.state.is_pending() {
if context.wait {
bail!("Failed to process files in {}s", max_wait.as_secs());
} else {
println!(
"{} File upload complete (processing pending on server)",
style(">").dim()
);
}
} else {
println!("{} File processing complete", style(">").dim());
}
print_upload_context_details(context);
Ok(())
}
fn upload_files_chunked(
context: &UploadContext,
files: &SourceFiles,
options: &ChunkUploadOptions,
) -> Result<()> {
let archive = build_artifact_bundle(context, files, None)?;
let progress_style =
ProgressStyle::default_spinner().template("{spinner} Optimizing bundle for upload...");
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(100);
pb.set_style(progress_style);
let view = ByteView::open(archive.path())?;
let (checksum, checksums) = get_sha1_checksums(&view, options.chunk_size)?;
let mut chunks = view
.chunks(options.chunk_size as usize)
.zip(checksums.iter())
.map(|(data, checksum)| Chunk((*checksum, data)))
.collect::<Vec<_>>();
pb.finish_with_duration("Optimizing");
let progress_style = ProgressStyle::default_bar().template(&format!(
"{} Uploading files...\
\n{{wide_bar}} {{bytes}}/{{total_bytes}} ({{eta}})",
style(">").dim(),
));
// Filter out chunks that are already on the server. This only matters if the server supports
// `ArtifactBundlesV2`, otherwise the `missing_chunks` field is meaningless.
if options.supports(ChunkUploadCapability::ArtifactBundlesV2) && context.project.is_some() {
let api = Api::current();
let response = api.assemble_artifact_bundle(
context.org,
vec![context.project.unwrap().to_string()],
checksum,
&checksums,
context.release,
context.dist,
)?;
chunks.retain(|Chunk((digest, _))| response.missing_chunks.contains(digest));
};
if !chunks.is_empty() {
upload_chunks(&chunks, options, progress_style)?;
println!("{} Uploaded files to Sentry", style(">").dim());
} else {
println!(
"{} Nothing to upload, all files are on the server",
style(">").dim()
);
}
poll_assemble(checksum, &checksums, context, options)
}
fn build_debug_id(files: &SourceFiles) -> DebugId {
let mut sorted_files = Vec::from_iter(files);
sorted_files.sort_by_key(|x| x.0);
let mut hash = sha1_smol::Sha1::new();
for (path, source_file) in sorted_files {
hash.update(path.as_bytes());
if let Some(debug_id) = source_file
.headers
.iter()
.filter_map(|(k, v)| (k == "debug_id").then_some(v))
.next()
{
hash.update(debug_id.as_bytes());
} else {
hash.update(&[0u8; 16]);
}
hash.update(&source_file.contents);
}
let mut sha1_bytes = [0u8; 16];
sha1_bytes.copy_from_slice(&hash.digest().bytes()[..16]);
DebugId::from_uuid(uuid::Builder::from_sha1_bytes(sha1_bytes).into_uuid())
}
fn build_artifact_bundle(
context: &UploadContext,
files: &SourceFiles,
debug_id: Option<DebugId>,
) -> Result<TempFile> {
let progress_style = ProgressStyle::default_bar().template(
"{prefix:.dim} Bundling files for upload... {msg:.dim}\
\n{wide_bar} {pos}/{len}",
);
let pb = ProgressBar::new(files.len());
pb.set_style(progress_style);
pb.set_prefix(">");
let archive = TempFile::create()?;
let mut bundle = SourceBundleWriter::start(BufWriter::new(archive.open()?))?;
// artifact bundles get a random UUID as debug id
let debug_id = debug_id.unwrap_or_else(|| build_debug_id(files));
bundle.set_attribute("debug_id", debug_id.to_string());
if let Some(note) = context.note {
bundle.set_attribute("note", note.to_owned());
}
bundle.set_attribute("org".to_owned(), context.org.to_owned());
if let Some(project) = context.project {
bundle.set_attribute("project".to_owned(), project.to_owned());
}
if let Some(release) = context.release {
bundle.set_attribute("release".to_owned(), release.to_owned());
}
if let Some(dist) = context.dist {
bundle.set_attribute("dist".to_owned(), dist.to_owned());
}
let mut files_sorted = files.values().collect::<Vec<_>>();
files_sorted.sort_by_key(|file| &file.url[..]);
for file in files_sorted {
pb.inc(1);
pb.set_message(&file.url);
let mut info = SourceFileInfo::new();
info.set_ty(file.ty);
info.set_url(file.url.clone());
for (k, v) in &file.headers {
info.add_header(k.clone(), v.clone());
}
let bundle_path = url_to_bundle_path(&file.url)?;
bundle.add_file(bundle_path, file.contents.as_slice(), info)?;
}
bundle.finish()?;
pb.finish_with_duration("Bundling");
println!(
"{} Bundled {} {} for upload",
style(">").dim(),
style(files.len()).yellow(),
match files.len() {
1 => "file",
_ => "files",
}
);
println!(
"{} Bundle ID: {}",
style(">").dim(),
style(debug_id).yellow(),
);
Ok(archive)
}
fn url_to_bundle_path(url: &str) -> Result<String> {
let base = Url::parse("http://~").unwrap();
let url = if let Some(rest) = url.strip_prefix("~/") {
base.join(rest)?
} else {
base.join(url)?
};
let mut path = url.path().to_string();
if let Some(fragment) = url.fragment() {
path = format!("{path}#{fragment}");
}
if path.starts_with('/') {
path.remove(0);
}
Ok(match url.host_str() {
Some("~") => format!("_/_/{path}"),
Some(host) => format!("{}/{}/{}", url.scheme(), host, path),
None => format!("{}/_/{}", url.scheme(), path),
})
}
fn print_upload_context_details(context: &UploadContext) {
println!(
"{} {}",
style("> Organization:").dim(),
style(context.org).yellow()
);
println!(
"{} {}",
style("> Project:").dim(),
style(context.project.unwrap_or("None")).yellow()
);
println!(
"{} {}",
style("> Release:").dim(),
style(context.release.unwrap_or("None")).yellow()
);
println!(
"{} {}",
style("> Dist:").dim(),
style(context.dist.unwrap_or("None")).yellow()
);
let upload_type = match context.chunk_upload_options {
None => "single file",
Some(opts)
if opts.supports(ChunkUploadCapability::ArtifactBundles)
|| opts.supports(ChunkUploadCapability::ArtifactBundlesV2) =>
{
"artifact bundle"
}
_ => "release bundle",
};
println!(
"{} {}",
style("> Upload type:").dim(),
style(upload_type).yellow()
);
}
#[cfg(test)]
mod tests {
use sha1_smol::Sha1;
use super::*;
#[test]
fn test_url_to_bundle_path() {
assert_eq!(url_to_bundle_path("~/bar").unwrap(), "_/_/bar");
assert_eq!(url_to_bundle_path("~/foo/bar").unwrap(), "_/_/foo/bar");
assert_eq!(
url_to_bundle_path("~/dist/js/bundle.js.map").unwrap(),
"_/_/dist/js/bundle.js.map"
);
assert_eq!(
url_to_bundle_path("~/babel.config.js").unwrap(),
"_/_/babel.config.js"
);
assert_eq!(url_to_bundle_path("~/#/bar").unwrap(), "_/_/#/bar");
assert_eq!(url_to_bundle_path("~/foo/#/bar").unwrap(), "_/_/foo/#/bar");
assert_eq!(
url_to_bundle_path("~/dist/#js/bundle.js.map").unwrap(),
"_/_/dist/#js/bundle.js.map"
);
assert_eq!(
url_to_bundle_path("~/#foo/babel.config.js").unwrap(),
"_/_/#foo/babel.config.js"
);
}
#[test]
fn build_artifact_bundle_deterministic() {
let context = UploadContext {
org: "wat-org",
project: Some("wat-project"),
release: None,
dist: None,
note: None,
wait: false,
dedupe: true,
chunk_upload_options: None,
};
let source_files = ["bundle.min.js.map", "vendor.min.js.map"]
.into_iter()
.map(|name| {
let file = SourceFile {
url: format!("~/{name}"),
path: format!("tests/integration/_fixtures/{name}").into(),
contents: std::fs::read(format!("tests/integration/_fixtures/{name}")).unwrap(),
ty: SourceFileType::SourceMap,
headers: Default::default(),
messages: Default::default(),
already_uploaded: false,
};
(format!("~/{name}"), file)
})
.collect();
let file = build_artifact_bundle(&context, &source_files, None).unwrap();
let buf = std::fs::read(file.path()).unwrap();
let hash = Sha1::from(buf);
assert_eq!(
hash.digest().to_string(),
"3f1ae634a707ec4bc01cf227589e24e4deac4a19"
);
}
}