forked from rust-lang/docs.rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcratesfyi.rs
972 lines (855 loc) · 31.9 KB
/
cratesfyi.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
use std::env;
use std::fmt::Write;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use anyhow::{Context as _, Error, Result, anyhow};
use clap::{Parser, Subcommand, ValueEnum};
use docs_rs::cdn::CdnBackend;
use docs_rs::db::{self, CrateId, Overrides, Pool, add_path_into_database};
use docs_rs::repositories::RepositoryStatsUpdater;
use docs_rs::utils::{
ConfigName, get_config, get_crate_pattern_and_priority, list_crate_priorities, queue_builder,
remove_crate_priority, set_config, set_crate_priority,
};
use docs_rs::{
AsyncBuildQueue, AsyncStorage, BuildQueue, Config, Context, Index, InstanceMetrics,
PackageKind, RegistryApi, RustwideBuilder, ServiceMetrics, Storage,
start_background_metrics_webserver, start_web_server,
};
use futures_util::StreamExt;
use humantime::Duration;
use once_cell::sync::OnceCell;
use sentry::{
TransactionContext, integrations::panic as sentry_panic,
integrations::tracing as sentry_tracing,
};
use tokio::runtime::{Builder, Runtime};
use tracing_log::LogTracer;
use tracing_subscriber::{EnvFilter, filter::Directive, prelude::*};
fn main() {
// set the global log::logger for backwards compatibility
// through rustwide.
rustwide::logging::init_with(LogTracer::new());
let log_formatter = {
let log_format = env::var("DOCSRS_LOG_FORMAT").unwrap_or_default();
if log_format == "json" {
tracing_subscriber::fmt::layer().json().boxed()
} else {
tracing_subscriber::fmt::layer().boxed()
}
};
let tracing_registry = tracing_subscriber::registry().with(log_formatter).with(
EnvFilter::builder()
.with_default_directive(Directive::from_str("docs_rs=info").unwrap())
.with_env_var("DOCSRS_LOG")
.from_env_lossy(),
);
let _sentry_guard = if let Ok(sentry_dsn) = env::var("SENTRY_DSN") {
tracing::subscriber::set_global_default(tracing_registry.with(
sentry_tracing::layer().event_filter(|md| {
if md.fields().field("reported_to_sentry").is_some() {
sentry_tracing::EventFilter::Ignore
} else {
sentry_tracing::default_event_filter(md)
}
}),
))
.unwrap();
let traces_sample_rate = env::var("SENTRY_TRACES_SAMPLE_RATE")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.0);
let traces_sampler = move |ctx: &TransactionContext| -> f32 {
if let Some(sampled) = ctx.sampled() {
// if the transaction was already marked as "to be sampled" by
// the JS/frontend SDK, we want to sample it in the backend too.
return if sampled { 1.0 } else { 0.0 };
}
let op = ctx.operation();
if op == "docbuilder.build_package" {
// record all transactions for builds
1.
} else {
traces_sample_rate
}
};
Some(sentry::init((
sentry_dsn,
sentry::ClientOptions {
release: Some(docs_rs::BUILD_VERSION.into()),
attach_stacktrace: true,
traces_sampler: Some(Arc::new(traces_sampler)),
..Default::default()
}
.add_integration(sentry_panic::PanicIntegration::default()),
)))
} else {
tracing::subscriber::set_global_default(tracing_registry).unwrap();
None
};
if let Err(err) = CommandLine::parse().handle_args() {
let mut msg = format!("Error: {err}");
for cause in err.chain() {
write!(msg, "\n\nCaused by:\n {cause}").unwrap();
}
eprintln!("{msg}");
let backtrace = err.backtrace().to_string();
if !backtrace.is_empty() {
eprintln!("\nStack backtrace:\n{backtrace}");
}
// we need to drop the sentry guard here so all unsent
// errors are sent to sentry before
// process::exit kills everything.
drop(_sentry_guard);
std::process::exit(1);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "snake_case")]
enum Toggle {
Enabled,
Disabled,
}
#[derive(Debug, Clone, PartialEq, Eq, Parser)]
#[command(
about = env!("CARGO_PKG_DESCRIPTION"),
version = docs_rs::BUILD_VERSION,
rename_all = "kebab-case",
)]
enum CommandLine {
Build {
#[command(subcommand)]
subcommand: BuildSubcommand,
},
/// Starts web server
StartWebServer {
#[arg(name = "SOCKET_ADDR", default_value = "0.0.0.0:3000")]
socket_addr: SocketAddr,
},
StartRegistryWatcher {
#[arg(name = "SOCKET_ADDR", default_value = "0.0.0.0:3000")]
metric_server_socket_addr: SocketAddr,
/// Enable or disable the repository stats updater
#[arg(
long = "repository-stats-updater",
default_value = "disabled",
value_enum
)]
repository_stats_updater: Toggle,
#[arg(long = "cdn-invalidator", default_value = "enabled", value_enum)]
cdn_invalidator: Toggle,
#[arg(long = "queue-rebuilds", default_value = "enabled", value_enum)]
queue_rebuilds: Toggle,
},
StartBuildServer {
#[arg(name = "SOCKET_ADDR", default_value = "0.0.0.0:3000")]
metric_server_socket_addr: SocketAddr,
},
/// Starts the daemon
Daemon {
/// Enable or disable the registry watcher to automatically enqueue newly published crates
#[arg(long = "registry-watcher", default_value = "enabled", value_enum)]
registry_watcher: Toggle,
},
/// Database operations
Database {
#[command(subcommand)]
subcommand: DatabaseSubcommand,
},
/// Interactions with the build queue
Queue {
#[command(subcommand)]
subcommand: QueueSubcommand,
},
}
impl CommandLine {
fn handle_args(self) -> Result<()> {
let ctx = BinContext::new();
match self {
Self::Build { subcommand } => subcommand.handle_args(ctx)?,
Self::StartRegistryWatcher {
metric_server_socket_addr,
repository_stats_updater,
cdn_invalidator,
queue_rebuilds,
} => {
if repository_stats_updater == Toggle::Enabled {
docs_rs::utils::daemon::start_background_repository_stats_updater(&ctx)?;
}
if cdn_invalidator == Toggle::Enabled {
docs_rs::utils::daemon::start_background_cdn_invalidator(&ctx)?;
}
if queue_rebuilds == Toggle::Enabled {
docs_rs::utils::daemon::start_background_queue_rebuild(&ctx)?;
}
start_background_metrics_webserver(Some(metric_server_socket_addr), &ctx)?;
ctx.runtime()?.block_on(async {
docs_rs::utils::watch_registry(
ctx.async_build_queue().await?,
ctx.config()?,
ctx.index()?,
)
.await
})?;
}
Self::StartBuildServer {
metric_server_socket_addr,
} => {
start_background_metrics_webserver(Some(metric_server_socket_addr), &ctx)?;
let build_queue = ctx.build_queue()?;
let config = ctx.config()?;
let rustwide_builder = RustwideBuilder::init(&ctx)?;
queue_builder(&ctx, rustwide_builder, build_queue, config)?;
}
Self::StartWebServer { socket_addr } => {
// Blocks indefinitely
start_web_server(Some(socket_addr), &ctx)?;
}
Self::Daemon { registry_watcher } => {
docs_rs::utils::start_daemon(ctx, registry_watcher == Toggle::Enabled)?;
}
Self::Database { subcommand } => subcommand.handle_args(ctx)?,
Self::Queue { subcommand } => subcommand.handle_args(ctx)?,
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
enum QueueSubcommand {
/// Add a crate to the build queue
Add {
/// Name of crate to build
#[arg(name = "CRATE_NAME")]
crate_name: String,
/// Version of crate to build
#[arg(name = "CRATE_VERSION")]
crate_version: String,
/// Priority of build (new crate builds get priority 0)
#[arg(
name = "BUILD_PRIORITY",
short = 'p',
long = "priority",
default_value = "5",
allow_negative_numbers = true
)]
build_priority: i32,
},
/// Interactions with build queue priorities
DefaultPriority {
#[command(subcommand)]
subcommand: PrioritySubcommand,
},
/// Get the registry watcher's last seen reference
GetLastSeenReference,
/// Set the registry watcher's last seen reference
#[command(arg_required_else_help(true))]
SetLastSeenReference {
/// The reference to set to, required unless flag used
#[arg(conflicts_with("head"))]
reference: Option<crates_index_diff::gix::ObjectId>,
/// Fetch the current HEAD of the remote index and use it
#[arg(long, conflicts_with("reference"))]
head: bool,
},
}
impl QueueSubcommand {
fn handle_args(self, ctx: BinContext) -> Result<()> {
let build_queue = ctx.build_queue()?;
match self {
Self::Add {
crate_name,
crate_version,
build_priority,
} => build_queue.add_crate(
&crate_name,
&crate_version,
build_priority,
ctx.config()?.registry_url.as_deref(),
)?,
Self::GetLastSeenReference => {
if let Some(reference) = build_queue.last_seen_reference()? {
println!("Last seen reference: {reference}");
} else {
println!("No last seen reference available");
}
}
Self::SetLastSeenReference { reference, head } => {
let reference = match (reference, head) {
(Some(reference), false) => reference,
(None, true) => {
println!("Fetching changes to set reference to HEAD");
let (_, oid) = ctx.index()?.diff()?.peek_changes()?;
oid
}
(_, _) => unreachable!(),
};
build_queue.set_last_seen_reference(reference)?;
println!("Set last seen reference: {reference}");
}
Self::DefaultPriority { subcommand } => subcommand.handle_args(ctx)?,
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
enum PrioritySubcommand {
/// Get priority for a crate
///
/// (returns only the first matching pattern, there may be other matching patterns)
Get { crate_name: String },
/// List priorities for all patterns
List,
/// Set all crates matching a pattern to a priority level
Set {
/// See https://www.postgresql.org/docs/current/functions-matching.html for pattern syntax
#[arg(name = "PATTERN")]
pattern: String,
/// The priority to give crates matching the given `PATTERN`
#[arg(allow_negative_numbers = true)]
priority: i32,
},
/// Remove the prioritization of crates for a pattern
Remove {
/// See https://www.postgresql.org/docs/current/functions-matching.html for pattern syntax
#[arg(name = "PATTERN")]
pattern: String,
},
}
impl PrioritySubcommand {
fn handle_args(self, ctx: BinContext) -> Result<()> {
ctx.runtime()?.block_on(async move {
let mut conn = ctx.pool()?.get_async().await?;
match self {
Self::List => {
for (pattern, priority) in list_crate_priorities(&mut conn).await? {
println!("{pattern:>20} : {priority:>3}");
}
}
Self::Get { crate_name } => {
if let Some((pattern, priority)) =
get_crate_pattern_and_priority(&mut conn, &crate_name).await?
{
println!("{pattern} : {priority}");
} else {
println!("No priority found for {crate_name}");
}
}
Self::Set { pattern, priority } => {
set_crate_priority(&mut conn, &pattern, priority)
.await
.context("Could not set pattern's priority")?;
println!("Set pattern '{pattern}' to priority {priority}");
}
Self::Remove { pattern } => {
if let Some(priority) = remove_crate_priority(&mut conn, &pattern)
.await
.context("Could not remove pattern's priority")?
{
println!("Removed pattern '{pattern}' with priority {priority}");
} else {
println!("Pattern '{pattern}' did not exist and so was not removed");
}
}
}
Ok(())
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
enum BuildSubcommand {
/// Builds documentation for a crate
Crate {
/// Crate name
#[arg(name = "CRATE_NAME", requires("CRATE_VERSION"))]
crate_name: Option<String>,
/// Version of crate
#[arg(name = "CRATE_VERSION")]
crate_version: Option<String>,
/// Build a crate at a specific path
#[arg(short = 'l', long = "local", conflicts_with_all(&["CRATE_NAME", "CRATE_VERSION"]))]
local: Option<PathBuf>,
},
/// update the currently installed rustup toolchain
UpdateToolchain {
/// Update the toolchain only if no toolchain is currently installed
#[arg(name = "ONLY_FIRST_TIME", long = "only-first-time")]
only_first_time: bool,
},
/// Adds essential files for the installed version of rustc
AddEssentialFiles,
SetToolchain {
toolchain_name: String,
},
/// Locks the daemon, preventing it from building new crates
Lock,
/// Unlocks the daemon to continue building new crates
Unlock,
}
impl BuildSubcommand {
fn handle_args(self, ctx: BinContext) -> Result<()> {
let build_queue = ctx.build_queue()?;
let rustwide_builder = || -> Result<RustwideBuilder> { RustwideBuilder::init(&ctx) };
match self {
Self::Crate {
crate_name,
crate_version,
local,
} => {
let mut builder = rustwide_builder()?;
if let Some(path) = local {
builder
.build_local_package(&path)
.context("Building documentation failed")?;
} else {
let registry_url = ctx.config()?.registry_url.clone();
builder
.build_package(
&crate_name
.with_context(|| anyhow!("must specify name if not local"))?,
&crate_version
.with_context(|| anyhow!("must specify version if not local"))?,
registry_url
.as_ref()
.map(|s| PackageKind::Registry(s.as_str()))
.unwrap_or(PackageKind::CratesIo),
)
.context("Building documentation failed")?;
}
}
Self::UpdateToolchain { only_first_time } => {
let rustc_version = ctx.runtime()?.block_on({
let pool = ctx.pool()?;
async move {
let mut conn = pool
.get_async()
.await
.context("failed to get a database connection")?;
get_config::<String>(&mut conn, ConfigName::RustcVersion).await
}
})?;
if only_first_time && rustc_version.is_some() {
println!("update-toolchain was already called in the past, exiting");
return Ok(());
}
rustwide_builder()?
.update_toolchain()
.context("failed to update toolchain")?;
rustwide_builder()?
.purge_caches()
.context("failed to purge caches")?;
rustwide_builder()?
.add_essential_files()
.context("failed to add essential files")?;
}
Self::AddEssentialFiles => {
rustwide_builder()?
.add_essential_files()
.context("failed to add essential files")?;
}
Self::SetToolchain { toolchain_name } => {
ctx.runtime()?.block_on(async move {
let mut conn = ctx
.pool()?
.get_async()
.await
.context("failed to get a database connection")?;
set_config(&mut conn, ConfigName::Toolchain, toolchain_name)
.await
.context("failed to set toolchain in database")
})?;
}
Self::Lock => build_queue.lock().context("Failed to lock")?,
Self::Unlock => build_queue.unlock().context("Failed to unlock")?,
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
enum DatabaseSubcommand {
/// Run database migration
Migrate {
/// The database version to migrate to
#[arg(name = "VERSION")]
version: Option<i64>,
},
/// temporary command to update the `crates.latest_version_id` field
UpdateLatestVersionId,
/// Updates GitHub/GitLab stats for crates.
UpdateRepositoryFields,
/// Backfill GitHub/GitLab stats for crates.
BackfillRepositoryStats,
/// Updates info for a crate from the registry's API
UpdateCrateRegistryFields {
#[arg(name = "CRATE")]
name: String,
},
AddDirectory {
/// Path of file or directory
#[arg(name = "DIRECTORY")]
directory: PathBuf,
},
/// Remove documentation from the database
Delete {
#[command(subcommand)]
command: DeleteSubcommand,
},
/// Blacklist operations
Blacklist {
#[command(subcommand)]
command: BlacklistSubcommand,
},
/// Limit overrides operations
Limits {
#[command(subcommand)]
command: LimitsSubcommand,
},
/// Compares the database with the index and resolves inconsistencies
Synchronize {
/// Don't actually resolve the inconsistencies, just log them
#[arg(long)]
dry_run: bool,
},
}
impl DatabaseSubcommand {
fn handle_args(self, ctx: BinContext) -> Result<()> {
match self {
Self::Migrate { version } => {
let pool = ctx.pool()?;
ctx.runtime()?
.block_on(async {
let mut conn = pool.get_async().await?;
db::migrate(&mut conn, version).await
})
.context("Failed to run database migrations")?
}
Self::UpdateLatestVersionId => {
let pool = ctx.pool()?;
ctx.runtime()?
.block_on(async {
let mut list_conn = pool.get_async().await?;
let mut update_conn = pool.get_async().await?;
let mut result_stream = sqlx::query!(
r#"SELECT id as "id: CrateId", name FROM crates ORDER BY name"#
)
.fetch(&mut *list_conn);
while let Some(row) = result_stream.next().await {
let row = row?;
println!("handling crate {}", row.name);
db::update_latest_version_id(&mut update_conn, row.id).await?;
}
Ok::<(), anyhow::Error>(())
})
.context("Failed to update latest version id")?
}
Self::UpdateRepositoryFields => {
ctx.runtime()?
.block_on(ctx.repository_stats_updater()?.update_all_crates())?;
}
Self::BackfillRepositoryStats => {
ctx.runtime()?
.block_on(ctx.repository_stats_updater()?.backfill_repositories())?;
}
Self::UpdateCrateRegistryFields { name } => ctx.runtime()?.block_on(async move {
let mut conn = ctx.pool()?.get_async().await?;
let registry_data = ctx.registry_api()?.get_crate_data(&name).await?;
db::update_crate_data_in_database(&mut conn, &name, ®istry_data).await
})?,
Self::AddDirectory { directory } => {
ctx.runtime()?
.block_on(async {
let storage = ctx.async_storage().await?;
add_path_into_database(&storage, &ctx.config()?.prefix, directory).await
})
.context("Failed to add directory into database")?;
}
Self::Delete {
command: DeleteSubcommand::Version { name, version },
} => ctx
.runtime()?
.block_on(async move {
let mut conn = ctx.pool()?.get_async().await?;
db::delete_version(
&mut conn,
&*ctx.async_storage().await?,
&*ctx.config()?,
&name,
&version,
)
.await
})
.context("failed to delete the version")?,
Self::Delete {
command: DeleteSubcommand::Crate { name },
} => ctx
.runtime()?
.block_on(async move {
let mut conn = ctx.pool()?.get_async().await?;
db::delete_crate(
&mut conn,
&*ctx.async_storage().await?,
&*ctx.config()?,
&name,
)
.await
})
.context("failed to delete the crate")?,
Self::Blacklist { command } => command.handle_args(ctx)?,
Self::Limits { command } => command.handle_args(ctx)?,
Self::Synchronize { dry_run } => {
ctx.runtime()?
.block_on(docs_rs::utils::consistency::run_check(&ctx, dry_run))?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
enum LimitsSubcommand {
/// Get sandbox limit overrides for a crate
Get { crate_name: String },
/// List sandbox limit overrides for all crates
List,
/// Set sandbox limits overrides for a crate
Set {
crate_name: String,
#[arg(long)]
memory: Option<usize>,
#[arg(long)]
targets: Option<usize>,
#[arg(long)]
timeout: Option<Duration>,
},
/// Remove sandbox limits overrides for a crate
Remove { crate_name: String },
}
impl LimitsSubcommand {
fn handle_args(self, ctx: BinContext) -> Result<()> {
let pool = ctx.pool()?;
ctx.runtime()?.block_on(async move {
let mut conn = pool.get_async().await?;
match self {
Self::Get { crate_name } => {
let overrides = Overrides::for_crate(&mut conn, &crate_name).await?;
println!("sandbox limit overrides for {crate_name} = {overrides:?}");
}
Self::List => {
for (crate_name, overrides) in Overrides::all(&mut conn).await? {
println!("sandbox limit overrides for {crate_name} = {overrides:?}");
}
}
Self::Set {
crate_name,
memory,
targets,
timeout,
} => {
let overrides = Overrides::for_crate(&mut conn, &crate_name).await?;
println!("previous sandbox limit overrides for {crate_name} = {overrides:?}");
let overrides = Overrides {
memory,
targets,
timeout: timeout.map(Into::into),
};
Overrides::save(&mut conn, &crate_name, overrides).await?;
let overrides = Overrides::for_crate(&mut conn, &crate_name).await?;
println!("new sandbox limit overrides for {crate_name} = {overrides:?}");
}
Self::Remove { crate_name } => {
let overrides = Overrides::for_crate(&mut conn, &crate_name).await?;
println!("previous overrides for {crate_name} = {overrides:?}");
Overrides::remove(&mut conn, &crate_name).await?;
}
}
Ok(())
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
enum BlacklistSubcommand {
/// List all crates on the blacklist
List,
/// Add a crate to the blacklist
Add {
/// Crate name
#[arg(name = "CRATE_NAME")]
crate_name: String,
},
/// Remove a crate from the blacklist
Remove {
/// Crate name
#[arg(name = "CRATE_NAME")]
crate_name: String,
},
}
impl BlacklistSubcommand {
fn handle_args(self, ctx: BinContext) -> Result<()> {
ctx.runtime()?.block_on(async {
let conn = &mut *ctx.pool()?.get_async().await?;
match self {
Self::List => {
let crates = db::blacklist::list_crates(conn)
.await
.context("failed to list crates on blacklist")?;
println!("{}", crates.join("\n"));
}
Self::Add { crate_name } => db::blacklist::add_crate(conn, &crate_name)
.await
.context("failed to add crate to blacklist")?,
Self::Remove { crate_name } => db::blacklist::remove_crate(conn, &crate_name)
.await
.context("failed to remove crate from blacklist")?,
}
Ok(())
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Subcommand)]
enum DeleteSubcommand {
/// Delete a whole crate
Crate {
/// Name of the crate to delete
#[arg(name = "CRATE_NAME")]
name: String,
},
/// Delete a single version of a crate (which may include multiple builds)
Version {
/// Name of the crate to delete
#[arg(name = "CRATE_NAME")]
name: String,
/// The version of the crate to delete
#[arg(name = "VERSION")]
version: String,
},
}
struct BinContext {
build_queue: OnceCell<Arc<BuildQueue>>,
async_build_queue: tokio::sync::OnceCell<Arc<AsyncBuildQueue>>,
storage: OnceCell<Arc<Storage>>,
cdn: tokio::sync::OnceCell<Arc<CdnBackend>>,
config: OnceCell<Arc<Config>>,
pool: OnceCell<Pool>,
service_metrics: OnceCell<Arc<ServiceMetrics>>,
instance_metrics: OnceCell<Arc<InstanceMetrics>>,
index: OnceCell<Arc<Index>>,
registry_api: OnceCell<Arc<RegistryApi>>,
repository_stats_updater: OnceCell<Arc<RepositoryStatsUpdater>>,
runtime: OnceCell<Arc<Runtime>>,
}
impl BinContext {
fn new() -> Self {
Self {
build_queue: OnceCell::new(),
async_build_queue: tokio::sync::OnceCell::new(),
storage: OnceCell::new(),
cdn: tokio::sync::OnceCell::new(),
config: OnceCell::new(),
pool: OnceCell::new(),
service_metrics: OnceCell::new(),
instance_metrics: OnceCell::new(),
index: OnceCell::new(),
registry_api: OnceCell::new(),
repository_stats_updater: OnceCell::new(),
runtime: OnceCell::new(),
}
}
}
macro_rules! lazy {
( $(fn $name:ident($self:ident) -> $type:ty = $init:expr);+ $(;)? ) => {
$(fn $name(&$self) -> Result<Arc<$type>> {
Ok($self
.$name
.get_or_try_init::<_, Error>(|| Ok(Arc::new($init)))?
.clone())
})*
}
}
impl Context for BinContext {
lazy! {
fn build_queue(self) -> BuildQueue = {
let runtime = self.runtime()?;
BuildQueue::new(
runtime.clone(),
runtime.block_on(self.async_build_queue())?
)
};
fn storage(self) -> Storage = {
let runtime = self.runtime()?;
Storage::new(
runtime.block_on(self.async_storage())?,
runtime
)
};
fn config(self) -> Config = Config::from_env()?;
fn service_metrics(self) -> ServiceMetrics = {
ServiceMetrics::new()?
};
fn instance_metrics(self) -> InstanceMetrics = InstanceMetrics::new()?;
fn runtime(self) -> Runtime = {
Builder::new_multi_thread()
.enable_all()
.build()?
};
fn index(self) -> Index = {
let config = self.config()?;
let path = config.registry_index_path.clone();
if let Some(registry_url) = config.registry_url.clone() {
Index::from_url(path, registry_url)
} else {
Index::new(path)
}?
};
fn registry_api(self) -> RegistryApi = {
let config = self.config()?;
RegistryApi::new(config.registry_api_host.clone(), config.crates_io_api_call_retries)?
};
fn repository_stats_updater(self) -> RepositoryStatsUpdater = {
let config = self.config()?;
let pool = self.pool()?;
RepositoryStatsUpdater::new(&config, pool)
};
}
async fn async_pool(&self) -> Result<Pool> {
self.pool()
}
fn pool(&self) -> Result<Pool> {
Ok(self
.pool
.get_or_try_init::<_, Error>(|| {
Ok(Pool::new(
&*self.config()?,
self.runtime()?,
self.instance_metrics()?,
)?)
})?
.clone())
}
async fn async_storage(&self) -> Result<Arc<AsyncStorage>> {
Ok(Arc::new(
AsyncStorage::new(self.pool()?, self.instance_metrics()?, self.config()?).await?,
))
}
async fn async_build_queue(&self) -> Result<Arc<AsyncBuildQueue>> {
Ok(self
.async_build_queue
.get_or_try_init(|| async {
Ok::<_, Error>(Arc::new(AsyncBuildQueue::new(
self.pool()?,
self.instance_metrics()?,
self.config()?,
self.async_storage().await?,
)))
})
.await?
.clone())
}
async fn cdn(&self) -> Result<Arc<CdnBackend>> {
let config = self.config()?;
Ok(self
.cdn
.get_or_init(|| async { Arc::new(CdnBackend::new(&config).await) })
.await
.clone())
}
}