laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
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
//! Service registration: the bindings that providers and the application declare, and the
//! discovery of a crate's services.

use crate::schedule::ScheduleInternals as _;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::sync::Arc;

use futures_util::FutureExt;

use super::binding::Lifetime;
use super::{Bindings, Container};
use crate::config::Config;
use crate::console::Commands;
use crate::error::Result;
use crate::errors::Errors;
use crate::event::Dispatcher;
use crate::foundation::LogLayers;
use crate::head::HeadConfig;
use crate::http::MiddlewareConfig;
use crate::routing::Routing;
use crate::schedule::Schedule;
use crate::session::Drivers;
use crate::task::Ticks;
use crate::type_map::TypeMap;
use crate::view::{ViewConfig, ViewConfigInternals as _};

/// Registers services and subsystem definitions, such as routes, commands, and drivers.
///
/// A provider receives a `Registrar` in
/// [`ServiceProvider::register`](crate::foundation::ServiceProvider::register), and so does
/// a callback given to [`with_services`](crate::foundation::ApplicationBuilder::with_services).
/// Registering a type again replaces its earlier registration. The configuration is final by
/// the time the registrar runs, so you can decide which services to register, or which
/// implementation to build:
///
/// ```
/// use std::sync::Arc;
/// use laravel::container::Registrar;
/// # pub struct Database;
/// # impl Database { async fn connect(url: &str) -> laravel::Result<Self> { Ok(Database) } }
/// # pub struct Orders;
/// # impl Orders { fn new(database: Arc<Database>) -> Self { Orders } }
/// # pub struct Telescope;
/// # pub struct DatabaseConfig { url: String }
/// # pub struct TelescopeConfig { enabled: bool }
///
/// fn register(app: &mut Registrar) {
///     if app.config().section::<TelescopeConfig>().enabled {
///         app.instance(Telescope);
///     }
///
///     app.singleton(|app| async move {
///         Database::connect(&app.config().section::<DatabaseConfig>().url).await
///     });
///
///     app.singleton(|app| async move {
///         let database = app.resolve::<Database>().await?;
///
///         Ok(Orders::new(database))
///     });
/// }
/// ```
pub struct Registrar {
    pub(crate) services: Bindings,
    pub(crate) events: Dispatcher,
    pub(crate) sessions: Drivers,
    pub(crate) features: crate::feature::Drivers,
    pub(crate) cache: crate::cache::Drivers,
    pub(crate) mail: crate::mail::Drivers,
    pub(crate) queue: crate::queue::Drivers,
    pub(crate) workflow: crate::workflow::Drivers,
    pub(crate) social: crate::auth::social::Drivers,
    #[cfg(feature = "search")]
    pub(crate) search: crate::search::Drivers,
    pub(crate) routing: Routing,
    pub(crate) middleware: MiddlewareConfig,
    pub(crate) views: ViewConfig,
    pub(crate) logging: LogLayers,
    pub(crate) errors: Errors,
    pub(crate) head: HeadConfig,
    pub(crate) auth: crate::auth::AuthConfig,
    pub(crate) commands: Commands,
    pub(crate) schedule: Schedule,
    pub(crate) ticks: Ticks,
    #[cfg(feature = "database")]
    pub(crate) migrations: crate::db::Migrations,
    #[cfg(feature = "database")]
    pub(crate) seeders: crate::db::seeders::Seeders,
    /// Runtime application parts registered by framework providers, inserted into `App::parts` during assembly.
    pub(crate) parts: TypeMap,
    /// The crates whose services have been discovered.
    discovered_crates: HashSet<String>,
}

impl Registrar {
    pub(crate) fn new(config: Arc<Config>) -> Self {
        Self {
            views: ViewConfig::new(&config),
            services: Bindings::new(config),
            events: Dispatcher::default(),
            sessions: Drivers::default(),
            features: crate::feature::Drivers::default(),
            cache: crate::cache::Drivers::default(),
            mail: crate::mail::Drivers::default(),
            queue: crate::queue::Drivers::default(),
            workflow: crate::workflow::Drivers::default(),
            social: crate::auth::social::Drivers::default(),
            #[cfg(feature = "search")]
            search: crate::search::Drivers::default(),
            routing: Routing::default(),
            middleware: MiddlewareConfig::default(),
            logging: LogLayers::default(),
            errors: Errors::default(),
            head: HeadConfig::default(),
            auth: crate::auth::AuthConfig::default(),
            commands: Commands::default(),
            schedule: Schedule::default(),
            ticks: Ticks::default(),
            #[cfg(feature = "database")]
            migrations: crate::db::Migrations::default(),
            #[cfg(feature = "database")]
            seeders: crate::db::seeders::Seeders::default(),
            parts: TypeMap::default(),
            discovered_crates: HashSet::new(),
        }
    }

    /// Register a runtime part to be stored in `App::parts` when the application is assembled.
    pub(crate) fn part<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
        self.parts.insert(value);
        self
    }

    pub(crate) const fn provider(&mut self, provider: Option<&'static str>) {
        self.services.provider = provider;
    }

    pub(crate) fn is_bound<T: ?Sized + 'static>(&self) -> bool {
        self.services.is_bound::<T>()
    }

    /// Returns the application's final configuration, after every config file has run.
    #[must_use]
    pub fn config(&self) -> &Config {
        self.services.config()
    }

    /// Returns the event dispatcher, to register listeners. These listeners register before the
    /// application's discovered listeners and its `with_events` callbacks.
    pub const fn events(&mut self) -> &mut Dispatcher {
        &mut self.events
    }

    /// Returns the session drivers, to register a named session factory. Only the configured
    /// driver's factory runs, when a request first uses the session.
    pub const fn sessions(&mut self) -> &mut Drivers {
        &mut self.sessions
    }

    /// Returns the feature store drivers, to register a named driver. Only the configured driver's
    /// factory runs, when the application boots.
    pub const fn features(&mut self) -> &mut crate::feature::Drivers {
        &mut self.features
    }

    /// Returns the cache drivers, to register a named driver. The driver's factory creates each
    /// store that uses the driver when the store is first used.
    ///
    /// ```
    /// use laravel::{cache::MemoryStore, container::Registrar, foundation::ServiceProvider};
    ///
    /// struct Package;
    ///
    /// impl ServiceProvider for Package {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.cache().extend("package", |_app, _definition| async { Ok(MemoryStore::default()) });
    ///     }
    /// }
    /// ```
    pub const fn cache(&mut self) -> &mut crate::cache::Drivers {
        &mut self.cache
    }

    /// Returns the search engine drivers, to register a named engine. `SEARCH_ENGINE` set to the
    /// driver's name chooses it, and its factory creates the engine on the first search or sync.
    ///
    /// ```
    /// use laravel::{container::Registrar, foundation::ServiceProvider};
    /// # use laravel::search::{Document, Engine, Hits, Index, Search};
    /// # struct Algolia;
    /// # impl Engine for Algolia {
    /// #   async fn upsert(&self, _: &Index, _: &[Document]) -> laravel::Result<()> { Ok(()) }
    /// #   async fn delete(&self, _: &Index, _: &[serde_json::Value]) -> laravel::Result<()> { Ok(()) }
    /// #   async fn search(&self, _: &Index, _: &Search) -> laravel::Result<Hits> { Ok(Hits::new(Vec::new(), 0)) }
    /// #   async fn flush(&self, _: &Index) -> laravel::Result<()> { Ok(()) }
    /// #   async fn sync_index(&self, _: &Index) -> laravel::Result<()> { Ok(()) }
    /// #   async fn delete_index(&self, _: &str) -> laravel::Result<bool> { Ok(false) }
    /// # }
    ///
    /// struct Package;
    ///
    /// impl ServiceProvider for Package {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.search().extend("algolia", |_app, _definition| async { Ok(Algolia) });
    ///     }
    /// }
    /// ```
    #[cfg(feature = "search")]
    pub const fn search(&mut self) -> &mut crate::search::Drivers {
        &mut self.search
    }

    /// Returns the workflow store drivers, to register a named store that keeps workflow runs. The
    /// driver's factory creates the store when a run first needs it.
    ///
    /// ```
    /// use laravel::container::Registrar;
    /// use laravel::foundation::ServiceProvider;
    /// # use std::time::Duration;
    /// # use laravel::time::Timestamp;
    /// # use laravel::workflow::RunId;
    /// # use laravel::workflow::store::{Claim, Created, Delivery, Entry, Filter, Lease, NewRun, Outcome, RunRecord, Store, Waited};
    /// # #[derive(Default)]
    /// # struct DynamoStore;
    /// # impl Store for DynamoStore {
    /// #     async fn create(&self, _: NewRun) -> laravel::Result<Created> { Ok(Created::Saved) }
    /// #     async fn claim(&self, _: RunId, _: Duration) -> laravel::Result<Claim> { Ok(Claim::Ended) }
    /// #     async fn record(&self, _: RunId, _: &Lease, _: Entry) -> laravel::Result<bool> { Ok(true) }
    /// #     async fn wait(&self, _: RunId, _: &Lease, _: &str, _: u32) -> laravel::Result<Waited> { Ok(Waited::Waiting) }
    /// #     async fn stop_waiting(&self, _: RunId, _: &Lease, _: &str) -> laravel::Result<bool> { Ok(true) }
    /// #     async fn resume(&self, _: &str, _: String) -> laravel::Result<Delivery> { Ok(Delivery::NotFound) }
    /// #     async fn waiting(&self, _: &str) -> laravel::Result<Option<RunId>> { Ok(None) }
    /// #     async fn set_attributes(&self, _: RunId, _: &Lease, _: std::collections::BTreeMap<String, String>) -> laravel::Result<bool> { Ok(true) }
    /// #     async fn renew(&self, _: RunId, _: &Lease, _: Duration) -> laravel::Result<bool> { Ok(true) }
    /// #     async fn release(&self, _: RunId, _: &Lease, _: Outcome, _: Timestamp) -> laravel::Result<bool> { Ok(true) }
    /// #     async fn find(&self, _: RunId) -> laravel::Result<Option<RunRecord>> { Ok(None) }
    /// #     async fn entries(&self, _: RunId) -> laravel::Result<Vec<Entry>> { Ok(Vec::new()) }
    /// #     async fn list(&self, _: Filter) -> laravel::Result<Vec<RunRecord>> { Ok(Vec::new()) }
    /// #     async fn cancel(&self, _: RunId, _: Option<String>, _: Timestamp) -> laravel::Result<bool> { Ok(false) }
    /// #     async fn retry(&self, _: RunId, _: Timestamp) -> laravel::Result<bool> { Ok(false) }
    /// #     async fn overdue(&self, _: Timestamp) -> laravel::Result<Vec<RunRecord>> { Ok(Vec::new()) }
    /// #     async fn prune(&self, _: Timestamp) -> laravel::Result<u64> { Ok(0) }
    /// # }
    ///
    /// struct DynamoWorkflows;
    ///
    /// impl ServiceProvider for DynamoWorkflows {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.workflow().extend("dynamodb", |_app, _definition| async { Ok(DynamoStore::default()) });
    ///     }
    /// }
    /// ```
    pub const fn workflow(&mut self) -> &mut crate::workflow::Drivers {
        &mut self.workflow
    }

    /// Returns the mail drivers, to register a named transport. The driver's factory creates the
    /// transport of each mailer that uses the driver on the mailer's first send.
    ///
    /// ```
    /// use laravel::container::Registrar;
    /// use laravel::foundation::ServiceProvider;
    /// use laravel::mail::{Email, SentMessage, Transport};
    ///
    /// struct Postmark;
    ///
    /// impl Transport for Postmark {
    ///     async fn send(&self, _email: &Email) -> laravel::Result<SentMessage> {
    ///         Ok(SentMessage::default())
    ///     }
    /// }
    ///
    /// struct PostmarkProvider;
    ///
    /// impl ServiceProvider for PostmarkProvider {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.mail().extend("postmark", |_app, _definition| async { Ok(Postmark) });
    ///     }
    /// }
    /// ```
    pub const fn mail(&mut self) -> &mut crate::mail::Drivers {
        &mut self.mail
    }

    /// Returns the social login providers, to register a provider under a name, such as `gitlab`.
    /// Each provider's factory runs once, while the application starts. See
    /// [`Driver`](crate::auth::social::Driver) for writing a provider.
    ///
    /// ```
    /// use laravel::auth::social::{self, Driver, Profile, Tokens};
    /// use laravel::{container::Registrar, foundation::ServiceProvider};
    ///
    /// struct GitLab;
    ///
    /// impl Driver for GitLab {
    ///     fn authorize_url(&self) -> String { "https://gitlab.com/oauth/authorize".into() }
    ///     fn token_url(&self) -> String { "https://gitlab.com/oauth/token".into() }
    ///     fn scopes(&self) -> &[&str] { &["openid", "profile", "email"] }
    ///
    ///     async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, social::Error> {
    ///         tokens.user_info("https://gitlab.com/oauth/userinfo").await
    ///     }
    /// }
    ///
    /// struct GitLabProvider;
    ///
    /// impl ServiceProvider for GitLabProvider {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.social().extend("gitlab", |_config| GitLab);
    ///     }
    /// }
    /// ```
    pub const fn social(&mut self) -> &mut crate::auth::social::Drivers {
        &mut self.social
    }

    /// Returns the queue drivers, to register a named driver. The driver's factory creates the
    /// driver of each connection that uses it, when a job is first pushed to the connection or a
    /// worker first works it. See [`Drivers`](crate::queue::Drivers) for writing a driver.
    pub const fn queue(&mut self) -> &mut crate::queue::Drivers {
        &mut self.queue
    }

    /// Returns the routing definition, to register routes and package assets. These register
    /// before the application's routing callbacks.
    pub const fn routing(&mut self) -> &mut Routing {
        &mut self.routing
    }

    /// Returns the middleware configuration. Changes made here apply before the application's
    /// middleware callbacks.
    pub const fn middleware(&mut self) -> &mut MiddlewareConfig {
        &mut self.middleware
    }

    /// Returns the view configuration, to register view engines, namespaces, and shared data.
    /// These register before the application's view callbacks.
    pub const fn views(&mut self) -> &mut ViewConfig {
        &mut self.views
    }

    /// Returns the log layers, to register `tracing` layers. These register before the
    /// application's logging callbacks.
    pub const fn logging(&mut self) -> &mut LogLayers {
        &mut self.logging
    }

    /// Returns the error configuration, to register how errors are reported and rendered.
    /// These register before the application's error callbacks.
    pub const fn errors(&mut self) -> &mut Errors {
        &mut self.errors
    }

    /// Returns the head configuration, to set head defaults and error page metadata. The
    /// application's head callbacks run later, so their settings win.
    pub const fn head(&mut self) -> &mut HeadConfig {
        &mut self.head
    }

    /// Returns the console commands, to register commands. These register before the
    /// application's command callbacks.
    ///
    /// ```
    /// use laravel::{console::clap, container::Registrar, foundation::ServiceProvider};
    ///
    /// #[derive(clap::Parser)]
    /// #[command(name = "package:run")]
    /// struct Run;
    ///
    /// #[laravel::console::command]
    /// impl Run {
    ///     async fn handle(self) {}
    /// }
    ///
    /// struct Package;
    ///
    /// impl ServiceProvider for Package {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.commands().add::<Run>();
    ///     }
    /// }
    /// ```
    pub const fn commands(&mut self) -> &mut Commands {
        &mut self.commands
    }

    /// Returns the schedule, to add scheduled tasks. These come before the application's schedule
    /// callbacks.
    ///
    /// ```
    /// use laravel::{container::Registrar, foundation::ServiceProvider};
    ///
    /// struct Package;
    ///
    /// impl ServiceProvider for Package {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.schedule().call(|| async {}).name("package:prune").daily();
    ///     }
    /// }
    /// ```
    pub const fn schedule(&mut self) -> &mut Schedule {
        &mut self.schedule
    }

    /// Returns the ticks, to add work that repeats in the server and queue workers. These come before
    /// the application's ticks.
    ///
    /// ```
    /// use laravel::time::ToSpan;
    /// use laravel::{container::Registrar, foundation::ServiceProvider};
    ///
    /// struct Package;
    ///
    /// impl ServiceProvider for Package {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.ticks().every(30.seconds(), || async {}).name("package:refresh");
    ///     }
    /// }
    /// ```
    pub const fn ticks(&mut self) -> &mut Ticks {
        &mut self.ticks
    }

    /// Returns the migrations, to register a package's migrations. They run with the application's
    /// migrations, in name order. Build them with [`migrations!`](crate::db::migrations!), which embeds them in
    /// the binary:
    ///
    /// ```ignore
    /// fn register(&self, app: &mut Registrar) {
    ///     app.migrations().add(laravel::db::migrations!("database/migrations"));
    /// }
    /// ```
    #[cfg(feature = "database")]
    pub const fn migrations(&mut self) -> &mut crate::db::Migrations {
        &mut self.migrations
    }

    /// Registers a service that's already built. Everything that resolves `T` shares it.
    ///
    /// ```
    /// use laravel::container::Registrar;
    /// # pub struct Stripe;
    /// # impl Stripe { fn new(key: &str) -> Self { Stripe } }
    ///
    /// fn register(app: &mut Registrar) {
    ///     app.instance(Stripe::new("sk_test_..."));
    /// }
    /// ```
    pub fn instance<T: Send + Sync + 'static>(&mut self, service: T) -> &mut Self {
        self.instance_as(Arc::new(service))
    }

    /// Registers a shared service that's already built under `T`, which may be a trait object.
    ///
    /// The service registers as `T`, not `Arc<T>`, so code resolves `T` or takes `Inject<T>`.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use laravel::{Application, config::Env};
    ///
    /// trait Greeting: Send + Sync {
    ///     fn text(&self) -> &str;
    /// }
    ///
    /// struct Hello;
    ///
    /// impl Greeting for Hello {
    ///     fn text(&self) -> &str {
    ///         "Hello"
    ///     }
    /// }
    ///
    /// let app = Application::configure()
    ///     .replace_env(Env::default())
    ///     .with_services(|app| {
    ///         app.instance_as(Arc::new(Hello) as Arc<dyn Greeting>);
    ///     })
    ///     .create();
    ///
    /// laravel::testing::__run(async {
    ///     assert_eq!(app.resolve::<dyn Greeting>().await.text(), "Hello");
    /// });
    /// ```
    pub fn instance_as<T: ?Sized + Send + Sync + 'static>(&mut self, service: Arc<T>) -> &mut Self {
        self.services.instance_as(service);
        self
    }

    /// Registers a transient service, which an async factory builds anew on every resolution.
    ///
    /// Each resolution runs the factory, even when several run at the same time. The factory runs
    /// in the context that resolves the service, so in a request it sees the request's
    /// [context values](crate::context) and URL. A singleton that depends on a transient service
    /// keeps the instance it received when it was built.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use laravel::{Application, config::Env};
    ///
    /// struct Report;
    ///
    /// let app = Application::configure()
    ///     .replace_env(Env::default())
    ///     .with_services(|services| {
    ///         services.bind(|_| async { Ok(Report) });
    ///     })
    ///     .create();
    ///
    /// laravel::testing::__run(async {
    ///     let first: Arc<Report> = app.resolve::<Report>().await.into();
    ///     let second: Arc<Report> = app.resolve::<Report>().await.into();
    ///
    ///     assert!(!Arc::ptr_eq(&first, &second));
    /// });
    /// ```
    pub fn bind<T, F, Fut>(&mut self, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(Container) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<T>> + Send + 'static,
    {
        self.bind_as(move |app| factory(app).map(|built| built.map(Arc::new)))
    }

    /// Registers a transient service under `T`, which may be a trait object, built by a factory
    /// that returns `Arc<T>`.
    ///
    /// The factory runs on every resolution. It may return an existing handle to share it instead
    /// of building a new instance.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use laravel::container::Registrar;
    ///
    /// trait Reports: Send + Sync {}
    ///
    /// struct Report;
    ///
    /// impl Reports for Report {}
    ///
    /// fn register(app: &mut Registrar) {
    ///     app.bind_as(|_| async { Ok(Arc::new(Report) as Arc<dyn Reports>) });
    /// }
    /// ```
    pub fn bind_as<T, F, Fut>(&mut self, factory: F) -> &mut Self
    where
        T: ?Sized + Send + Sync + 'static,
        F: Fn(Container) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Arc<T>>> + Send + 'static,
    {
        self.factory(factory, Lifetime::Transient)
    }

    /// Registers a singleton, which an async factory builds the first time it's resolved, then
    /// shares.
    ///
    /// The factory resolves the services it depends on from the [`Container`] it receives, in
    /// whatever order they were registered. It runs in a context of its own, not in the request
    /// that first resolves the service. If the factory fails, the next resolution runs it again. A
    /// later registration of the same type, such as the application's own, replaces a package's
    /// service.
    ///
    /// ```
    /// use laravel::container::Registrar;
    /// # pub struct StripeConfig { key: String }
    /// # pub struct Stripe;
    /// # impl Stripe { fn new(key: &str) -> Self { Stripe } }
    ///
    /// fn register(app: &mut Registrar) {
    ///     app.singleton(async |app| {
    ///         let key = &app.config().section::<StripeConfig>().key;
    ///
    ///         Ok(Stripe::new(key))
    ///     });
    /// }
    /// ```
    pub fn singleton<T, F, Fut>(&mut self, factory: F) -> &mut Self
    where
        T: Send + Sync + 'static,
        F: Fn(Container) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<T>> + Send + 'static,
    {
        self.singleton_as(move |app| factory(app).map(|built| built.map(Arc::new)))
    }

    /// Registers a singleton under `T`, which may be a trait object, built by a factory that
    /// returns `Arc<T>`.
    ///
    /// The factory may resolve a concrete singleton and return its handle as a trait object, so
    /// both share one instance. A trait object must be `Send + Sync + 'static`.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use laravel::testing::MakesHttpRequests;
    /// use laravel::{Application, config::Env, container::Inject};
    ///
    /// trait Greeting: Send + Sync {
    ///     fn text(&self) -> &str;
    /// }
    ///
    /// struct Hello;
    ///
    /// impl Greeting for Hello {
    ///     fn text(&self) -> &str {
    ///         "Hello"
    ///     }
    /// }
    ///
    /// let app = Application::configure()
    ///     .replace_env(Env::default())
    ///     .with_services(|app| {
    ///         app.singleton(|_| async { Ok(Hello) });
    ///         app.singleton_as(|app| async move { Ok(app.resolve::<Hello>().await? as Arc<dyn Greeting>) });
    ///     })
    ///     .with_routing(|routing, _| {
    ///         routing.routes(|route| {
    ///             route.get("/", |greeting: Inject<dyn Greeting>| async move { greeting.text().to_owned() });
    ///         });
    ///     })
    ///     .create();
    ///
    /// laravel::testing::__run(async {
    ///     app.get("/").await.assert_see("Hello");
    /// });
    /// ```
    pub fn singleton_as<T, F, Fut>(&mut self, factory: F) -> &mut Self
    where
        T: ?Sized + Send + Sync + 'static,
        F: Fn(Container) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Arc<T>>> + Send + 'static,
    {
        self.factory(factory, Lifetime::Singleton)
    }

    fn factory<T, F, Fut>(&mut self, factory: F, lifetime: Lifetime) -> &mut Self
    where
        T: ?Sized + Send + Sync + 'static,
        F: Fn(Container) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Arc<T>>> + Send + 'static,
    {
        self.services.factory(factory, lifetime);
        self
    }

    /// Discovers and registers a crate's [`#[singleton]`](macro@super::singleton) and
    /// [`#[bind]`](macro@super::bind) services, [`#[listener]`](crate::event::listener) functions,
    /// [command functions](macro@crate::console::command), and
    /// [`#[schedule::tasks]`](macro@crate::schedule::tasks) functions.
    ///
    /// It leaves out the crate's [`#[seeder]`](macro@crate::db::seeder) functions. Only the
    /// application discovers seeders, with
    /// [`with_seeders`](crate::foundation::ApplicationBuilder::with_seeders).
    ///
    /// Applications discover the `app` crate automatically. They register its services after
    /// providers register theirs and before `with_services` callbacks, and register its listeners
    /// as [`Dispatcher::discover`] describes. To opt in another crate, pass
    /// `env!("CARGO_CRATE_NAME")` from a package's provider, or from an application with a custom
    /// library name. Discovering a crate again does nothing. If two of a crate's services register
    /// under the same type, the application doesn't start, and the startup error names both.
    ///
    /// ```
    /// use laravel::{container::Registrar, foundation::ServiceProvider};
    ///
    /// struct BillingServiceProvider;
    ///
    /// impl ServiceProvider for BillingServiceProvider {
    ///     fn register(&self, app: &mut Registrar) {
    ///         app.discover(env!("CARGO_CRATE_NAME"));
    ///     }
    /// }
    /// ```
    pub fn discover(&mut self, crate_name: &str) -> &mut Self {
        self.discover_services(crate_name);
        self.events.discover(crate_name);
        self.commands.discover(crate_name);
        self.schedule.discover(crate_name, self.services.config());

        self
    }

    fn discover_services(&mut self, crate_name: &str) {
        if !self.discovered_crates.insert(crate_name.to_owned()) {
            return;
        }

        let mut services: Vec<_> = inventory::iter::<__Registration>
            .into_iter()
            .filter(|service| service.crate_name == crate_name)
            .collect();
        services.sort_unstable_by_key(|service| (service.name)());

        let provider = self.services.provider;
        self.services.discovering = Some(HashMap::new());
        for service in services {
            self.services.provider = Some((service.name)());
            (service.register)(self);
        }
        self.services.discovering = None;
        self.services.provider = provider;
    }

    /// Register a discovered service's factory, returning a handle to add its contracts.
    #[doc(hidden)]
    pub fn __service<T, F, Fut>(&mut self, factory: F, transient: bool) -> __Service<'_, T>
    where
        T: Send + Sync + 'static,
        F: Fn(Container) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<T>> + Send + 'static,
    {
        let lifetime = if transient {
            Lifetime::Transient
        } else {
            Lifetime::Singleton
        };
        self.factory(move |app| factory(app).map(|built| built.map(Arc::new)), lifetime);

        __Service {
            registrar: self,
            lifetime,
            service: PhantomData,
        }
    }
}

impl fmt::Debug for Registrar {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Registrar")
            .field("services", &self.services)
            .finish_non_exhaustive()
    }
}

/// A discovered service's registration, for adding the trait contracts it's also registered under.
#[doc(hidden)]
pub struct __Service<'a, T> {
    registrar: &'a mut Registrar,
    lifetime: Lifetime,
    service: PhantomData<fn() -> T>,
}

impl<T> fmt::Debug for __Service<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("__Service")
            .field("service", &std::any::type_name::<T>())
            .field("lifetime", &self.lifetime)
            .finish_non_exhaustive()
    }
}

impl<T: Send + Sync + 'static> __Service<'_, T> {
    /// Resolve `C` through the service, using the same lifetime.
    #[doc(hidden)]
    pub fn __contract<C: ?Sized + Send + Sync + 'static>(&mut self, coerce: fn(Arc<T>) -> Arc<C>) -> &mut Self {
        self.registrar.factory(
            move |app| async move { Ok(coerce(app.resolve::<T>().await?)) },
            self.lifetime,
        );

        self
    }
}

/// A discovered service: what [`Registrar::discover`] registers for its crate.
#[doc(hidden)]
#[derive(Debug)]
pub struct __Registration {
    pub crate_name: &'static str,
    pub name: fn() -> &'static str,
    pub register: fn(&mut Registrar),
}
inventory::collect!(__Registration);