-
-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathexplain.rs
More file actions
521 lines (458 loc) · 16.7 KB
/
explain.rs
File metadata and controls
521 lines (458 loc) · 16.7 KB
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
#![expect(clippy::unwrap_used, reason = "deprecated command")]
use std::io::Read as _;
use std::path::Path;
use anyhow::{bail, format_err, Result};
use clap::{Arg, ArgAction, ArgMatches, Command};
use console::style;
use sentry::protocol::{Frame, Stacktrace};
use url::Url;
use crate::api::{Api, Artifact, ProcessedEvent};
use crate::config::Config;
use crate::utils::fs::TempFile;
use crate::utils::system::QuietExit;
use super::resolve::print_source;
pub fn make_command(command: Command) -> Command {
command
.about("[DEPRECATED] Explain why sourcemaps are not working for a given event.")
.hide(true)
.alias("why")
.arg(
Arg::new("event")
.value_name("EVENT_ID")
.required(true)
.help("ID of an event to be explained."),
)
.arg(
Arg::new("frame")
.long("frame")
.default_value("0")
.value_parser(clap::value_parser!(usize))
.help("Position of the frame that should be used for source map resolution."),
)
.arg(
Arg::new("force")
.long("force")
.short('f')
.action(ArgAction::SetTrue)
.help("Force full validation flow, even when event is already source mapped."),
)
}
fn tip<S>(msg: S)
where
S: std::fmt::Display,
{
println!("{}", style(format!("ℹ {msg}")).blue());
}
fn success<S>(msg: S)
where
S: std::fmt::Display,
{
println!("{}", style(format!("✔ {msg}")).green());
}
fn warning<S>(msg: S)
where
S: std::fmt::Display,
{
println!("{}", style(format!("⚠ {msg}")).yellow());
}
fn error<S>(msg: S)
where
S: std::fmt::Display,
{
println!("{}", style(format!("✖ {msg}")).red());
}
fn fetch_event(org: &str, project: &str, event_id: &str) -> Result<ProcessedEvent> {
match Api::current()
.authenticated()?
.get_event(org, Some(project), event_id)?
{
Some(event) => {
success(format!("Fetched data for event: {event_id}"));
Ok(event)
}
None => {
error(format!("Could not retrieve event {event_id}"));
tip("Make sure that event ID you used is valid.");
Err(QuietExit(1).into())
}
}
}
fn extract_in_app_frames(stacktrace: &Stacktrace) -> Vec<&Frame> {
stacktrace
.frames
.iter()
.filter(|frame| frame.in_app.unwrap_or(false))
.collect()
}
fn extract_nth_frame(stacktrace: &Stacktrace, position: usize) -> Result<&Frame> {
let mut in_app_frames = extract_in_app_frames(stacktrace);
if in_app_frames.is_empty() {
bail!("Event exception stacktrace has no in_app frames");
}
// Frames are in bottom-up order.
in_app_frames.reverse();
let frame = in_app_frames
.get(position)
.ok_or_else(|| format_err!("Selected frame ({position}) is missing."))?;
let abs_path = frame
.abs_path
.as_ref()
.ok_or_else(|| format_err!("Selected frame ({position}) is missing an abs_path"))?;
if let Ok(abs_path) = Url::parse(abs_path) {
if Path::new(abs_path.path()).extension().is_none() {
bail!("Selected frame ({position}) of event exception originates from the <script> tag, its not possible to resolve source maps");
}
} else {
bail!("Event exception stacktrace selected frame ({position}) has incorrect abs_path (valid url is required). Found {abs_path}");
}
Ok(frame)
}
fn fetch_release_artifacts(org: &str, project: &str, release: &str) -> Result<Vec<Artifact>> {
Api::current().authenticated()?.list_release_files(org, Some(project), release).map(|artifacts| {
if artifacts.is_empty() {
error("Release has no artifacts uploaded");
tip("https://docs.sentry.io/platforms/javascript/sourcemaps/troubleshooting_js/#verify-artifacts-are-uploaded");
return Err(QuietExit(1).into());
}
Ok(artifacts)
})?
}
// Try to find an artifact which matches the path part of the url extracted from the stacktrace frame,
// prefixed with the default `~/`, which is a "glob-like" pattern for matching any hostname.
fn find_matching_artifact(artifacts: &[Artifact], path: &str) -> Result<Artifact> {
let full_match = artifacts.iter().find(|a| a.name == path);
let partial_match = artifacts
.iter()
.find(|a| a.name.ends_with(path.split('/').next_back().unwrap()));
if full_match.is_none() {
error(format!("Uploaded artifacts do not include entry: {path}"));
if let Some(pm) = partial_match {
tip(format!(
"Found entry with partially matching filename: {}. \
Make sure that that --url-prefix is set correctly.",
pm.name,
));
}
return Err(QuietExit(1).into());
}
success(format!("Artifact {path} found."));
Ok(full_match.cloned().unwrap())
}
fn verify_dists_matches(artifact: &Artifact, dist: Option<&str>) -> Result<()> {
if artifact.dist.as_deref() != dist {
error(format!(
"Release artifact distribution mismatch. Event: {}, Artifact: {}",
dist.unwrap_or("[none]"),
artifact.dist.as_ref().unwrap_or(&String::from("[none]"))
));
tip("Configure 'dist' option in the SDK to match the one used during artifacts upload.\n \
https://docs.sentry.io/platforms/javascript/sourcemaps/troubleshooting_js/#verify-artifact-distribution-value-matches-value-configured-in-your-sdk");
return Err(QuietExit(1).into());
}
success(format!(
"Release artifact distribution matched. Event: {}, Artifact: {}",
dist.unwrap_or("[none]"),
artifact.dist.as_ref().unwrap_or(&String::from("[none]"))
));
Ok(())
}
fn fetch_release_artifact_file(
org: &str,
project: &str,
release: &str,
artifact: &Artifact,
) -> Result<TempFile> {
let api = Api::current();
let file = TempFile::create()?;
api.authenticated()?
.get_release_file(
org,
Some(project),
release,
&artifact.id,
&mut file.open().unwrap(),
)
.map(|_| {
success(format!(
"Successfully fetched {} file from the server.",
artifact.name
));
Ok(file)
})
.map_err(|err| {
format_err!(
"Could not retrieve file {} from release {release}: {err:?}",
artifact.name
)
})?
}
fn fetch_release_artifact_file_metadata(
org: &str,
project: &str,
release: &str,
artifact: &Artifact,
) -> Result<Artifact> {
let api = Api::current();
let file_metadata = api.authenticated()?.get_release_file_metadata(
org,
Some(project),
release,
&artifact.id,
)?;
file_metadata
.ok_or_else(|| format_err!("Could not retrieve file metadata: {}", &artifact.id))
.inspect(|_| {
success(format!(
"Successfully fetched {} file metadata from the server.",
artifact.name
))
})
}
// https://github.com/getsentry/sentry/blob/623c2f5f3313e6dc55e08e2ae2b11d8f90cdbece/src/sentry/lang/javascript/processor.py#L145-L207
fn discover_sourcemaps_location(
org: &str,
project: &str,
release: &str,
artifact: &Artifact,
) -> Result<String> {
let file_metadata = fetch_release_artifact_file_metadata(org, project, release, artifact)?;
if let Some(header) = file_metadata.headers.get("Sourcemap") {
return Ok(header.to_owned());
}
if let Some(header) = file_metadata.headers.get("X-SourceMap") {
return Ok(header.to_owned());
}
let file = fetch_release_artifact_file(org, project, release, artifact)?;
let mut f = file.open()?;
let mut buffer = String::new();
f.read_to_string(&mut buffer)?;
for line in buffer.lines().rev() {
if line.starts_with("//# sourceMappingURL=") || line.starts_with("//@ sourceMappingURL=") {
let possible_sourcemap = line[21..].trim();
if possible_sourcemap.starts_with("data:application/json") {
bail!("Found inlined source maps, this tool doesnt support further verification for this scenario yet");
}
return Ok(possible_sourcemap.to_owned());
}
}
Err(format_err!("Failed to discover source map url"))
}
fn print_sourcemap(file: &TempFile, line: u32, column: u32) -> Result<()> {
let mut f = file.open()?;
let mut buf = vec![];
f.read_to_end(&mut buf)?;
let sm = sourcemap::decode_slice(&buf)?;
if let Some(token) = sm.lookup_token(line, column) {
if let Some(view) = token.get_source_view() {
success("Sourcemap position resolves to:");
print_source(&token, view);
} else if token.get_source_view().is_none() {
bail!("cannot find source");
} else {
bail!("cannot find source for line {line} column {column}");
}
} else {
bail!("invalid sourcemap location");
}
Ok(())
}
fn print_mapped_frame(frame: &Frame) {
println!(
"{}",
style(
frame
.pre_context
.iter()
.map(|l| format!(" {l}"))
.collect::<Vec<String>>()
.join("\n")
)
.yellow()
);
println!(
"{}",
style(format!("> {}", frame.context_line.as_ref().unwrap())).yellow()
);
println!(
"{}",
style(
frame
.post_context
.iter()
.map(|l| format!(" {l}"))
.collect::<Vec<String>>()
.join("\n")
)
.yellow()
);
}
fn extract_release(event: &ProcessedEvent) -> Result<String> {
if let Some(release) = event.release.as_ref() {
success(format!("Event has release name: {release}"));
Ok(release.clone())
} else {
error("Event is missing a release name");
tip("Configure 'release' option in the SDK.\n \
https://docs.sentry.io/platforms/javascript/configuration/options/#release\n \
https://docs.sentry.io/platforms/javascript/sourcemaps/troubleshooting_js/#verify-a-release-is-configured-in-your-sdk");
Err(QuietExit(1).into())
}
}
fn resolve_sourcemap_url(abs_path: &str, sourcemap_location: &str) -> Result<String> {
let base = Url::parse(abs_path)?;
base.join(sourcemap_location)
.map(|url| url.to_string())
.map_err(|e| e.into())
}
// Unify url to be prefixed with the default `~/`, which is a "glob-like" pattern for matching any hostname.
//
// We only need the `pathname` portion of the url, so if it's absolute, just extract it.
// If it's relative however, parse any random url (example.com) and join it with our relative url,
// as Rust cannot handle parsing of relative urls.
//
// It should be more generic than using the defaults, but should be sufficient for our current usecase.
fn unify_artifact_url(abs_path: &str) -> Result<String> {
let abs_path = match Url::parse(abs_path) {
Ok(path) => Ok(path),
Err(_) => {
let base = Url::parse("http://example.com").unwrap();
base.join(abs_path)
.map_err(|_| format_err!("Cannot parse source map url {abs_path}"))
}
}?;
let mut filename = String::from("~");
filename.push_str(abs_path.path());
Ok(filename)
}
pub fn execute(matches: &ArgMatches) -> Result<()> {
let config = Config::current();
warning("DEPRECATION: `sourcemaps explain` has drifted from how sourcemap processing actually operates \
and its output may not be accurate. It will be removed in a future version of `sentry-cli`.");
let (org, project) = config.get_org_and_project(matches)?;
let event_id = matches.get_one::<String>("event").unwrap();
let event = fetch_event(&org, &project, event_id)?;
let release = extract_release(&event)?;
if event.exception.values.is_empty() {
warning("Event has no exception captured, there is no use for source maps");
return Err(QuietExit(0).into());
}
success("Event has a valid exception present");
let exception = &event.exception.values[0];
let stacktrace = exception.stacktrace.as_ref().ok_or_else(|| {
error("Event exception has no stacktrace available");
QuietExit(1)
})?;
success("Event has a valid stacktrace present");
let mut frame = extract_nth_frame(stacktrace, *matches.get_one::<usize>("frame").unwrap())
.map_err(|err| {
error(err);
QuietExit(1)
})?;
if exception.raw_stacktrace.is_some() {
if matches.get_flag("force") {
warning(
"Exception is already source mapped, however 'force' flag was used. Moving along.",
);
let raw_stacktrace = exception.raw_stacktrace.as_ref().unwrap();
frame = extract_nth_frame(raw_stacktrace, *matches.get_one::<usize>("frame").unwrap())
.map_err(|err| {
error(err);
QuietExit(1)
})?;
} else {
warning("Exception is already source mapped and first resolved frame points to:\n");
if let Some(frame) = extract_in_app_frames(stacktrace)
.iter()
.rev()
.find(|f| f.context_line.is_some())
{
print_mapped_frame(frame);
} else {
println!("{}", style("> [missing context line]").yellow());
}
return Err(QuietExit(0).into());
}
}
let abs_path = frame.abs_path.as_ref().expect("Incorrect abs_path value");
let artifacts = fetch_release_artifacts(&org, &project, &release)?;
let matched_artifact = find_matching_artifact(&artifacts, &unify_artifact_url(abs_path)?)?;
verify_dists_matches(&matched_artifact, event.dist.as_deref())?;
let sourcemap_location =
discover_sourcemaps_location(&org, &project, &release, &matched_artifact).map_err(
|err| {
error(err);
QuietExit(1)
},
)?;
success(format!(
"Found source map location: {}",
&sourcemap_location
));
let sourcemap_url = unify_artifact_url(&resolve_sourcemap_url(abs_path, &sourcemap_location)?)?;
success(format!("Resolved source map url: {}", &sourcemap_url));
let sourcemap_artifact = find_matching_artifact(&artifacts, &sourcemap_url)?;
verify_dists_matches(&sourcemap_artifact, event.dist.as_deref())?;
let sourcemap_file =
fetch_release_artifact_file(&org, &project, &release, &sourcemap_artifact)?;
print_sourcemap(
&sourcemap_file,
frame.lineno.expect("Event frame is missing line number") as u32 - 1,
frame.colno.expect("Event frame is missing column number") as u32 - 1,
)
.map_err(|err| {
error(err);
QuietExit(1)
})?;
success("Source Maps should be working fine. Have you tried turning it off and on again?");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_resolve_sourcemap_url() {
// Tests coming from `tests/sentry/utils/test_urls.py` in `getsentry/sentry`
let cases = vec![
("http://example.com/foo", "bar", "http://example.com/bar"),
("http://example.com/foo", "/bar", "http://example.com/bar"),
("https://example.com/foo", "/bar", "https://example.com/bar"),
(
"http://example.com/foo/baz",
"bar",
"http://example.com/foo/bar",
),
(
"http://example.com/foo/baz",
"/bar",
"http://example.com/bar",
),
("aps://example.com/foo", "/bar", "aps://example.com/bar"),
(
"apsunknown://example.com/foo",
"/bar",
"apsunknown://example.com/bar",
),
(
"apsunknown://example.com/foo",
"//aha/uhu",
"apsunknown://aha/uhu",
),
];
for (base, to_join, expected) in cases {
assert_eq!(resolve_sourcemap_url(base, to_join).unwrap(), expected);
}
}
#[test]
fn test_unify_artifact_url() {
let cases = vec![
(
"http://localhost:5000/dist/bundle.min.js",
"~/dist/bundle.min.js",
),
("/dist/bundle.js.map", "~/dist/bundle.js.map"),
];
for (path, expected) in cases {
assert_eq!(unify_artifact_url(path).unwrap(), expected);
}
}
}