forked from rust-lang/docs.rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrustdoc.rs
2593 lines (2334 loc) · 86.6 KB
/
rustdoc.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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! rustdoc handler
use crate::{
db::Pool,
repositories::RepositoryStatsUpdater,
storage::rustdoc_archive_path,
utils::{self, spawn_blocking},
web::{
axum_cached_redirect, axum_parse_uri_with_params,
cache::CachePolicy,
crate_details::CrateDetails,
csp::Csp,
encode_url_path,
error::{AxumNope, AxumResult},
file::File,
match_version_axum,
metrics::RenderingTimesRecorder,
page::TemplateData,
MatchSemver, MetaData,
},
Config, Metrics, Storage, RUSTDOC_STATIC_STORAGE_PREFIX,
};
use anyhow::{anyhow, Context as _};
use axum::{
extract::{Extension, Path, Query},
http::{StatusCode, Uri},
response::{Html, IntoResponse, Response as AxumResponse},
};
use lol_html::errors::RewritingError;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, HashMap},
sync::Arc,
};
use tracing::{debug, instrument, trace};
static DOC_RUST_LANG_ORG_REDIRECTS: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
HashMap::from([
("alloc", "stable/alloc"),
("core", "stable/core"),
("proc_macro", "stable/proc_macro"),
("proc-macro", "stable/proc_macro"),
("std", "stable/std"),
("test", "stable/test"),
("rustc", "nightly/nightly-rustc"),
("rustdoc", "nightly/nightly-rustc/rustdoc"),
])
});
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RustdocRedirectorParams {
name: String,
version: Option<String>,
target: Option<String>,
}
/// try to serve a toolchain specific asset from the legacy location.
///
/// Newer rustdoc builds use a specific subfolder on the bucket,
/// a new `static-root-path` prefix (`/-/rustdoc.static/...`), which
/// is served via our `static_asset_handler`.
///
/// The legacy location is the root, both on the bucket & the URL
/// path, which is suboptimal since the route overlaps with other routes.
///
/// See also https://github.com/rust-lang/docs.rs/pull/1889
async fn try_serve_legacy_toolchain_asset(
storage: Arc<Storage>,
config: Arc<Config>,
path: impl AsRef<str>,
) -> AxumResult<AxumResponse> {
let path = path.as_ref().to_owned();
// FIXME: this could be optimized: when a path doesn't exist
// in storage, we don't need to recheck on every request.
// Existing files are returned with caching headers, so
// are cached by the CDN.
// If cached, it doesn't need to be invalidated,
// since new nightly versions will always put their
// toolchain specific resources into the new folder,
// which is reached via the new handler.
Ok(
spawn_blocking(move || File::from_path(&storage, &path, &config))
.await
.map(IntoResponse::into_response)?,
)
}
/// Handler called for `/:crate` and `/:crate/:version` URLs. Automatically redirects to the docs
/// or crate details page based on whether the given crate version was successfully built.
#[instrument(skip_all)]
pub(crate) async fn rustdoc_redirector_handler(
Path(params): Path<RustdocRedirectorParams>,
Extension(metrics): Extension<Arc<Metrics>>,
Extension(storage): Extension<Arc<Storage>>,
Extension(config): Extension<Arc<Config>>,
Extension(pool): Extension<Pool>,
Query(query_pairs): Query<HashMap<String, String>>,
uri: Uri,
) -> AxumResult<impl IntoResponse> {
#[instrument]
fn redirect_to_doc(
query_pairs: &HashMap<String, String>,
url_str: String,
cache_policy: CachePolicy,
path_in_crate: Option<&str>,
) -> AxumResult<impl IntoResponse> {
let mut queries: BTreeMap<String, String> = BTreeMap::new();
if let Some(path) = path_in_crate {
queries.insert("search".into(), path.into());
}
queries.extend(query_pairs.to_owned());
trace!("redirect to doc");
Ok(axum_cached_redirect(
axum_parse_uri_with_params(&url_str, queries)?,
cache_policy,
)?)
}
let mut rendering_time = RenderingTimesRecorder::new(&metrics.rustdoc_redirect_rendering_times);
// global static assets for older builds are served from the root, which ends up
// in this handler as `params.name`.
if let Some((_, extension)) = params.name.rsplit_once('.') {
if ["css", "js", "png", "svg", "woff", "woff2"]
.binary_search(&extension)
.is_ok()
{
rendering_time.step("serve static asset");
return try_serve_legacy_toolchain_asset(storage, config, params.name).await;
}
}
if let Some((_, extension)) = uri.path().rsplit_once('.') {
if extension == "ico" {
// redirect all ico requests
// originally from:
// https://github.com/rust-lang/docs.rs/commit/f3848a34c391841a2516a9e6ad1f80f6f490c6d0
return Ok(axum_cached_redirect(
"/-/static/favicon.ico",
CachePolicy::ForeverInCdnAndBrowser,
)?
.into_response());
}
}
let (mut crate_name, path_in_crate) = match params.name.split_once("::") {
Some((krate, path)) => (krate.to_string(), Some(path.to_string())),
None => (params.name.to_string(), None),
};
if let Some(inner_path) = DOC_RUST_LANG_ORG_REDIRECTS.get(crate_name.as_str()) {
return Ok(redirect_to_doc(
&query_pairs,
format!("https://doc.rust-lang.org/{inner_path}/"),
CachePolicy::ForeverInCdnAndStaleInBrowser,
path_in_crate.as_deref(),
)?
.into_response());
}
// it doesn't matter if the version that was given was exact or not, since we're redirecting
// anyway
rendering_time.step("match version");
let v = match_version_axum(&pool, &crate_name, params.version.as_deref()).await?;
trace!(?v, "matched version");
if let Some(new_name) = v.corrected_name {
// `match_version` checked against -/_ typos, so if we have a name here we should
// use that instead
crate_name = new_name;
}
let (mut version, id) = v.version.into_parts();
// we might get requests to crate-specific JS files here.
if let Some(ref target) = params.target {
if target.ends_with(".js") {
// this URL is actually from a crate-internal path, serve it there instead
rendering_time.step("serve JS for crate");
let krate = spawn_blocking({
let crate_name = crate_name.clone();
let version = version.clone();
move || {
let mut conn = pool.get()?;
CrateDetails::new(&mut *conn, &crate_name, &version, &version, None)
}
})
.await?
.ok_or(AxumNope::ResourceNotFound)?;
match spawn_blocking({
let version = version.clone();
let storage = storage.clone();
let target = target.clone();
move || {
storage.fetch_rustdoc_file(
&crate_name,
&version,
&target,
krate.archive_storage,
None, // FIXME: &mut rendering_time, re-add this when storage is async
)
}
})
.await
{
Ok(blob) => return Ok(File(blob).into_response()),
Err(err) => {
if !matches!(err.downcast_ref(), Some(AxumNope::ResourceNotFound))
&& !matches!(err.downcast_ref(), Some(crate::storage::PathNotFoundError))
{
debug!(?target, ?err, "got error serving file");
}
// FIXME: we sometimes still get requests for toolchain
// specific static assets under the crate/version/ path.
// This is fixed in rustdoc, but pending a rebuild for
// docs that were affected by this bug.
// https://github.com/rust-lang/docs.rs/issues/1979
if target.starts_with("search-") || target.starts_with("settings-") {
return try_serve_legacy_toolchain_asset(storage, config, target).await;
} else {
return Err(err.into());
}
}
}
}
}
if let None | Some("latest") = params.version.as_deref() {
version = "latest".to_string()
}
// get target name and whether it has docs
// FIXME: This is a bit inefficient but allowing us to use less code in general
rendering_time.step("fetch release doc status");
let (target_name, has_docs): (String, bool) = spawn_blocking({
move || {
let mut conn = pool.get()?;
let row = conn.query_one(
"SELECT target_name, rustdoc_status
FROM releases
WHERE releases.id = $1",
&[&id],
)?;
Ok((row.get(0), row.get(1)))
}
})
.await?;
let mut target = params.target.as_deref();
if target == Some("index.html") || target == Some(&target_name) {
target = None;
}
if has_docs {
rendering_time.step("redirect to doc");
let url_str = if let Some(target) = target {
format!("/{crate_name}/{version}/{target}/{target_name}/")
} else {
format!("/{crate_name}/{version}/{target_name}/")
};
let cache = if version == "latest" {
CachePolicy::ForeverInCdn
} else {
CachePolicy::ForeverInCdnAndStaleInBrowser
};
Ok(redirect_to_doc(
&query_pairs,
encode_url_path(&url_str),
cache,
path_in_crate.as_deref(),
)?
.into_response())
} else {
rendering_time.step("redirect to crate");
Ok(axum_cached_redirect(
format!("/crate/{}/{}", crate_name, version),
CachePolicy::ForeverInCdn,
)?
.into_response())
}
}
#[derive(Debug, Clone, Serialize)]
struct RustdocPage {
latest_path: String,
permalink_path: String,
latest_version: String,
target: String,
inner_path: String,
// true if we are displaying the latest version of the crate, regardless
// of whether the URL specifies a version number or the string "latest."
is_latest_version: bool,
// true if the URL specifies a version using the string "latest."
is_latest_url: bool,
is_prerelease: bool,
krate: CrateDetails,
metadata: MetaData,
}
impl RustdocPage {
fn into_response(
self,
rustdoc_html: &[u8],
max_parse_memory: usize,
templates: &TemplateData,
metrics: &Metrics,
config: &Config,
file_path: &str,
) -> AxumResult<AxumResponse> {
let is_latest_url = self.is_latest_url;
// Build the page of documentation
let ctx = tera::Context::from_serialize(self).context("error creating tera context")?;
// Extract the head and body of the rustdoc file so that we can insert it into our own html
// while logging OOM errors from html rewriting
let html = match utils::rewrite_lol(rustdoc_html, max_parse_memory, ctx, templates) {
Err(RewritingError::MemoryLimitExceeded(..)) => {
metrics.html_rewrite_ooms.inc();
return Err(AxumNope::InternalError(
anyhow!(
"Failed to serve the rustdoc file '{}' because rewriting it surpassed the memory limit of {} bytes",
file_path, config.max_parse_memory,
)
));
}
result => result.context("error rewriting HTML")?,
};
Ok((
StatusCode::OK,
(!is_latest_url).then_some([("X-Robots-Tag", "noindex")]),
Extension(if is_latest_url {
CachePolicy::ForeverInCdn
} else {
CachePolicy::ForeverInCdnAndStaleInBrowser
}),
Html(html),
)
.into_response())
}
}
#[derive(Clone, Deserialize)]
pub(crate) struct RustdocHtmlParams {
name: String,
version: String,
// both target and path are only used for matching the route.
// The actual path is read from the request `Uri` because
// we have some static filenames directly in the routes.
#[allow(dead_code)]
target: Option<String>,
#[allow(dead_code)]
path: Option<String>,
}
/// Serves documentation generated by rustdoc.
///
/// This includes all HTML files for an individual crate, as well as the `search-index.js`, which is
/// also crate-specific.
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub(crate) async fn rustdoc_html_server_handler(
Path(params): Path<RustdocHtmlParams>,
Extension(metrics): Extension<Arc<Metrics>>,
Extension(templates): Extension<Arc<TemplateData>>,
Extension(pool): Extension<Pool>,
Extension(storage): Extension<Arc<Storage>>,
Extension(config): Extension<Arc<Config>>,
Extension(csp): Extension<Arc<Csp>>,
Extension(updater): Extension<Arc<RepositoryStatsUpdater>>,
uri: Uri,
) -> AxumResult<AxumResponse> {
let mut rendering_time = RenderingTimesRecorder::new(&metrics.rustdoc_rendering_times);
// since we directly use the Uri-path and not the extracted params from the router,
// we have to percent-decode the string here.
let original_path = percent_encoding::percent_decode(uri.path().as_bytes())
.decode_utf8()
.map_err(|_| AxumNope::BadRequest)?;
let mut req_path: Vec<&str> = original_path.split('/').collect();
// Remove the empty start, the name and the version from the path
req_path.drain(..3).for_each(drop);
// Pages generated by Rustdoc are not ready to be served with a CSP yet.
csp.suppress(true);
// Convenience function to allow for easy redirection
#[instrument]
fn redirect(
name: &str,
vers: &str,
path: &[&str],
cache_policy: CachePolicy,
) -> AxumResult<AxumResponse> {
trace!("redirect");
// Format and parse the redirect url
Ok(axum_cached_redirect(
encode_url_path(&format!("/{}/{}/{}", name, vers, path.join("/"))),
cache_policy,
)?
.into_response())
}
trace!("match version");
rendering_time.step("match version");
// Check the database for releases with the requested version while doing the following:
// * If no matching releases are found, return a 404 with the underlying error
// Then:
// * If both the name and the version are an exact match, return the version of the crate.
// * If there is an exact match, but the requested crate name was corrected (dashes vs. underscores), redirect to the corrected name.
// * If there is a semver (but not exact) match, redirect to the exact version.
let release_found = match_version_axum(&pool, ¶ms.name, Some(¶ms.version)).await?;
trace!(?release_found, "found release");
let (version, version_or_latest, is_latest_url) = match release_found.version {
MatchSemver::Exact((version, _)) => {
// Redirect when the requested crate name isn't correct
if let Some(name) = release_found.corrected_name {
return redirect(&name, &version, &req_path, CachePolicy::NoCaching);
}
(version.clone(), version, false)
}
MatchSemver::Latest((version, _)) => {
// Redirect when the requested crate name isn't correct
if let Some(name) = release_found.corrected_name {
return redirect(&name, "latest", &req_path, CachePolicy::NoCaching);
}
(version, "latest".to_string(), true)
}
// Redirect when the requested version isn't correct
MatchSemver::Semver((v, _)) => {
// to prevent cloudfront caching the wrong artifacts on URLs with loose semver
// versions, redirect the browser to the returned version instead of loading it
// immediately
return redirect(¶ms.name, &v, &req_path, CachePolicy::ForeverInCdn);
}
};
trace!("crate details");
rendering_time.step("crate details");
// Get the crate's details from the database
// NOTE: we know this crate must exist because we just checked it above (or else `match_version` is buggy)
let krate = spawn_blocking({
let params = params.clone();
let version = version.clone();
let version_or_latest = version_or_latest.clone();
move || {
let mut conn = pool.get()?;
CrateDetails::new(
&mut *conn,
¶ms.name,
&version,
&version_or_latest,
Some(&updater),
)
}
})
.await?
.ok_or(AxumNope::ResourceNotFound)?;
// if visiting the full path to the default target, remove the target from the path
// expects a req_path that looks like `[/:target]/.*`
if req_path.first().copied() == Some(&krate.metadata.default_target) {
return redirect(
¶ms.name,
&version_or_latest,
&req_path[1..],
CachePolicy::ForeverInCdn,
);
}
// Create the path to access the file from
let mut storage_path = req_path.join("/");
if storage_path.ends_with('/') {
req_path.pop(); // get rid of empty string
storage_path.push_str("index.html");
req_path.push("index.html");
}
trace!(?storage_path, ?req_path, "try fetching from storage");
// Attempt to load the file from the database
let blob = match spawn_blocking({
let params = params.clone();
let version = version.clone();
let storage = storage.clone();
let storage_path = storage_path.clone();
move || {
storage.fetch_rustdoc_file(
¶ms.name,
&version,
&storage_path,
krate.archive_storage,
None, // FIXME: &mut rendering_time, re-add this when storage is async
)
}
})
.await
{
Ok(file) => file,
Err(err) => {
if !matches!(err.downcast_ref(), Some(AxumNope::ResourceNotFound))
&& !matches!(err.downcast_ref(), Some(crate::storage::PathNotFoundError))
{
debug!("got error serving {}: {}", storage_path, err);
}
// If it fails, we try again with /index.html at the end
storage_path.push_str("/index.html");
req_path.push("index.html");
return if spawn_blocking({
let params = params.clone();
let version = version.clone();
let storage = storage.clone();
move || {
storage.rustdoc_file_exists(
¶ms.name,
&version,
&storage_path,
krate.archive_storage,
)
}
})
.await?
{
redirect(
¶ms.name,
&version_or_latest,
&req_path,
CachePolicy::ForeverInCdn,
)
} else if req_path.first().map_or(false, |p| p.contains('-')) {
// This is a target, not a module; it may not have been built.
// Redirect to the default target and show a search page instead of a hard 404.
Ok(axum_cached_redirect(
encode_url_path(&format!(
"/crate/{}/{}/target-redirect/{}",
params.name,
version,
req_path.join("/")
)),
CachePolicy::ForeverInCdn,
)?
.into_response())
} else {
Err(AxumNope::ResourceNotFound)
};
}
};
// Serve non-html files directly
if !storage_path.ends_with(".html") {
trace!(?storage_path, "serve asset");
rendering_time.step("serve asset");
// default asset caching behaviour is `Cache::ForeverInCdnAndBrowser`.
// This is an edge-case when we serve invocation specific static assets under `/latest/`:
// https://github.com/rust-lang/docs.rs/issues/1593
return Ok(File(blob).into_response());
}
rendering_time.step("find latest path");
let latest_release = krate.latest_release();
// Get the latest version of the crate
let latest_version = latest_release.version.to_string();
let is_latest_version = latest_version == version;
let is_prerelease = !(semver::Version::parse(&version)
.with_context(|| {
format!(
"invalid semver in database for crate {}: {}",
params.name, &version
)
})?
.pre
.is_empty());
// The path within this crate version's rustdoc output
let (target, inner_path) = {
let mut inner_path = req_path.clone();
let target = if inner_path.len() > 1
&& krate
.metadata
.doc_targets
.iter()
.any(|s| s == inner_path[0])
{
inner_path.remove(0)
} else {
""
};
(target, inner_path.join("/"))
};
// Find the path of the latest version for the `Go to latest` and `Permalink` links
let target_redirect = if latest_release.build_status {
let target = if target.is_empty() {
&krate.metadata.default_target
} else {
target
};
format!("/target-redirect/{}/{}", target, inner_path)
} else {
"".to_string()
};
let query_string = if let Some(query) = uri.query() {
format!("?{}", query)
} else {
"".to_string()
};
let permalink_path = format!(
"/{}/{}/{}{}",
params.name, latest_version, inner_path, query_string
);
let latest_path = format!(
"/crate/{}/latest{}{}",
params.name, target_redirect, query_string
);
metrics
.recently_accessed_releases
.record(krate.crate_id, krate.release_id, target);
let target = if target.is_empty() {
String::new()
} else {
format!("{}/", target)
};
rendering_time.step("rewrite html");
// Build the page of documentation,
// inside `spawn_blocking` since it's CPU intensive.
spawn_blocking({
let metrics = metrics.clone();
move || {
Ok(RustdocPage {
latest_path,
permalink_path,
latest_version,
target,
inner_path,
is_latest_version,
is_latest_url,
is_prerelease,
metadata: krate.metadata.clone(),
krate: krate.clone(),
}
.into_response(
&blob.content,
config.max_parse_memory,
&templates,
&metrics,
&config,
&storage_path,
))
}
})
.await?
}
/// Checks whether the given path exists.
/// The crate's `target_name` is used to confirm whether a platform triple is part of the path.
///
/// Note that path is overloaded in this context to mean both the path of a URL
/// and the file path of a static file in the DB.
///
/// `file_path` is assumed to have the following format:
/// `[/platform]/module/[kind.name.html|index.html]`
///
/// Returns a path that can be appended to `/crate/version/` to create a complete URL.
fn path_for_version(
file_path: &[&str],
crate_details: &CrateDetails,
) -> (String, HashMap<String, String>) {
// check if req_path[3] is the platform choice or the name of the crate
// Note we don't require the platform to have a trailing slash.
let platform = if crate_details
.metadata
.doc_targets
.iter()
.any(|s| s == file_path[0])
&& !file_path.is_empty()
{
file_path[0]
} else {
""
};
let is_source_view = if platform.is_empty() {
// /{name}/{version}/src/{crate}/index.html
file_path.first().copied() == Some("src")
} else {
// /{name}/{version}/{platform}/src/{crate}/index.html
file_path.get(1).copied() == Some("src")
};
// this page doesn't exist in the latest version
let last_component = *file_path.last().unwrap();
let search_item = if last_component == "index.html" {
// this is a module
file_path.get(file_path.len() - 2).copied()
// no trailing slash; no one should be redirected here but we handle it gracefully anyway
} else if last_component == platform {
// nothing to search for
None
} else if !is_source_view {
// this is an item
last_component.split('.').nth(1)
} else {
// if this is a Rust source file, try searching for the module;
// else, don't try searching at all, we don't know how to find it
last_component.strip_suffix(".rs.html")
};
let target_name = &crate_details.target_name;
let path = if platform.is_empty() {
format!("{target_name}/")
} else {
format!("{platform}/{target_name}/")
};
let query_params = search_item
.map(|i| HashMap::from_iter([("search".into(), i.into())]))
.unwrap_or_default();
(path, query_params)
}
pub(crate) async fn target_redirect_handler(
Path((name, version, req_path)): Path<(String, String, String)>,
Extension(pool): Extension<Pool>,
Extension(storage): Extension<Arc<Storage>>,
Extension(updater): Extension<Arc<RepositoryStatsUpdater>>,
) -> AxumResult<impl IntoResponse> {
let release_found = match_version_axum(&pool, &name, Some(&version)).await?;
let (version, version_or_latest, is_latest_url) = match release_found.version {
MatchSemver::Exact((version, _)) => (version.clone(), version, false),
MatchSemver::Latest((version, _)) => (version, "latest".to_string(), true),
// semver matching not supported here
MatchSemver::Semver(_) => return Err(AxumNope::VersionNotFound),
};
let crate_details = spawn_blocking({
let name = name.clone();
let version = version.clone();
let version_or_latest = version_or_latest.clone();
move || {
let mut conn = pool.get()?;
CrateDetails::new(
&mut *conn,
&name,
&version,
&version_or_latest,
Some(&updater),
)
}
})
.await?
.ok_or(AxumNope::VersionNotFound)?;
// We're trying to find the storage location
// for the requested path in the target-redirect.
// *path always contains the target,
// here we are dropping it when it's the
// default target,
// and add `/index.html` if we request
// a folder.
let storage_location_for_path = {
let mut pieces: Vec<_> = req_path.split('/').map(str::to_owned).collect();
if let Some(target) = pieces.first() {
if target == &crate_details.metadata.default_target {
pieces.remove(0);
}
}
if let Some(last) = pieces.last_mut() {
if last.is_empty() {
*last = "index.html".to_string();
}
}
pieces.join("/")
};
let (redirect_path, query_args) = if spawn_blocking({
let name = name.clone();
let file_path = storage_location_for_path.clone();
move || {
storage.rustdoc_file_exists(&name, &version, &file_path, crate_details.archive_storage)
}
})
.await?
{
// Simple case: page exists in the other target & version, so just change these
(storage_location_for_path, HashMap::new())
} else {
let pieces: Vec<_> = storage_location_for_path.split('/').collect();
path_for_version(&pieces, &crate_details)
};
Ok(axum_cached_redirect(
axum_parse_uri_with_params(
&encode_url_path(&format!("/{name}/{version_or_latest}/{redirect_path}")),
query_args,
)?,
if is_latest_url {
CachePolicy::ForeverInCdn
} else {
CachePolicy::ForeverInCdnAndStaleInBrowser
},
)?)
}
#[derive(Deserialize, Debug)]
pub(crate) struct BadgeQueryParams {
version: Option<String>,
}
#[instrument]
pub(crate) async fn badge_handler(
Path(name): Path<String>,
Query(query): Query<BadgeQueryParams>,
) -> AxumResult<impl IntoResponse> {
let version = query.version.unwrap_or_else(|| "latest".to_string());
let url = url::Url::parse(&format!(
"https://img.shields.io/docsrs/{}/{}",
name, version
))
.context("could not parse URL")?;
Ok((
StatusCode::MOVED_PERMANENTLY,
[(http::header::LOCATION, url.to_string())],
Extension(CachePolicy::ForeverInCdnAndBrowser),
))
}
pub(crate) async fn download_handler(
Path((name, req_version)): Path<(String, String)>,
Extension(pool): Extension<Pool>,
Extension(storage): Extension<Arc<Storage>>,
Extension(config): Extension<Arc<Config>>,
) -> AxumResult<impl IntoResponse> {
let (version, _) = match_version_axum(&pool, &name, Some(&req_version))
.await?
.assume_exact()?
.into_parts();
let archive_path = rustdoc_archive_path(&name, &version);
spawn_blocking({
let archive_path = archive_path.clone();
move || {
// not all archives are set for public access yet, so we check if
// the access is set and fix it if needed.
let archive_is_public = match storage
.get_public_access(&archive_path)
.context("reading public access for archive")
{
Ok(is_public) => is_public,
Err(err) => {
if matches!(err.downcast_ref(), Some(crate::storage::PathNotFoundError)) {
return Err(AxumNope::ResourceNotFound.into());
} else {
return Err(AxumNope::InternalError(err).into());
}
}
};
if !archive_is_public {
storage.set_public_access(&archive_path, true)?;
}
Ok(())
}
})
.await?;
Ok(super::axum_cached_redirect(
format!("{}/{}", config.s3_static_root_path, archive_path),
CachePolicy::ForeverInCdn,
)?)
}
/// Serves shared resources used by rustdoc-generated documentation.
///
/// This serves files from S3, and is pointed to by the `--static-root-path` flag to rustdoc.
pub(crate) async fn static_asset_handler(
Path(path): Path<String>,
Extension(storage): Extension<Arc<Storage>>,
Extension(config): Extension<Arc<Config>>,
) -> AxumResult<impl IntoResponse> {
let storage_path = format!("{}{}", RUSTDOC_STATIC_STORAGE_PREFIX, path);
Ok(spawn_blocking(move || File::from_path(&storage, &storage_path, &config)).await?)
}
#[cfg(test)]
mod test {
use crate::{test::*, web::cache::CachePolicy, Config};
use anyhow::Context;
use kuchiki::traits::TendrilSink;
use reqwest::{blocking::ClientBuilder, redirect, StatusCode};
use std::collections::BTreeMap;
use test_case::test_case;
use tracing::info;
fn try_latest_version_redirect(
path: &str,
web: &TestFrontend,
config: &Config,
) -> Result<Option<String>, anyhow::Error> {
assert_success(path, web)?;
let response = web.get(path).send()?;
assert_cache_control(
&response,
CachePolicy::ForeverInCdnAndStaleInBrowser,
config,
);
let data = response.text()?;
info!("fetched path {} and got content {}\nhelp: if this is missing the header, remember to add <html><head></head><body></body></html>", path, data);
let dom = kuchiki::parse_html().one(data);
if let Some(elem) = dom
.select("form > ul > li > a.warn")
.expect("invalid selector")
.next()
{
let link = elem.attributes.borrow().get("href").unwrap().to_string();
assert_success_cached(&link, web, CachePolicy::ForeverInCdn, config)?;
Ok(Some(link))
} else {
Ok(None)
}
}
fn latest_version_redirect(
path: &str,
web: &TestFrontend,
config: &Config,
) -> Result<String, anyhow::Error> {
try_latest_version_redirect(path, web, config)?
.with_context(|| anyhow::anyhow!("no redirect found for {}", path))
}
#[test_case(true)]
#[test_case(false)]
// regression test for https://github.com/rust-lang/docs.rs/issues/552
fn settings_html(archive_storage: bool) {
wrapper(|env| {
// first release works, second fails
env.fake_release()
.name("buggy")
.version("0.1.0")
.archive_storage(archive_storage)
.rustdoc_file("settings.html")
.rustdoc_file("scrape-examples-help.html")
.rustdoc_file("directory_1/index.html")
.rustdoc_file("directory_2.html/index.html")
.rustdoc_file("all.html")
.rustdoc_file("directory_3/.gitignore")
.rustdoc_file("directory_4/empty_file_no_ext")
.create()?;
env.fake_release()
.name("buggy")
.version("0.2.0")
.archive_storage(archive_storage)
.build_result_failed()
.create()?;
let web = env.frontend();
assert_success_cached("/", web, CachePolicy::NoCaching, &env.config())?;
assert_success_cached(
"/crate/buggy/0.1.0/",
web,
CachePolicy::ForeverInCdnAndStaleInBrowser,
&env.config(),
)?;
assert_success_cached(
"/buggy/0.1.0/directory_1/index.html",
web,
CachePolicy::ForeverInCdnAndStaleInBrowser,
&env.config(),