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
use std::any::type_name;
use std::fmt;
use std::future::Future;
use std::sync::Arc;

use futures_util::future::BoxFuture;

use crate::config::{Config, Env};
use crate::container::{Container, Registrar};
use crate::error::Result;

/// Adds services, config, routes, and middleware to an application.
///
/// A service provider is a package's entry point. An application needs no provider of its own,
/// because its builder has callbacks for the same registrations, such as
/// [`with_services`](super::ApplicationBuilder::with_services) and
/// [`booted`](super::ApplicationBuilder::booted). Those callbacks run after every provider's
/// hooks.
///
/// Every method is optional. Each method runs for every provider, in the order the providers
/// were added, after the framework's internal providers. When the application is created:
///
/// 1. `config` sets the provider's config defaults.
/// 2. The application's config files replace the values they need.
/// 3. `register` declares services, routes, views, and other definitions with the final
///    config, before the application's registration callbacks run.
///
/// When the application boots, `boot` runs. Services are built the first time something
/// resolves them.
///
/// ```
/// use laravel::config::{Config, Env};
/// use laravel::container::{Container, Inject, Registrar};
/// use laravel::foundation::ServiceProvider;
///
/// pub struct StripeConfig { key: String, webhooks: bool }
/// pub struct Stripe { key: String }
///
/// pub struct StripeServiceProvider;
///
/// impl ServiceProvider for StripeServiceProvider {
///     fn config(&self, config: &mut Config, env: &Env) {
///         config.set(StripeConfig {
///             key: env.get("STRIPE_KEY").unwrap_or_default(),
///             webhooks: env.get("STRIPE_WEBHOOKS").unwrap_or(true),
///         });
///     }
///
///     fn register(&self, app: &mut Registrar) {
///         app.singleton(|app| async move {
///             Ok(Stripe { key: app.config().section::<StripeConfig>().key.clone() })
///         });
///
///         if app.config().section::<StripeConfig>().webhooks {
///             app.routing().web(|route| {
///                 route.post("/stripe/webhook", webhook);
///             });
///         }
///     }
/// }
///
/// async fn webhook(stripe: Inject<Stripe>) -> &'static str {
///     "Received"
/// }
/// ```
pub trait ServiceProvider: Send + Sync + 'static {
    /// Set the defaults of the provider's config sections, usually read from the environment.
    ///
    /// The application's config files run after every provider's `config` hook, so they can replace
    /// these defaults.
    fn config(&self, config: &mut Config, env: &Env) {
        let _ = (config, env);
    }

    /// Declare services and configure the application's subsystem builders through [`Registrar`].
    ///
    /// The configuration is final, but services aren't built yet, so resolve dependencies in
    /// factories rather than in this hook. The application's callbacks run after every provider's
    /// `register` hook and can override its registrations.
    fn register(&self, app: &mut Registrar) {
        let _ = app;
    }

    /// Validate services and initialize integrations when the application boots.
    ///
    /// The hook runs once every provider has registered. Resolving a service here builds the
    /// service if it isn't built yet. Services are shared, so configure them in their factories
    /// rather than by mutating them here. The application's `booted` callbacks run after every
    /// provider's `boot` hook.
    ///
    /// ```
    /// use laravel::container::Container;
    /// use laravel::foundation::ServiceProvider;
    /// # pub struct Search;
    /// # impl Search { fn validate(&self) -> laravel::Result<()> { Ok(()) } }
    ///
    /// pub struct SearchServiceProvider;
    ///
    /// impl ServiceProvider for SearchServiceProvider {
    ///     async fn boot(&self, app: &Container) -> laravel::Result<()> {
    ///         app.resolve::<Search>().await?.validate()
    ///     }
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// An error stops the application from booting.
    fn boot(&self, app: &Container) -> impl Future<Output = Result<()>> + Send {
        let _ = app;
        async { Ok(()) }
    }
}

pub(crate) trait AnyProvider: Send + Sync + 'static {
    fn config(&self, config: &mut Config, env: &Env);

    fn register(&self, app: &mut Registrar);

    fn boot<'a>(&'a self, app: &'a Container) -> BoxFuture<'a, Result<()>>;
}

impl<P: ServiceProvider> AnyProvider for P {
    fn config(&self, config: &mut Config, env: &Env) {
        ServiceProvider::config(self, config, env);
    }

    fn register(&self, app: &mut Registrar) {
        ServiceProvider::register(self, app);
    }

    fn boot<'a>(&'a self, app: &'a Container) -> BoxFuture<'a, Result<()>> {
        Box::pin(ServiceProvider::boot(self, app))
    }
}

/// A provider, with its name for error messages.
#[derive(Clone)]
pub struct Provider {
    pub(crate) name: &'static str,
    pub(crate) provider: Arc<dyn AnyProvider>,
}

/// The application's service providers, in the order they run.
///
/// Package providers usually come first, followed by any providers of the application's own.
///
/// ```
/// use laravel::foundation::ServiceProvider;
///
/// pub struct StripeServiceProvider;
///
/// impl ServiceProvider for StripeServiceProvider {}
///
/// let app = laravel::Application::configure()
///     .with_providers(|providers| {
///         providers.add(StripeServiceProvider);
///     })
///     .create();
///
/// assert_eq!(app.providers().names().len(), 1);
/// ```
#[derive(Default, Clone)]
pub struct Providers(Vec<Provider>);

pub(super) fn framework() -> Providers {
    let mut providers = Providers::default();
    providers.add(super::commands::ConsoleServiceProvider);
    providers.add(super::providers::ViewServiceProvider);
    #[cfg(feature = "database")]
    providers.add(crate::db::DatabaseServiceProvider);
    #[cfg(feature = "database")]
    providers.add(crate::session::database::DatabaseSessionServiceProvider);
    #[cfg(feature = "redis")]
    providers.add(RedisServiceProvider);
    providers.add(crate::cache::CacheServiceProvider);
    providers.add(crate::feature::FeatureServiceProvider);
    #[cfg(feature = "search")]
    providers.add(crate::search::SearchServiceProvider);
    providers.add(super::providers::StorageServiceProvider);
    providers.add(super::providers::ClientServiceProvider);
    providers.add(super::providers::AuthServiceProvider);
    providers.add(super::providers::EventsServiceProvider);
    providers.add(super::providers::NotificationsServiceProvider);
    providers.add(super::providers::WorkflowServiceProvider);
    providers.add(super::providers::ScheduleServiceProvider);
    providers
}

impl Providers {
    /// Add a provider after the providers already added.
    pub fn add<P: ServiceProvider>(&mut self, provider: P) -> &mut Self {
        self.0.push(Provider {
            name: type_name::<P>(),
            provider: Arc::new(provider),
        });
        self
    }

    /// The providers' names, in order.
    pub fn names(&self) -> impl ExactSizeIterator<Item = &'static str> {
        self.0.iter().map(|provider| provider.name)
    }

    pub(crate) fn iter(&self) -> impl Iterator<Item = &Provider> {
        self.0.iter()
    }

    pub(super) fn extend(&mut self, providers: Self) {
        self.0.extend(providers.0);
    }
}

impl fmt::Debug for Providers {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.names()).finish()
    }
}

#[cfg(feature = "redis")]
struct RedisServiceProvider;

#[cfg(feature = "redis")]
impl ServiceProvider for RedisServiceProvider {
    fn register(&self, app: &mut Registrar) {
        app.instance(crate::redis::RedisManager::new(&app.config().redis));
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use super::*;
    use crate::Application;
    use crate::console::{Console, ConsoleInternals as _, clap};
    use crate::container::Inject;
    use crate::testing::MakesConsoleRequests;

    struct Origin(Mutex<Vec<&'static str>>);

    struct RecordingProvider {
        name: &'static str,
        events: Arc<Mutex<Vec<String>>>,
    }

    impl RecordingProvider {
        fn record(&self, phase: &str) {
            self.events.lock().unwrap().push(format!("{}:{phase}", self.name));
        }

        fn configured(&self, phase: &str, config: &Config) {
            assert_eq!(config.app.name, "final");
            self.record(phase);
        }
    }

    impl ServiceProvider for RecordingProvider {
        fn config(&self, config: &mut Config, _: &Env) {
            self.record("config");
            config.app.name = self.name.to_owned();
        }

        fn register(&self, services: &mut Registrar) {
            self.configured("register", services.config());
            services.instance(Origin(Mutex::new(vec![self.name])));
            let name = self.name;
            services.routing().api(move |route| {
                route.get(&format!("/{name}"), || async { "hello" });
            });
            services.commands().add::<Inspect>();
        }

        async fn boot(&self, services: &Container) -> Result<()> {
            self.configured("boot", services.config());
            services.resolve::<Origin>().await?.0.lock().unwrap().push(self.name);
            Ok(())
        }
    }

    #[derive(clap::Parser)]
    #[command(name = "inspect")]
    struct Inspect;

    #[crate::console::command]
    impl Inspect {
        async fn handle(self, app: &Application, origin: Inject<Origin>, console: &mut Console) -> Result<()> {
            assert_eq!(
                *origin.0.lock().unwrap(),
                ["application", "first", "second", "package", "booted"]
            );
            assert_eq!(
                app.routes().len(),
                4,
                "each provider's route and the workflow resume route"
            );
            console.line("booted");
            Ok(())
        }
    }

    #[tokio::test]
    async fn multiple_framework_providers_share_every_phase_and_boot_before_application_callbacks() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let mut builder = Application::configure().replace_env(Env::default());
        for name in ["first", "second"] {
            builder.framework_providers.add(RecordingProvider {
                name,
                events: Arc::clone(&events),
            });
        }
        let configuring = Arc::clone(&events);
        let registering_listeners = Arc::clone(&events);
        let registering = Arc::clone(&events);
        let booting = Arc::clone(&events);
        let app = builder
            .with_providers(|providers| {
                providers.add(RecordingProvider {
                    name: "package",
                    events: Arc::clone(&events),
                });
            })
            .with_config(move |config, _| {
                configuring.lock().unwrap().push("application:config".to_owned());
                config.app.name = "final".to_owned();
            })
            .with_services(move |services| {
                registering.lock().unwrap().push("application:register".to_owned());
                services.instance(Origin(Mutex::new(vec!["application"])));
            })
            .with_events(move |_, config| {
                assert_eq!(config.app.name, "final");
                registering_listeners
                    .lock()
                    .unwrap()
                    .push("application:events".to_owned());
            })
            .booted(move |services| async move {
                booting.lock().unwrap().push("application:boot".to_owned());
                services.resolve::<Origin>().await?.0.lock().unwrap().push("booted");
                Ok(())
            })
            .create();
        assert_eq!(app.providers().names().count(), 1);
        let _ = app
            .command("inspect")
            .await
            .assert_successful()
            .assert_output_contains("booted");
        let _ = app
            .command("list")
            .await
            .assert_successful()
            .assert_output_contains("route:list");
        let expected = ["config", "register", "events", "boot"]
            .into_iter()
            .flat_map(|phase| {
                ["first", "second", "package"]
                    .into_iter()
                    .filter(move |_| phase != "events")
                    .chain(std::iter::once("application"))
                    .map(move |provider| format!("{provider}:{phase}"))
            })
            .collect::<Vec<_>>();
        assert_eq!(*events.lock().unwrap(), expected);
    }

    #[derive(clap::Parser)]
    #[command(name = "binary:name")]
    struct BinaryName;

    #[crate::console::command]
    impl BinaryName {
        async fn handle(self, console: &mut Console) -> Result<()> {
            tokio::task::yield_now().await;
            console.line(crate::console::commands().get_bin_name().unwrap());
            Ok(())
        }
    }

    #[tokio::test]
    async fn command_metadata_retains_the_executable_name_per_invocation() {
        let app = Application::configure()
            .replace_env(Env::default())
            .with_commands(|commands, _| {
                commands.add::<BinaryName>();
            })
            .create();
        let first = async {
            let mut console = Console::captured();
            let code = app
                .run_command("first".into(), vec!["binary:name".into()], &mut console)
                .await;
            assert_eq!(code, 0);
            assert_eq!(console.into_output().0.trim(), "first");
        };
        let second = async {
            let mut console = Console::captured();
            let code = app
                .run_command("second".into(), vec!["binary:name".into()], &mut console)
                .await;
            assert_eq!(code, 0);
            assert_eq!(console.into_output().0.trim(), "second");
        };
        tokio::join!(first, second);
    }

    #[tokio::test]
    async fn framework_provider_boot_failures_prevent_command_execution_and_help() {
        struct FailingProvider;

        impl ServiceProvider for FailingProvider {
            async fn boot(&self, _: &Container) -> Result<()> {
                Err(anyhow::anyhow!("internal boot failed").into())
            }
        }

        let mut builder = Application::configure().replace_env(Env::default());
        builder.framework_providers.add(FailingProvider);
        let app = builder.create();
        for invocation in ["list", "serve --help"] {
            let _ = app
                .command(invocation)
                .await
                .assert_exit_code(1)
                .assert_error_output_contains("FailingProvider")
                .assert_error_output_contains("internal boot failed");
        }
    }

    #[derive(Clone)]
    struct DiscoveredSection(&'static str);

    inventory::submit! {
        crate::config::__Registration {
            crate_name: "app",
            name: || "app::Discovered",
            configure: |config, _env| { config.set(DiscoveredSection("discovered")); },
        }
    }

    #[test]
    fn app_sections_are_set_after_providers_and_before_config_files() {
        struct Package;
        impl ServiceProvider for Package {
            fn config(&self, config: &mut Config, _env: &Env) {
                config.set(DiscoveredSection("provider"));
            }
        }
        let app = Application::configure()
            .replace_env(Env::default())
            .with_providers(|providers| {
                providers.add(Package);
            })
            .with_config(|config, _| {
                assert_eq!(config.section::<DiscoveredSection>().0, "discovered");
                config.section_mut::<DiscoveredSection>().0 = "config file";
            })
            .create();

        assert_eq!(app.config().section::<DiscoveredSection>().0, "config file");
    }
}