-
Notifications
You must be signed in to change notification settings - Fork 599
/
mod.rs
1549 lines (1389 loc) · 50.2 KB
/
mod.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
use std::ascii::AsciiExt;
use std::cmp;
use std::collections::HashMap;
use std::sync::Arc;
use chrono::{NaiveDate, NaiveDateTime};
use conduit::{Request, Response};
use conduit_router::RequestParams;
use diesel::associations::Identifiable;
use diesel::expression::helper_types::Eq;
use diesel::helper_types::Select;
use diesel::pg::upsert::*;
use diesel::pg::Pg;
use diesel::prelude::*;
use diesel;
use diesel_full_text_search::*;
use license_exprs;
use hex::ToHex;
use serde_json;
use semver;
use url::Url;
use app::{App, RequestApp};
use badge::EncodableBadge;
use category::{CrateCategory, EncodableCategory};
use db::RequestTransaction;
use dependency::{self, EncodableDependency, ReverseDependency};
use download::{EncodableVersionDownload, VersionDownload};
use git;
use keyword::{CrateKeyword, EncodableKeyword};
use owner::{rights, CrateOwner, EncodableOwner, Owner, OwnerKind, Rights, Team};
use crate_owner_invitation::NewCrateOwnerInvitation;
use pagination::Paginate;
use render;
use schema::*;
use upload;
use user::RequestUser;
use util::{read_fill, read_le_u32};
use util::{human, internal, CargoResult, ChainError, RequestUtils};
use version::{EncodableVersion, NewVersion};
use {Badge, Category, Keyword, Replica, User, Version};
/// Hosts in this blacklist are known to not be hosting documentation,
/// and are possibly of malicious intent e.g. ad tracking networks, etc.
const DOCUMENTATION_BLACKLIST: [&'static str; 1] = ["rust-ci.org"];
#[derive(Debug, Insertable, Queryable, Identifiable, Associations, AsChangeset, Clone, Copy)]
#[belongs_to(Crate)]
#[primary_key(crate_id, date)]
#[table_name = "crate_downloads"]
pub struct CrateDownload {
pub crate_id: i32,
pub downloads: i32,
pub date: NaiveDate,
}
#[derive(Debug, Clone, Queryable, Identifiable, Associations, AsChangeset)]
pub struct Crate {
pub id: i32,
pub name: String,
pub updated_at: NaiveDateTime,
pub created_at: NaiveDateTime,
pub downloads: i32,
pub description: Option<String>,
pub homepage: Option<String>,
pub documentation: Option<String>,
pub readme: Option<String>,
pub license: Option<String>,
pub repository: Option<String>,
pub max_upload_size: Option<i32>,
}
/// We literally never want to select `textsearchable_index_col`
/// so we provide this type and constant to pass to `.select`
type AllColumns = (
crates::id,
crates::name,
crates::updated_at,
crates::created_at,
crates::downloads,
crates::description,
crates::homepage,
crates::documentation,
crates::readme,
crates::license,
crates::repository,
crates::max_upload_size,
);
pub const ALL_COLUMNS: AllColumns = (
crates::id,
crates::name,
crates::updated_at,
crates::created_at,
crates::downloads,
crates::description,
crates::homepage,
crates::documentation,
crates::readme,
crates::license,
crates::repository,
crates::max_upload_size,
);
pub const MAX_NAME_LENGTH: usize = 64;
type CrateQuery<'a> = crates::BoxedQuery<'a, Pg, <AllColumns as Expression>::SqlType>;
#[derive(Serialize, Deserialize, Debug)]
pub struct EncodableCrate {
pub id: String,
pub name: String,
pub updated_at: NaiveDateTime,
pub versions: Option<Vec<i32>>,
pub keywords: Option<Vec<String>>,
pub categories: Option<Vec<String>>,
pub badges: Option<Vec<EncodableBadge>>,
pub created_at: NaiveDateTime,
pub downloads: i32,
pub recent_downloads: Option<i64>,
pub max_version: String,
pub description: Option<String>,
pub homepage: Option<String>,
pub documentation: Option<String>,
pub repository: Option<String>,
pub links: CrateLinks,
pub exact_match: bool,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CrateLinks {
pub version_downloads: String,
pub versions: Option<String>,
pub owners: Option<String>,
pub owner_team: Option<String>,
pub owner_user: Option<String>,
pub reverse_dependencies: String,
}
#[derive(Insertable, AsChangeset, Default, Debug)]
#[table_name = "crates"]
#[primary_key(name, max_upload_size)] // This is actually just to skip updating them
pub struct NewCrate<'a> {
pub name: &'a str,
pub description: Option<&'a str>,
pub homepage: Option<&'a str>,
pub documentation: Option<&'a str>,
pub readme: Option<&'a str>,
pub repository: Option<&'a str>,
pub max_upload_size: Option<i32>,
pub license: Option<&'a str>,
}
impl<'a> NewCrate<'a> {
pub fn create_or_update(
mut self,
conn: &PgConnection,
license_file: Option<&'a str>,
uploader: i32,
) -> CargoResult<Crate> {
use diesel::update;
self.validate(license_file)?;
self.ensure_name_not_reserved(conn)?;
conn.transaction(|| {
// To avoid race conditions, we try to insert
// first so we know whether to add an owner
if let Some(krate) = self.save_new_crate(conn, uploader)? {
return Ok(krate);
}
let target = crates::table
.filter(canon_crate_name(crates::name).eq(canon_crate_name(self.name)));
update(target)
.set(&self)
.returning(ALL_COLUMNS)
.get_result(conn)
.map_err(Into::into)
})
}
fn validate(&mut self, license_file: Option<&'a str>) -> CargoResult<()> {
fn validate_url(url: Option<&str>, field: &str) -> CargoResult<()> {
let url = match url {
Some(s) => s,
None => return Ok(()),
};
let url = Url::parse(url).map_err(|_| {
human(&format_args!("`{}` is not a valid url: `{}`", field, url))
})?;
match &url.scheme()[..] {
"http" | "https" => {}
s => {
return Err(human(&format_args!(
"`{}` has an invalid url \
scheme: `{}`",
field,
s
)))
}
}
if url.cannot_be_a_base() {
return Err(human(&format_args!(
"`{}` must have relative scheme \
data: {}",
field,
url
)));
}
Ok(())
}
validate_url(self.homepage, "homepage")?;
validate_url(self.documentation, "documentation")?;
validate_url(self.repository, "repository")?;
self.validate_license(license_file)?;
Ok(())
}
fn validate_license(&mut self, license_file: Option<&str>) -> CargoResult<()> {
if let Some(license) = self.license {
for part in license.split('/') {
license_exprs::validate_license_expr(part).map_err(|e| {
human(&format_args!(
"{}; see http://opensource.org/licenses \
for options, and http://spdx.org/licenses/ \
for their identifiers",
e
))
})?;
}
} else if license_file.is_some() {
// If no license is given, but a license file is given, flag this
// crate as having a nonstandard license. Note that we don't
// actually do anything else with license_file currently.
self.license = Some("non-standard");
}
Ok(())
}
fn ensure_name_not_reserved(&self, conn: &PgConnection) -> CargoResult<()> {
use schema::reserved_crate_names::dsl::*;
use diesel::select;
use diesel::expression::dsl::exists;
let reserved_name = select(exists(
reserved_crate_names.filter(canon_crate_name(name).eq(canon_crate_name(self.name))),
)).get_result::<bool>(conn)?;
if reserved_name {
Err(human("cannot upload a crate with a reserved name"))
} else {
Ok(())
}
}
fn save_new_crate(&self, conn: &PgConnection, user_id: i32) -> QueryResult<Option<Crate>> {
use schema::crates::dsl::*;
use diesel::insert;
conn.transaction(|| {
let maybe_inserted = insert(&self.on_conflict_do_nothing())
.into(crates)
.returning(ALL_COLUMNS)
.get_result::<Crate>(conn)
.optional()?;
if let Some(ref krate) = maybe_inserted {
let owner = CrateOwner {
crate_id: krate.id,
owner_id: user_id,
created_by: user_id,
owner_kind: OwnerKind::User as i32,
};
insert(&owner).into(crate_owners::table).execute(conn)?;
}
Ok(maybe_inserted)
})
}
}
impl Crate {
pub fn by_name(name: &str) -> CrateQuery {
Crate::all()
.filter(Crate::name_canonically_equals(name))
.into_boxed()
}
pub fn all() -> Select<crates::table, AllColumns> {
crates::table.select(ALL_COLUMNS)
}
fn name_canonically_equals(
s: &str,
) -> Eq<canon_crate_name<crates::name>, canon_crate_name<&str>> {
canon_crate_name(crates::name).eq(canon_crate_name(s))
}
pub fn valid_name(name: &str) -> bool {
let under_max_length = name.chars().take(MAX_NAME_LENGTH + 1).count() <= MAX_NAME_LENGTH;
Crate::valid_ident(name) && under_max_length
}
fn valid_ident(name: &str) -> bool {
if name.is_empty() {
return false;
}
name.chars().next().unwrap().is_alphabetic()
&& name.chars()
.all(|c| c.is_alphanumeric() || c == '_' || c == '-')
&& name.chars().all(|c| c.is_ascii())
}
pub fn valid_feature_name(name: &str) -> bool {
let mut parts = name.split('/');
match parts.next() {
Some(part) if !Crate::valid_ident(part) => return false,
None => return false,
_ => {}
}
match parts.next() {
Some(part) if !Crate::valid_ident(part) => return false,
_ => {}
}
parts.next().is_none()
}
pub fn minimal_encodable(
self,
max_version: semver::Version,
badges: Option<Vec<Badge>>,
exact_match: bool,
recent_downloads: Option<i64>,
) -> EncodableCrate {
self.encodable(
max_version,
None,
None,
None,
badges,
exact_match,
recent_downloads,
)
}
#[cfg_attr(feature = "clippy", allow(too_many_arguments))]
pub fn encodable(
self,
max_version: semver::Version,
versions: Option<Vec<i32>>,
keywords: Option<&[Keyword]>,
categories: Option<&[Category]>,
badges: Option<Vec<Badge>>,
exact_match: bool,
recent_downloads: Option<i64>,
) -> EncodableCrate {
let Crate {
name,
created_at,
updated_at,
downloads,
description,
homepage,
documentation,
repository,
..
} = self;
let versions_link = match versions {
Some(..) => None,
None => Some(format!("/api/v1/crates/{}/versions", name)),
};
let keyword_ids = keywords.map(|kws| kws.iter().map(|kw| kw.keyword.clone()).collect());
let category_ids = categories.map(|cats| cats.iter().map(|cat| cat.slug.clone()).collect());
let badges = badges.map(|bs| bs.into_iter().map(|b| b.encodable()).collect());
let documentation = Crate::remove_blacklisted_documentation_urls(documentation);
EncodableCrate {
id: name.clone(),
name: name.clone(),
updated_at: updated_at,
created_at: created_at,
downloads: downloads,
recent_downloads: recent_downloads,
versions: versions,
keywords: keyword_ids,
categories: category_ids,
badges: badges,
max_version: max_version.to_string(),
documentation: documentation,
homepage: homepage,
exact_match: exact_match,
description: description,
repository: repository,
links: CrateLinks {
version_downloads: format!("/api/v1/crates/{}/downloads", name),
versions: versions_link,
owners: Some(format!("/api/v1/crates/{}/owners", name)),
owner_team: Some(format!("/api/v1/crates/{}/owner_team", name)),
owner_user: Some(format!("/api/v1/crates/{}/owner_user", name)),
reverse_dependencies: format!("/api/v1/crates/{}/reverse_dependencies", name),
},
}
}
/// Return `None` if the documentation URL host matches a blacklisted host
fn remove_blacklisted_documentation_urls(url: Option<String>) -> Option<String> {
// Handles if documentation URL is None
let url = match url {
Some(url) => url,
None => return None,
};
// Handles unsuccessful parsing of documentation URL
let parsed_url = match Url::parse(&url) {
Ok(parsed_url) => parsed_url,
Err(_) => return None,
};
// Extract host string from documentation URL
let url_host = match parsed_url.host_str() {
Some(url_host) => url_host,
None => return None,
};
// Match documentation URL host against blacklisted host array elements
if DOCUMENTATION_BLACKLIST.contains(&url_host) {
None
} else {
Some(url)
}
}
pub fn max_version(&self, conn: &PgConnection) -> CargoResult<semver::Version> {
use schema::versions::dsl::*;
let vs = Version::belonging_to(self)
.select(num)
.filter(yanked.eq(false))
.load::<String>(conn)?
.into_iter()
.map(|s| semver::Version::parse(&s).unwrap());
Ok(Version::max(vs))
}
pub fn owners(&self, conn: &PgConnection) -> CargoResult<Vec<Owner>> {
let base_query = CrateOwner::belonging_to(self).filter(crate_owners::deleted.eq(false));
let users = base_query
.inner_join(users::table)
.select(users::all_columns)
.filter(crate_owners::owner_kind.eq(OwnerKind::User as i32))
.load(conn)?
.into_iter()
.map(Owner::User);
let teams = base_query
.inner_join(teams::table)
.select(teams::all_columns)
.filter(crate_owners::owner_kind.eq(OwnerKind::Team as i32))
.load(conn)?
.into_iter()
.map(Owner::Team);
Ok(users.chain(teams).collect())
}
pub fn owner_add(
&self,
app: &App,
conn: &PgConnection,
req_user: &User,
login: &str,
) -> CargoResult<String> {
use diesel::insert;
let owner = Owner::find_or_create_by_login(app, conn, req_user, login)?;
match owner {
// Users are invited and must accept before being added
owner @ Owner::User(_) => {
let owner_invitation = NewCrateOwnerInvitation {
invited_user_id: owner.id(),
invited_by_user_id: req_user.id,
crate_id: self.id,
};
diesel::insert(&owner_invitation.on_conflict_do_nothing())
.into(crate_owner_invitations::table)
.execute(conn)?;
Ok(format!(
"user {} has been invited to be an owner of crate {}",
owner.login(),
self.name
))
}
// Teams are added as owners immediately
owner @ Owner::Team(_) => {
let crate_owner = CrateOwner {
crate_id: self.id,
owner_id: owner.id(),
created_by: req_user.id,
owner_kind: OwnerKind::Team as i32,
};
insert(&crate_owner.on_conflict(
crate_owners::table.primary_key(),
do_update().set(crate_owners::deleted.eq(false)),
)).into(crate_owners::table)
.execute(conn)?;
Ok(format!(
"team {} has been added as an owner of crate {}",
owner.login(),
self.name
))
}
}
}
pub fn owner_remove(
&self,
app: &App,
conn: &PgConnection,
req_user: &User,
login: &str,
) -> CargoResult<()> {
let owner = Owner::find_or_create_by_login(app, conn, req_user, login)?;
let target = crate_owners::table.find((self.id(), owner.id(), owner.kind() as i32));
diesel::update(target)
.set(crate_owners::deleted.eq(true))
.execute(conn)?;
Ok(())
}
pub fn badges(&self, conn: &PgConnection) -> QueryResult<Vec<Badge>> {
badges::table
.filter(badges::crate_id.eq(self.id))
.load(conn)
}
/// Returns (dependency, dependent crate name, dependent crate downloads)
pub fn reverse_dependencies(
&self,
conn: &PgConnection,
offset: i64,
limit: i64,
) -> QueryResult<(Vec<ReverseDependency>, i64)> {
use diesel::expression::dsl::sql;
use diesel::types::{BigInt, Integer, Text};
type SqlType = ((dependencies::SqlType, Integer, Text), BigInt);
let rows = sql::<SqlType>(include_str!("krate_reverse_dependencies.sql"))
.bind::<Integer, _>(self.id)
.bind::<BigInt, _>(offset)
.bind::<BigInt, _>(limit)
.load::<(ReverseDependency, i64)>(conn)?;
let (vec, counts): (_, Vec<_>) = rows.into_iter().unzip();
let cnt = counts.into_iter().nth(0).unwrap_or(0i64);
Ok((vec, cnt))
}
}
/// Handles the `GET /crates` route.
/// Returns a list of crates. Called in a variety of scenarios in the
/// front end, including:
/// - Alphabetical listing of crates
/// - List of crates under a specific owner
/// - Listing a user's followed crates
///
/// Notes:
/// The different use cases this function covers is handled through passing
/// in parameters in the GET request.
///
/// We would like to stop adding functionality in here. It was built like
/// this to keep the number of database queries low, though given Rust's
/// low performance overhead, this is a soft goal to have, and can afford
/// more database transactions if it aids understandability.
///
/// All of the edge cases for this function are not currently covered
/// in testing, and if they fail, it is difficult to determine what
/// caused the break. In the future, we should look at splitting this
/// function out to cover the different use cases, and create unit tests
/// for them.
pub fn index(req: &mut Request) -> CargoResult<Response> {
use diesel::expression::{AsExpression, DayAndMonthIntervalDsl};
use diesel::types::{BigInt, Bool, Nullable};
use diesel::expression::functions::date_and_time::{date, now};
use diesel::expression::sql_literal::sql;
let conn = req.db_conn()?;
let (offset, limit) = req.pagination(10, 100)?;
let params = req.query();
let sort = params
.get("sort")
.map(|s| &**s)
.unwrap_or("recent-downloads");
let recent_downloads = sql::<Nullable<BigInt>>("SUM(crate_downloads.downloads)");
let mut query = crates::table
.left_join(
crate_downloads::table.on(
crates::id
.eq(crate_downloads::crate_id)
.and(crate_downloads::date.gt(date(now - 90.days()))),
),
)
.group_by(crates::id)
.select((
ALL_COLUMNS,
AsExpression::<Bool>::as_expression(false),
recent_downloads.clone(),
))
.into_boxed();
if sort == "downloads" {
query = query.order(crates::downloads.desc())
} else if sort == "recent-downloads" {
query = query.order(recent_downloads.clone().desc().nulls_last())
} else {
query = query.order(crates::name.asc())
}
if let Some(q_string) = params.get("q") {
let sort = params.get("sort").map(|s| &**s).unwrap_or("relevance");
let q = plainto_tsquery(q_string);
query = query.filter(
q.matches(crates::textsearchable_index_col)
.or(Crate::name_canonically_equals(q_string)),
);
query = query.select((
ALL_COLUMNS,
Crate::name_canonically_equals(q_string),
recent_downloads.clone(),
));
let perfect_match = Crate::name_canonically_equals(q_string).desc();
if sort == "downloads" {
query = query.order((perfect_match, crates::downloads.desc()));
} else if sort == "recent-downloads" {
query = query.order((
perfect_match,
recent_downloads.clone().desc().nulls_last(),
));
} else {
let rank = ts_rank_cd(crates::textsearchable_index_col, q);
query = query.order((perfect_match, rank.desc()))
}
}
if let Some(cat) = params.get("category") {
query = query.filter(
crates::id.eq_any(
crates_categories::table
.select(crates_categories::crate_id)
.inner_join(categories::table)
.filter(
categories::slug
.eq(cat)
.or(categories::slug.like(format!("{}::%", cat))),
),
),
);
}
if let Some(kw) = params.get("keyword") {
query = query.filter(
crates::id.eq_any(
crates_keywords::table
.select(crates_keywords::crate_id)
.inner_join(keywords::table)
.filter(::lower(keywords::keyword).eq(::lower(kw))),
),
);
} else if let Some(letter) = params.get("letter") {
let pattern = format!(
"{}%",
letter
.chars()
.next()
.unwrap()
.to_lowercase()
.collect::<String>()
);
query = query.filter(canon_crate_name(crates::name).like(pattern));
} else if let Some(user_id) = params.get("user_id").and_then(|s| s.parse::<i32>().ok()) {
query = query.filter(
crates::id.eq_any(
crate_owners::table
.select(crate_owners::crate_id)
.filter(crate_owners::owner_id.eq(user_id))
.filter(crate_owners::deleted.eq(false))
.filter(crate_owners::owner_kind.eq(OwnerKind::User as i32)),
),
);
} else if let Some(team_id) = params.get("team_id").and_then(|s| s.parse::<i32>().ok()) {
query = query.filter(
crates::id.eq_any(
crate_owners::table
.select(crate_owners::crate_id)
.filter(crate_owners::owner_id.eq(team_id))
.filter(crate_owners::deleted.eq(false))
.filter(crate_owners::owner_kind.eq(OwnerKind::Team as i32)),
),
);
} else if params.get("following").is_some() {
query = query.filter(
crates::id.eq_any(
follows::table
.select(follows::crate_id)
.filter(follows::user_id.eq(req.user()?.id)),
),
);
}
// The database query returns a tuple within a tuple , with the root
// tuple containing 3 items.
let data = query
.paginate(limit, offset)
.load::<((Crate, bool, Option<i64>), i64)>(&*conn)?;
let total = data.first().map(|&(_, t)| t).unwrap_or(0);
let crates = data.iter()
.map(|&((ref c, _, _), _)| c.clone())
.collect::<Vec<_>>();
let perfect_matches = data.clone()
.into_iter()
.map(|((_, b, _), _)| b)
.collect::<Vec<_>>();
let recent_downloads = data.clone()
.into_iter()
.map(|((_, _, s), _)| s.unwrap_or(0))
.collect::<Vec<_>>();
let versions = Version::belonging_to(&crates)
.load::<Version>(&*conn)?
.grouped_by(&crates)
.into_iter()
.map(|versions| Version::max(versions.into_iter().map(|v| v.num)));
let crates = versions
.zip(crates)
.zip(perfect_matches)
.zip(recent_downloads)
.map(
|(((max_version, krate), perfect_match), recent_downloads)| {
// FIXME: If we add crate_id to the Badge enum we can eliminate
// this N+1
let badges = badges::table
.filter(badges::crate_id.eq(krate.id))
.load::<Badge>(&*conn)?;
Ok(krate.minimal_encodable(
max_version,
Some(badges),
perfect_match,
Some(recent_downloads),
))
},
)
.collect::<Result<_, ::diesel::result::Error>>()?;
#[derive(Serialize)]
struct R {
crates: Vec<EncodableCrate>,
meta: Meta,
}
#[derive(Serialize)]
struct Meta {
total: i64,
}
Ok(req.json(&R {
crates: crates,
meta: Meta { total: total },
}))
}
/// Handles the `GET /summary` route.
pub fn summary(req: &mut Request) -> CargoResult<Response> {
use diesel::expression::{date, now, sql, DayAndMonthIntervalDsl};
use diesel::types::{BigInt, Nullable};
use schema::crates::dsl::*;
let conn = req.db_conn()?;
let num_crates = crates.count().get_result(&*conn)?;
let num_downloads = metadata::table
.select(metadata::total_downloads)
.get_result(&*conn)?;
let encode_crates = |krates: Vec<Crate>| -> CargoResult<Vec<_>> {
Version::belonging_to(&krates)
.filter(versions::yanked.eq(false))
.load::<Version>(&*conn)?
.grouped_by(&krates)
.into_iter()
.map(|versions| Version::max(versions.into_iter().map(|v| v.num)))
.zip(krates)
.map(|(max_version, krate)| {
Ok(krate.minimal_encodable(max_version, None, false, None))
})
.collect()
};
let new_crates = crates
.order(created_at.desc())
.select(ALL_COLUMNS)
.limit(10)
.load(&*conn)?;
let just_updated = crates
.filter(updated_at.ne(created_at))
.order(updated_at.desc())
.select(ALL_COLUMNS)
.limit(10)
.load(&*conn)?;
let most_downloaded = crates
.order(downloads.desc())
.select(ALL_COLUMNS)
.limit(10)
.load(&*conn)?;
let recent_downloads = sql::<Nullable<BigInt>>("SUM(crate_downloads.downloads)");
let most_recently_downloaded = crates
.left_join(
crate_downloads::table.on(
id.eq(crate_downloads::crate_id)
.and(crate_downloads::date.gt(date(now - 90.days()))),
),
)
.group_by(id)
.order(recent_downloads.desc().nulls_last())
.limit(10)
.select(ALL_COLUMNS)
.load::<Crate>(&*conn)?;
let popular_keywords = keywords::table
.order(keywords::crates_cnt.desc())
.limit(10)
.load(&*conn)?
.into_iter()
.map(Keyword::encodable)
.collect();
let popular_categories = Category::toplevel(&conn, "crates", 10, 0)?
.into_iter()
.map(Category::encodable)
.collect();
#[derive(Serialize)]
struct R {
num_downloads: i64,
num_crates: i64,
new_crates: Vec<EncodableCrate>,
most_downloaded: Vec<EncodableCrate>,
most_recently_downloaded: Vec<EncodableCrate>,
just_updated: Vec<EncodableCrate>,
popular_keywords: Vec<EncodableKeyword>,
popular_categories: Vec<EncodableCategory>,
}
Ok(req.json(&R {
num_downloads: num_downloads,
num_crates: num_crates,
new_crates: encode_crates(new_crates)?,
most_downloaded: encode_crates(most_downloaded)?,
most_recently_downloaded: encode_crates(most_recently_downloaded)?,
just_updated: encode_crates(just_updated)?,
popular_keywords: popular_keywords,
popular_categories: popular_categories,
}))
}
/// Handles the `GET /crates/:crate_id` route.
pub fn show(req: &mut Request) -> CargoResult<Response> {
use diesel::expression::dsl::*;
let name = &req.params()["crate_id"];
let conn = req.db_conn()?;
let krate = Crate::by_name(name).first::<Crate>(&*conn)?;
let mut versions = Version::belonging_to(&krate).load::<Version>(&*conn)?;
versions.sort_by(|a, b| b.num.cmp(&a.num));
let ids = versions.iter().map(|v| v.id).collect();
let kws = CrateKeyword::belonging_to(&krate)
.inner_join(keywords::table)
.select(keywords::all_columns)
.load(&*conn)?;
let cats = CrateCategory::belonging_to(&krate)
.inner_join(categories::table)
.select(categories::all_columns)
.load(&*conn)?;
let recent_downloads = CrateDownload::belonging_to(&krate)
.filter(crate_downloads::date.gt(date(now - 90.days())))
.select(sum(crate_downloads::downloads))
.get_result(&*conn)?;
let badges = badges::table
.filter(badges::crate_id.eq(krate.id))
.load(&*conn)?;
let max_version = krate.max_version(&conn)?;
#[derive(Serialize)]
struct R {
#[serde(rename = "crate")] krate: EncodableCrate,
versions: Vec<EncodableVersion>,
keywords: Vec<EncodableKeyword>,
categories: Vec<EncodableCategory>,
}
Ok(
req.json(&R {
krate: krate.clone().encodable(
max_version,
Some(ids),
Some(&kws),
Some(&cats),
Some(badges),
false,
recent_downloads,
),
versions: versions
.into_iter()
.map(|v| v.encodable(&krate.name))
.collect(),
keywords: kws.into_iter().map(|k| k.encodable()).collect(),
categories: cats.into_iter().map(|k| k.encodable()).collect(),
}),
)
}
/// Handles the `PUT /crates/new` route.
/// Used by `cargo publish` to publish a new crate or to publish a new version of an
/// existing crate.
///
/// Currently blocks the HTTP thread, perhaps some function calls can spawn new
/// threads and return completion or error through other methods a `cargo publish
/// --status` command, via crates.io's front end, or email.
pub fn new(req: &mut Request) -> CargoResult<Response> {
let app = Arc::clone(req.app());
let (new_crate, user) = parse_new_headers(req)?;
let name = &*new_crate.name;
let vers = &*new_crate.vers;
let features = new_crate
.features
.iter()
.map(|(k, v)| {
(
k[..].to_string(),
v.iter().map(|v| v[..].to_string()).collect(),
)
})
.collect::<HashMap<String, Vec<String>>>();
let keywords = new_crate
.keywords
.as_ref()
.map(|kws| kws.iter().map(|kw| &**kw).collect())
.unwrap_or_else(Vec::new);
let categories = new_crate.categories.as_ref().map(|s| &s[..]).unwrap_or(&[]);
let categories: Vec<_> = categories.iter().map(|k| &**k).collect();
let conn = req.db_conn()?;
// Create a transaction on the database, if there are no errors,
// commit the transactions to record a new or updated crate.
conn.transaction(|| {
// Persist the new crate, if it doesn't already exist
let persist = NewCrate {
name: name,
description: new_crate.description.as_ref().map(|s| &**s),
homepage: new_crate.homepage.as_ref().map(|s| &**s),
documentation: new_crate.documentation.as_ref().map(|s| &**s),
readme: new_crate.readme.as_ref().map(|s| &**s),
repository: new_crate.repository.as_ref().map(|s| &**s),
license: new_crate.license.as_ref().map(|s| &**s),
max_upload_size: None,
};
let license_file = new_crate.license_file.as_ref().map(|s| &**s);
let krate = persist.create_or_update(&conn, license_file, user.id)?;
let owners = krate.owners(&conn)?;
if rights(req.app(), &owners, &user)? < Rights::Publish {
return Err(human(
"this crate exists but you don't seem to be an owner. \
If you believe this is a mistake, perhaps you need \
to accept an invitation to be an owner before \
publishing.",
));
}
if krate.name != name {
return Err(human(
&format_args!("crate was previously named `{}`", krate.name),
));
}
let length = req.content_length()
.chain_error(|| human("missing header: Content-Length"))?;
let max = krate
.max_upload_size