Skip to content

Commit be5f0de

Browse files
authored
Merge branch 'master' into sg-update-swirl
2 parents ececdf8 + faf625e commit be5f0de

File tree

18 files changed

+156
-122
lines changed

18 files changed

+156
-122
lines changed

Cargo.lock

Lines changed: 7 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

app/routes/crate/version.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export default Route.extend({
6262
.get('versions')
6363
.then(versions => {
6464
const latestStableVersion = versions.find(version => {
65-
if (!isUnstableVersion(version.get('num'))) {
65+
if (!isUnstableVersion(version.get('num')) && !version.get('yanked')) {
6666
return version;
6767
}
6868
});

app/routes/github-authorize.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import Route from '@ember/routing/route';
2-
import ajax from 'ember-fetch/ajax';
2+
import fetch from 'fetch';
33
import { serializeQueryParams } from 'ember-fetch/mixins/adapter-fetch';
44

55
/**
@@ -19,8 +19,9 @@ export default Route.extend({
1919
async beforeModel(transition) {
2020
try {
2121
let queryParams = serializeQueryParams(transition.queryParams);
22-
let d = await ajax(`/authorize?${queryParams}`);
23-
let item = JSON.stringify({ ok: true, data: d });
22+
let resp = await fetch(`/authorize?${queryParams}`);
23+
let json = await resp.json();
24+
let item = JSON.stringify({ ok: resp.ok, data: json });
2425
if (window.opener) {
2526
window.opener.github_response = item;
2627
}

app/routes/login.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,15 +53,15 @@ export default Route.extend({
5353
if (!response) {
5454
return;
5555
}
56-
if (!response.ok) {
57-
this.flashMessages.show('Failed to log in');
58-
return;
59-
}
56+
6057
let { data } = response;
61-
if (data.errors) {
58+
if (data && data.errors) {
6259
let error = `Failed to log in: ${data.errors[0].detail}`;
6360
this.flashMessages.show(error);
6461
return;
62+
} else if (!response.ok) {
63+
this.flashMessages.show('Failed to log in');
64+
return;
6565
}
6666

6767
let user = this.store.push(this.store.normalize('user', data.user));

src/app.rs

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
//! Application-wide components in a struct accessible from each request
22
3-
use crate::{db, util::CargoResult, Config, Env};
3+
use crate::{db, Config, Env};
44
use std::{path::PathBuf, sync::Arc, time::Duration};
55

66
use diesel::r2d2;
7+
use reqwest::Client;
78
use scheduled_thread_pool::ScheduledThreadPool;
89

910
/// The `App` struct holds the main components of the application like
@@ -26,17 +27,24 @@ pub struct App {
2627

2728
/// The server configuration
2829
pub config: Config,
30+
31+
/// A configured client for outgoing HTTP requests
32+
///
33+
/// In production this shares a single connection pool across requests. In tests
34+
/// this is either None (in which case any attempt to create an outgoing connection
35+
/// will panic) or a `Client` configured with a per-test replay proxy.
36+
http_client: Option<Client>,
2937
}
3038

3139
impl App {
32-
/// Creates a new `App` with a given `Config`
40+
/// Creates a new `App` with a given `Config` and an optional HTTP `Client`
3341
///
3442
/// Configures and sets up:
3543
///
3644
/// - GitHub OAuth
3745
/// - Database connection pools
38-
/// - A `git2::Repository` instance from the index repo checkout (that server.rs ensures exists)
39-
pub fn new(config: &Config) -> App {
46+
/// - Holds an HTTP `Client` and associated connection pool, if provided
47+
pub fn new(config: &Config, http_client: Option<Client>) -> App {
4048
let mut github = oauth2::Config::new(
4149
&config.gh_client_id,
4250
&config.gh_client_secret,
@@ -90,19 +98,22 @@ impl App {
9098
session_key: config.session_key.clone(),
9199
git_repo_checkout: config.git_repo_checkout.clone(),
92100
config: config.clone(),
101+
http_client,
93102
}
94103
}
95104

96105
/// Returns a client for making HTTP requests to upload crate files.
97106
///
98-
/// The handle will go through a proxy if the uploader being used has specified one, which
99-
/// is only done in tests with `TestApp::with_proxy()` in order to be able to record and
100-
/// inspect the HTTP requests that tests make.
101-
pub fn http_client(&self) -> CargoResult<reqwest::Client> {
102-
let mut builder = reqwest::Client::builder();
103-
if let Some(proxy) = self.config.uploader.proxy() {
104-
builder = builder.proxy(reqwest::Proxy::all(proxy)?);
105-
}
106-
Ok(builder.build()?)
107+
/// The client will go through a proxy if the application was configured via
108+
/// `TestApp::with_proxy()`.
109+
///
110+
/// # Panics
111+
///
112+
/// Panics if the application was not initialized with a client. This should only occur in
113+
/// tests that were not properly initialized.
114+
pub fn http_client(&self) -> &Client {
115+
self.http_client
116+
.as_ref()
117+
.expect("No HTTP client is configured. In tests, use `TestApp::with_proxy()`.")
107118
}
108119
}

src/bin/render-readmes.rs

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use chrono::{TimeZone, Utc};
2121
use diesel::{dsl::any, prelude::*};
2222
use docopt::Docopt;
2323
use flate2::read::GzDecoder;
24+
use reqwest::Client;
2425
use tar::{self, Archive};
2526

2627
const DEFAULT_PAGE_SIZE: usize = 25;
@@ -94,6 +95,8 @@ fn main() {
9495
total_pages + 1
9596
};
9697

98+
let client = Client::new();
99+
97100
for (page_num, version_ids_chunk) in version_ids.chunks(page_size).enumerate() {
98101
println!(
99102
"= Page {} of {} ==================================",
@@ -117,22 +120,18 @@ fn main() {
117120
krate_name, version.num
118121
)
119122
});
123+
let client = client.clone();
120124
let handle = thread::spawn(move || {
121125
println!("[{}-{}] Rendering README...", krate_name, version.num);
122-
let readme = get_readme(&config, &version, &krate_name);
126+
let readme = get_readme(&config, &client, &version, &krate_name);
123127
if readme.is_none() {
124128
return;
125129
}
126130
let readme = readme.unwrap();
127131
let readme_path = format!("readmes/{0}/{0}-{1}.html", krate_name, version.num);
128132
config
129133
.uploader
130-
.upload(
131-
&reqwest::Client::new(),
132-
&readme_path,
133-
readme.into_bytes(),
134-
"text/html",
135-
)
134+
.upload(&client, &readme_path, readme.into_bytes(), "text/html")
136135
.unwrap_or_else(|_| {
137136
panic!(
138137
"[{}-{}] Couldn't upload file to S3",
@@ -151,12 +150,17 @@ fn main() {
151150
}
152151

153152
/// Renders the readme of an uploaded crate version.
154-
fn get_readme(config: &Config, version: &Version, krate_name: &str) -> Option<String> {
153+
fn get_readme(
154+
config: &Config,
155+
client: &Client,
156+
version: &Version,
157+
krate_name: &str,
158+
) -> Option<String> {
155159
let location = config
156160
.uploader
157-
.crate_location(krate_name, &version.num.to_string())?;
161+
.crate_location(krate_name, &version.num.to_string());
158162

159-
let mut response = match reqwest::get(&location) {
163+
let mut response = match client.get(&location).send() {
160164
Ok(r) => r,
161165
Err(err) => {
162166
println!(

src/bin/server.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use std::{
99

1010
use civet::Server as CivetServer;
1111
use conduit_hyper::Service as HyperService;
12+
use reqwest::Client;
1213

1314
enum Server {
1415
Civet(CivetServer),
@@ -24,7 +25,9 @@ fn main() {
2425
env_logger::init();
2526

2627
let config = cargo_registry::Config::default();
27-
let app = App::new(&config);
28+
let client = Client::new();
29+
30+
let app = App::new(&config, Some(client));
2831
let app = cargo_registry::build_handler(Arc::new(app));
2932

3033
// On every server restart, ensure the categories available in the database match

src/config.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,6 @@ impl Default for Config {
6868
&api_protocol,
6969
),
7070
cdn: dotenv::var("S3_CDN").ok(),
71-
proxy: None,
7271
}
7372
}
7473
(Env::Production, Replica::ReadOnlyMirror) => {
@@ -89,7 +88,6 @@ impl Default for Config {
8988
&api_protocol,
9089
),
9190
cdn: dotenv::var("S3_CDN").ok(),
92-
proxy: None,
9391
}
9492
}
9593
// In Development mode, either running as a primary instance or a read-only mirror
@@ -109,7 +107,6 @@ impl Default for Config {
109107
&api_protocol,
110108
),
111109
cdn: dotenv::var("S3_CDN").ok(),
112-
proxy: None,
113110
}
114111
} else {
115112
// If we don't set the `S3_BUCKET` variable, we'll use a development-only

src/controllers/krate/metadata.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,7 @@ pub fn readme(req: &mut dyn Request) -> CargoResult<Response> {
169169
.app()
170170
.config
171171
.uploader
172-
.readme_location(crate_name, version)
173-
.ok_or_else(|| human("crate readme not found"))?;
172+
.readme_location(crate_name, version);
174173

175174
if req.wants_json() {
176175
#[derive(Serialize)]

0 commit comments

Comments
 (0)