cratery 1.11.1

Cratery -- a private cargo registry
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
/*******************************************************************************
 * Copyright (c) 2024 Cénotélie Opérations SAS (cenotelie.fr)
 ******************************************************************************/

//! Main application

use std::future::Future;
use std::ops::Deref;
use std::sync::Arc;

use log::{error, info};
use tokio::sync::mpsc::{channel, Receiver, Sender};

use crate::model::auth::{Authentication, RegistryUserToken, RegistryUserTokenWithSecret};
use crate::model::cargo::{
    CrateUploadData, CrateUploadResult, OwnersQueryResult, RegistryUser, SearchResults, YesNoMsgResult, YesNoResult,
};
use crate::model::config::Configuration;
use crate::model::deps::DepsAnalysis;
use crate::model::docs::{DocGenEvent, DocGenJob, DocGenJobSpec, DocGenTrigger};
use crate::model::packages::{CrateInfo, CrateInfoTarget};
use crate::model::stats::{DownloadStats, GlobalStats};
use crate::model::worker::{WorkerEvent, WorkerPublicData, WorkersManager};
use crate::model::{AppEvent, CrateVersion, RegistryInformation};
use crate::services::database::{db_transaction_read, db_transaction_write, Database};
use crate::services::deps::DepsChecker;
use crate::services::docs::DocsGenerator;
use crate::services::emails::EmailSender;
use crate::services::index::Index;
use crate::services::rustsec::RustSecChecker;
use crate::services::storage::Storage;
use crate::services::ServiceProvider;
use crate::utils::apierror::{error_forbidden, error_invalid_request, error_unauthorized, specialize, ApiError};
use crate::utils::axum::auth::{AuthData, Token};
use crate::utils::db::RwSqlitePool;

/// The state of this application for axum
pub struct Application {
    /// The configuration
    pub configuration: Arc<Configuration>,
    /// The database pool
    service_db_pool: RwSqlitePool,
    /// The storage layer
    service_storage: Arc<dyn Storage + Send + Sync>,
    /// Service to index the metadata of crates
    service_index: Arc<dyn Index + Send + Sync>,
    /// The `RustSec` checker service
    #[allow(dead_code)]
    service_rustsec: Arc<dyn RustSecChecker + Send + Sync>,
    /// Service to check the dependencies of a crate
    service_deps_checker: Arc<dyn DepsChecker + Send + Sync>,
    /// The service to send emails
    #[allow(dead_code)]
    service_email_sender: Arc<dyn EmailSender + Send + Sync>,
    /// The service to generator documentation
    service_docs_generator: Arc<dyn DocsGenerator + Send + Sync>,
    /// Sender to use to notify about events that will be asynchronously handled
    app_events_sender: Sender<AppEvent>,
    /// The connected worker nodes
    pub worker_nodes: WorkersManager,
}

/// The empty database
const DB_EMPTY: &[u8] = include_bytes!("empty.db");

impl Application {
    /// Creates a new application
    pub async fn launch<P: ServiceProvider>(configuration: Configuration) -> Result<Arc<Self>, ApiError> {
        // load configuration
        let configuration = Arc::new(configuration);

        // connection pool to the database
        let db_filename = configuration.get_database_filename();
        if tokio::fs::metadata(&db_filename).await.is_err() {
            // write the file
            info!("db file is inaccessible => attempt to create an empty one");
            tokio::fs::write(&db_filename, DB_EMPTY).await?;
        }
        let service_db_pool = RwSqlitePool::new(&configuration.get_database_url())?;
        // migrate the database, if appropriate
        db_transaction_write(&service_db_pool, "migrate_to_last", |database| async move {
            crate::migrations::migrate_to_last(database.transaction).await
        })
        .await?;

        let worker_nodes = WorkersManager::default();

        let db_is_empty =
            db_transaction_read(&service_db_pool, |database| async move { database.get_is_empty().await }).await?;
        let service_storage = P::get_storage(&configuration.deref().clone());
        let service_index = P::get_index(&configuration, db_is_empty).await?;
        let service_rustsec = P::get_rustsec(&configuration);
        let service_deps_checker = P::get_deps_checker(configuration.clone(), service_index.clone(), service_rustsec.clone());
        let service_email_sender = P::get_email_sender(configuration.clone());
        let service_docs_generator = P::get_docs_generator(
            configuration.clone(),
            service_db_pool.clone(),
            service_storage.clone(),
            worker_nodes.clone(),
        );

        // check undocumented packages
        let default_target = &configuration.self_toolchain_host;
        let job_specs = db_transaction_write(
            &service_db_pool,
            "Application::launch::get_undocumented_crates",
            |database| async move {
                let jobs = database.get_undocumented_crates(default_target).await?;
                for job in &jobs {
                    // resolve the docs
                    database
                        .set_crate_documentation(&job.package, &job.version, &job.target, false, false)
                        .await?;
                }
                Ok::<_, ApiError>(jobs)
            },
        )
        .await?;
        for spec in &job_specs {
            service_docs_generator.queue(spec, &DocGenTrigger::MissingOnLaunch).await?;
        }

        // deps worker
        crate::services::deps::create_deps_worker(
            configuration.clone(),
            service_deps_checker.clone(),
            service_email_sender.clone(),
            service_db_pool.clone(),
        );

        let (app_events_sender, app_events_receiver) = channel(64);

        let this = Arc::new(Self {
            configuration,
            service_db_pool,
            service_storage,
            service_index,
            service_rustsec,
            service_deps_checker,
            service_email_sender,
            service_docs_generator,
            app_events_sender,
            worker_nodes,
        });

        let _handle = {
            let app = this.clone();
            tokio::spawn(async move {
                app.events_handler(app_events_receiver).await;
            })
        };

        Ok(this)
    }

    /// Gets the storage service
    #[must_use]
    pub fn get_service_storage(&self) -> Arc<dyn Storage + Send + Sync> {
        self.service_storage.clone()
    }

    /// Gets the index service
    #[must_use]
    pub fn get_service_index(&self) -> &(dyn Index + Send + Sync) {
        self.service_index.as_ref()
    }

    /// The worker to handle the update of token usage
    async fn events_handler(&self, mut receiver: Receiver<AppEvent>) {
        const BUFFER_SIZE: usize = 16;
        let mut events = Vec::with_capacity(BUFFER_SIZE);
        loop {
            let count = receiver.recv_many(&mut events, BUFFER_SIZE).await;
            if count == 0 {
                break;
            }
            if let Err(e) = self.events_handler_handle(&events).await {
                error!("{e}");
                if let Some(backtrace) = e.backtrace {
                    error!("{backtrace}");
                }
            }
            events.clear();
        }
    }

    /// Handles a set of events
    async fn events_handler_handle(&self, events: &[AppEvent]) -> Result<(), ApiError> {
        self.db_transaction_write("events_handler_handle", |app| async move {
            for event in events {
                match event {
                    AppEvent::TokenUse(usage) => {
                        app.database.update_token_last_usage(usage).await?;
                    }
                    AppEvent::CrateDownload(CrateVersion { package: name, version }) => {
                        app.database.increment_crate_version_dl_count(name, version).await?;
                    }
                }
            }
            Ok::<_, ApiError>(())
        })
        .await
    }

    /// Executes a piece of work in the context of a transaction
    /// The transaction is committed if the operation succeed,
    /// or rolled back if it fails
    ///
    /// # Errors
    ///
    /// Returns an instance of the `E` type argument
    pub(crate) async fn db_transaction_read<'s, F, FUT, T, E>(&'s self, workload: F) -> Result<T, E>
    where
        F: FnOnce(ApplicationWithTransaction<'s>) -> FUT,
        FUT: Future<Output = Result<T, E>>,
        E: From<sqlx::Error>,
    {
        db_transaction_read(&self.service_db_pool, |database| async move {
            workload(ApplicationWithTransaction {
                database,
                application: self,
            })
            .await
        })
        .await
    }

    /// Executes a piece of work in the context of a transaction
    /// The transaction is committed if the operation succeed,
    /// or rolled back if it fails
    ///
    /// # Errors
    ///
    /// Returns an instance of the `E` type argument
    pub(crate) async fn db_transaction_write<'s, F, FUT, T, E>(&'s self, operation: &'static str, workload: F) -> Result<T, E>
    where
        F: FnOnce(ApplicationWithTransaction<'s>) -> FUT,
        FUT: Future<Output = Result<T, E>>,
        E: From<sqlx::Error>,
    {
        db_transaction_write(&self.service_db_pool, operation, |database| async move {
            workload(ApplicationWithTransaction {
                database,
                application: self,
            })
            .await
        })
        .await
    }

    /// Attempts the authentication of a user
    pub async fn authenticate(&self, auth_data: &AuthData) -> Result<Authentication, ApiError> {
        self.db_transaction_read(|app| async move { app.authenticate(auth_data).await })
            .await
    }

    /// Gets the registry configuration
    pub async fn get_registry_information(&self, auth_data: &AuthData) -> Result<RegistryInformation, ApiError> {
        let _authentication = self.authenticate(auth_data).await?;
        Ok(RegistryInformation {
            registry_name: self.configuration.self_local_name.clone(),
            toolchain_host: self.configuration.self_toolchain_host.clone(),
            toolchain_version_stable: self.configuration.self_toolchain_version_stable.clone(),
            toolchain_version_nightly: self.configuration.self_toolchain_version_nightly.clone(),
            toolchain_targets: self.configuration.self_known_targets.clone(),
        })
    }

    /// Gets the connected worker nodes
    pub async fn get_workers(&self, auth_data: &AuthData) -> Result<Vec<WorkerPublicData>, ApiError> {
        let authentication = self.authenticate(auth_data).await?;
        if !authentication.can_admin {
            return Err(error_forbidden());
        }
        Ok(self.worker_nodes.get_workers())
    }

    /// Adds a listener to workers updates
    pub async fn get_workers_updates(&self, auth_data: &AuthData) -> Result<Receiver<WorkerEvent>, ApiError> {
        let authentication = self.authenticate(auth_data).await?;
        if !authentication.can_admin {
            return Err(error_forbidden());
        }
        let (sender, receiver) = channel(16);
        self.worker_nodes.add_listener(sender).await;
        Ok(receiver)
    }

    /// Gets the data about the current user
    pub async fn get_current_user(&self, auth_data: &AuthData) -> Result<RegistryUser, ApiError> {
        self.db_transaction_read(|app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.database.get_user_profile(authentication.uid()?).await
        })
        .await
    }

    /// Attempts to login using an OAuth code
    pub async fn login_with_oauth_code(&self, code: &str) -> Result<RegistryUser, ApiError> {
        self.db_transaction_write("login_with_oauth_code", |app| async move {
            app.database.login_with_oauth_code(&self.configuration, code).await
        })
        .await
    }

    /// Gets the known users
    pub async fn get_users(&self, auth_data: &AuthData) -> Result<Vec<RegistryUser>, ApiError> {
        self.db_transaction_read(|app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_admin_registry(&authentication).await?;
            app.database.get_users().await
        })
        .await
    }

    /// Updates the information of a user
    pub async fn update_user(&self, auth_data: &AuthData, target: &RegistryUser) -> Result<RegistryUser, ApiError> {
        self.db_transaction_write("update_user", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            let principal_uid = authentication.uid()?;
            let can_admin = if target.id == principal_uid {
                // same user
                authentication.can_admin && app.database.get_is_admin(principal_uid).await?
            } else {
                // different users, requires admin
                app.check_can_admin_registry(&authentication).await?;
                true
            };
            app.database.update_user(principal_uid, target, can_admin).await
        })
        .await
    }

    /// Attempts to deactivate a user
    pub async fn deactivate_user(&self, auth_data: &AuthData, target: &str) -> Result<(), ApiError> {
        self.db_transaction_write("deactivate_user", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            let principal_uid = app.check_can_admin_registry(&authentication).await?;
            app.database.deactivate_user(principal_uid, target).await
        })
        .await
    }

    /// Attempts to re-activate a user
    pub async fn reactivate_user(&self, auth_data: &AuthData, target: &str) -> Result<(), ApiError> {
        self.db_transaction_write("reactivate_user", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_admin_registry(&authentication).await?;
            app.database.reactivate_user(target).await
        })
        .await
    }

    /// Attempts to delete a user
    pub async fn delete_user(&self, auth_data: &AuthData, target: &str) -> Result<(), ApiError> {
        self.db_transaction_write("delete_user", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            let principal_uid = app.check_can_admin_registry(&authentication).await?;
            app.database.delete_user(principal_uid, target).await
        })
        .await
    }

    /// Gets the tokens for a user
    pub async fn get_tokens(&self, auth_data: &AuthData) -> Result<Vec<RegistryUserToken>, ApiError> {
        self.db_transaction_read(|app| async move {
            let authentication = app.authenticate(auth_data).await?;
            authentication.check_can_admin()?;
            app.database.get_tokens(authentication.uid()?).await
        })
        .await
    }

    /// Creates a token for the current user
    pub async fn create_token(
        &self,
        auth_data: &AuthData,
        name: &str,
        can_write: bool,
        can_admin: bool,
    ) -> Result<RegistryUserTokenWithSecret, ApiError> {
        self.db_transaction_write("create_token", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            authentication.check_can_admin()?;
            app.database
                .create_token(authentication.uid()?, name, can_write, can_admin)
                .await
        })
        .await
    }

    /// Revoke a previous token
    pub async fn revoke_token(&self, auth_data: &AuthData, token_id: i64) -> Result<(), ApiError> {
        self.db_transaction_write("revoke_token", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            authentication.check_can_admin()?;
            app.database.revoke_token(authentication.uid()?, token_id).await
        })
        .await
    }

    /// Gets the global tokens for the registry, usually for CI purposes
    pub async fn get_global_tokens(&self, auth_data: &AuthData) -> Result<Vec<RegistryUserToken>, ApiError> {
        self.db_transaction_read(|app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_admin_registry(&authentication).await?;
            app.database.get_global_tokens().await
        })
        .await
    }

    /// Creates a global token for the registry
    pub async fn create_global_token(&self, auth_data: &AuthData, name: &str) -> Result<RegistryUserTokenWithSecret, ApiError> {
        self.db_transaction_write("create_global_token", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_admin_registry(&authentication).await?;
            app.database.create_global_token(name).await
        })
        .await
    }

    /// Revokes a globel token for the registry
    pub async fn revoke_global_token(&self, auth_data: &AuthData, token_id: i64) -> Result<(), ApiError> {
        self.db_transaction_write("revoke_global_token", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_admin_registry(&authentication).await?;
            app.database.revoke_global_token(token_id).await
        })
        .await
    }

    /// Publish a crate
    pub async fn publish_crate_version(&self, auth_data: &AuthData, content: &[u8]) -> Result<CrateUploadResult, ApiError> {
        // deserialize payload
        let package = CrateUploadData::new(content)?;
        let index_data = package.build_index_data();

        let (user, result, targets, capabilities) = {
            let package = &package;
            self.db_transaction_write("publish_crate_version", |app| async move {
                let authentication = app.authenticate(auth_data).await?;
                authentication.check_can_write()?;
                let user = app.database.get_user_profile(authentication.uid()?).await?;
                // publish
                let result = app.database.publish_crate_version(user.id, package).await?;
                let mut targets = app.database.get_crate_targets(&package.metadata.name).await?;
                if targets.is_empty() {
                    targets.push(CrateInfoTarget {
                        target: self.configuration.self_toolchain_host.clone(),
                        docs_use_native: true,
                    });
                }
                for info in &targets {
                    app.database
                        .set_crate_documentation(&package.metadata.name, &package.metadata.vers, &info.target, false, false)
                        .await?;
                }
                let capabilities = app.database.get_crate_required_capabilities(&package.metadata.name).await?;
                Ok::<_, ApiError>((user, result, targets, capabilities))
            })
            .await
        }?;

        self.service_storage.store_crate(&package.metadata, package.content).await?;
        self.service_index.publish_crate_version(&index_data).await?;
        for info in targets {
            self.service_docs_generator
                .queue(
                    &DocGenJobSpec {
                        package: index_data.name.clone(),
                        version: index_data.vers.clone(),
                        target: info.target,
                        use_native: info.docs_use_native,
                        capabilities: capabilities.clone(),
                    },
                    &DocGenTrigger::Upload { by: user.clone() },
                )
                .await?;
        }
        Ok(result)
    }

    /// Gets all the data about a crate
    pub async fn get_crate_info(&self, auth_data: &AuthData, package: &str) -> Result<CrateInfo, ApiError> {
        let info = self
            .db_transaction_read(|app| async move {
                let _authentication = app.authenticate(auth_data).await?;
                app.database
                    .get_crate_info(package, self.service_index.get_crate_data(package).await?)
                    .await
            })
            .await?;
        let metadata = self
            .service_storage
            .download_crate_metadata(package, &info.versions.last().unwrap().index.vers)
            .await?;
        Ok(CrateInfo { metadata, ..info })
    }

    /// Downloads the last README for a crate
    pub async fn get_crate_last_readme(&self, auth_data: &AuthData, package: &str) -> Result<Vec<u8>, ApiError> {
        let version = self
            .db_transaction_read(|app| async move {
                let _authentication = app.authenticate(auth_data).await?;
                let version = app.database.get_crate_last_version(package).await?;
                Ok::<_, ApiError>(version)
            })
            .await?;
        let readme = self.service_storage.download_crate_readme(package, &version).await?;
        Ok(readme)
    }

    /// Downloads the README for a crate
    pub async fn get_crate_readme(&self, auth_data: &AuthData, package: &str, version: &str) -> Result<Vec<u8>, ApiError> {
        let _authentication = self.authenticate(auth_data).await?;
        let readme = self.service_storage.download_crate_readme(package, version).await?;
        Ok(readme)
    }

    /// Downloads the content for a crate
    pub async fn get_crate_content(&self, auth_data: &AuthData, package: &str, version: &str) -> Result<Vec<u8>, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database.check_crate_exists(package, version).await?;
            Ok::<_, ApiError>(())
        })
        .await?;
        let content = self.service_storage.download_crate(package, version).await?;
        self.app_events_sender
            .send(AppEvent::CrateDownload(CrateVersion {
                package: package.to_string(),
                version: version.to_string(),
            }))
            .await?;
        Ok(content)
    }

    /// Yank a crate version
    pub async fn yank_crate_version(
        &self,
        auth_data: &AuthData,
        package: &str,
        version: &str,
    ) -> Result<YesNoResult, ApiError> {
        self.db_transaction_write("yank_crate_version", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_manage_crate(&authentication, package).await?;
            app.database.yank_crate_version(package, version).await
        })
        .await
    }

    /// Unyank a crate version
    pub async fn unyank_crate_version(
        &self,
        auth_data: &AuthData,
        package: &str,
        version: &str,
    ) -> Result<YesNoResult, ApiError> {
        self.db_transaction_write("unyank_crate_version", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_manage_crate(&authentication, package).await?;
            app.database.unyank_crate_version(package, version).await
        })
        .await
    }

    /// Gets the packages that need documentation generation
    pub async fn get_undocumented_crates(&self, auth_data: &AuthData) -> Result<Vec<DocGenJobSpec>, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database
                .get_undocumented_crates(&self.configuration.self_toolchain_host)
                .await
        })
        .await
    }

    /// Gets the documentation jobs
    pub async fn get_doc_gen_jobs(&self, auth_data: &AuthData) -> Result<Vec<DocGenJob>, ApiError> {
        let _authentication = self.authenticate(auth_data).await?;
        self.service_docs_generator.get_jobs().await
    }

    /// Gets the log for a documentation generation job
    pub async fn get_doc_gen_job_log(&self, auth_data: &AuthData, job_id: i64) -> Result<String, ApiError> {
        let _authentication = self.authenticate(auth_data).await?;
        self.service_docs_generator.get_job_log(job_id).await
    }

    /// Adds a listener to job updates
    pub async fn get_doc_gen_job_updates(&self, auth_data: &AuthData) -> Result<Receiver<DocGenEvent>, ApiError> {
        let _authentication = self.authenticate(auth_data).await?;
        let (sender, receiver) = channel(16);
        self.service_docs_generator.add_listener(sender).await?;
        Ok(receiver)
    }

    /// Force the re-generation for the documentation of a package
    pub async fn regen_crate_version_doc(
        &self,
        auth_data: &AuthData,
        package: &str,
        version: &str,
    ) -> Result<Vec<DocGenJob>, ApiError> {
        let (user, targets, capabilities) = self
            .db_transaction_write("regen_crate_version_doc", |app| async move {
                let authentication = app.authenticate(auth_data).await?;
                let principal_uid = app.check_can_manage_crate(&authentication, package).await?;
                let user = app.database.get_user_profile(principal_uid).await?;
                let targets = app
                    .database
                    .regen_crate_version_doc(package, version, &self.configuration.self_toolchain_host)
                    .await?;
                let capabilities = app.database.get_crate_required_capabilities(package).await?;
                Ok::<_, ApiError>((user, targets, capabilities))
            })
            .await?;

        let mut jobs = Vec::new();
        for info in targets {
            jobs.push(
                self.service_docs_generator
                    .queue(
                        &DocGenJobSpec {
                            package: package.to_string(),
                            version: version.to_string(),
                            target: info.target,
                            use_native: info.docs_use_native,
                            capabilities: capabilities.clone(),
                        },
                        &DocGenTrigger::Manual { by: user.clone() },
                    )
                    .await?,
            );
        }
        Ok(jobs)
    }

    /// Gets all the packages that are outdated while also being the latest version
    pub async fn get_crates_outdated_heads(&self, auth_data: &AuthData) -> Result<Vec<CrateVersion>, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database.get_crates_outdated_heads().await
        })
        .await
    }

    /// Gets the download statistics for a crate
    pub async fn get_crate_dl_stats(&self, auth_data: &AuthData, package: &str) -> Result<DownloadStats, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database.get_crate_dl_stats(package).await
        })
        .await
    }

    /// Gets the list of owners for a package
    pub async fn get_crate_owners(&self, auth_data: &AuthData, package: &str) -> Result<OwnersQueryResult, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database.get_crate_owners(package).await
        })
        .await
    }

    /// Add owners to a package
    pub async fn add_crate_owners(
        &self,
        auth_data: &AuthData,
        package: &str,
        new_users: &[String],
    ) -> Result<YesNoMsgResult, ApiError> {
        self.db_transaction_write("add_crate_owners", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_manage_crate(&authentication, package).await?;
            app.database.add_crate_owners(package, new_users).await
        })
        .await
    }

    /// Remove owners from a package
    pub async fn remove_crate_owners(
        &self,
        auth_data: &AuthData,
        package: &str,
        old_users: &[String],
    ) -> Result<YesNoResult, ApiError> {
        self.db_transaction_write("remove_crate_owners", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_manage_crate(&authentication, package).await?;
            app.database.remove_crate_owners(package, old_users).await
        })
        .await
    }

    /// Gets the targets for a crate
    pub async fn get_crate_targets(&self, auth_data: &AuthData, package: &str) -> Result<Vec<CrateInfoTarget>, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database.get_crate_targets(package).await
        })
        .await
    }

    /// Sets the targets for a crate
    pub async fn set_crate_targets(
        &self,
        auth_data: &AuthData,
        package: &str,
        targets: &[CrateInfoTarget],
    ) -> Result<(), ApiError> {
        let (user, jobs) = self
            .db_transaction_write("set_crate_targets", |app| async move {
                let authentication = app.authenticate(auth_data).await?;
                let principal_uid = app.check_can_manage_crate(&authentication, package).await?;
                let user = app.database.get_user_profile(principal_uid).await?;
                for info in targets {
                    if !self.configuration.self_known_targets.contains(&info.target) {
                        return Err(specialize(
                            error_invalid_request(),
                            format!("Unknown target: {}", info.target),
                        ));
                    }
                }
                let jobs = app.database.set_crate_targets(package, targets).await?;
                for job in &jobs {
                    app.database
                        .set_crate_documentation(&job.package, &job.version, &job.target, false, false)
                        .await?;
                }
                Ok::<_, ApiError>((user, jobs))
            })
            .await?;
        for job in jobs {
            self.service_docs_generator
                .queue(&job, &DocGenTrigger::NewTarget { by: user.clone() })
                .await?;
        }
        Ok(())
    }

    /// Gets the required capabilities for a crate
    pub async fn get_crate_required_capabilities(&self, auth_data: &AuthData, package: &str) -> Result<Vec<String>, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database.get_crate_required_capabilities(package).await
        })
        .await
    }

    /// Sets the required capabilities for a crate
    pub async fn set_crate_required_capabilities(
        &self,
        auth_data: &AuthData,
        package: &str,
        capabilities: &[String],
    ) -> Result<(), ApiError> {
        self.db_transaction_write("set_crate_required_capabilities", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            let _ = app.check_can_manage_crate(&authentication, package).await?;
            app.database.set_crate_required_capabilities(package, capabilities).await?;
            Ok::<_, ApiError>(())
        })
        .await?;
        Ok(())
    }

    /// Sets the deprecation status on a crate
    pub async fn set_crate_deprecation(&self, auth_data: &AuthData, package: &str, deprecated: bool) -> Result<(), ApiError> {
        self.db_transaction_write("set_crate_deprecation", |app| async move {
            let authentication = app.authenticate(auth_data).await?;
            app.check_can_manage_crate(&authentication, package).await?;
            app.database.set_crate_deprecation(package, deprecated).await
        })
        .await
    }

    /// Gets the global statistics for the registry
    pub async fn get_crates_stats(&self, auth_data: &AuthData) -> Result<GlobalStats, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database.get_crates_stats().await
        })
        .await
    }

    /// Search for crates
    pub async fn search_crates(
        &self,
        auth_data: &AuthData,
        query: &str,
        per_page: Option<usize>,
        deprecated: Option<bool>,
    ) -> Result<SearchResults, ApiError> {
        self.db_transaction_read(|app| async move {
            let _authentication = app.authenticate(auth_data).await?;
            app.database.search_crates(query, per_page, deprecated).await
        })
        .await
    }

    /// Checks the dependencies of a local crate
    pub async fn check_crate_version_deps(
        &self,
        auth_data: &AuthData,
        package: &str,
        version: &str,
    ) -> Result<DepsAnalysis, ApiError> {
        let targets = self
            .db_transaction_read(|app| async move {
                let _authentication = app.authenticate(auth_data).await?;
                app.database.check_crate_exists(package, version).await?;
                app.database.get_crate_targets(package).await
            })
            .await?;
        let targets = targets.into_iter().map(|info| info.target).collect::<Vec<_>>();
        self.service_deps_checker.check_crate(package, version, &targets).await
    }
}

/// The application, running with a transaction
pub(crate) struct ApplicationWithTransaction<'a> {
    /// The application with its services
    pub(crate) application: &'a Application,
    /// The database access encapsulating a transaction
    pub(crate) database: Database,
}

impl<'a> ApplicationWithTransaction<'a> {
    /// Attempts the authentication of a user
    async fn authenticate(&self, auth_data: &AuthData) -> Result<Authentication, ApiError> {
        if let Some(token) = &auth_data.token {
            self.authenticate_token(token).await
        } else {
            let authentication = auth_data.try_authenticate_cookie()?.ok_or_else(error_unauthorized)?;
            self.database.check_is_user(authentication.email()?).await?;
            Ok(authentication)
        }
    }

    /// Tries to authenticate using a token
    async fn authenticate_token(&self, token: &Token) -> Result<Authentication, ApiError> {
        if token.id == self.application.configuration.self_service_login
            && token.secret == self.application.configuration.self_service_token
        {
            // self authentication to read
            return Ok(Authentication::new_self());
        }
        let user = self
            .database
            .check_token(&token.id, &token.secret, &|usage| async move {
                self.application
                    .app_events_sender
                    .send(AppEvent::TokenUse(usage))
                    .await
                    .unwrap();
            })
            .await?;
        Ok(user)
    }

    /// Checks that the given authentication can perform admin tasks
    async fn check_can_admin_registry(&self, authentication: &Authentication) -> Result<i64, ApiError> {
        authentication.check_can_admin()?;
        let principal_uid = authentication.uid()?;
        self.database.check_is_admin(principal_uid).await?;
        Ok(principal_uid)
    }

    /// Checks that the given authentication can manage a given crate
    async fn check_can_manage_crate(&self, authentication: &Authentication, package: &str) -> Result<i64, ApiError> {
        authentication.check_can_write()?;
        let principal_uid = authentication.uid()?;
        self.database.check_is_crate_manager(principal_uid, package).await?;
        Ok(principal_uid)
    }
}