Skip to content

Commit

Permalink
prep v0.10.0 (#811)
Browse files Browse the repository at this point in the history
releasing v0.10.x
  • Loading branch information
jondot authored Oct 13, 2024
1 parent e544fa4 commit 19a52ab
Show file tree
Hide file tree
Showing 51 changed files with 1,148 additions and 1,355 deletions.
14 changes: 12 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

* `Format(respond_to): Format` extractor in controller can now be replaced with `respond_to: RespondTo` extractor for less typing.
* When supplying data to views, you can now use `data!` instead of `serde_json::json!` for shorthand.
* Refactor middlewares. [https://github.com/loco-rs/loco/pull/785](https://github.com/loco-rs/loco/pull/785)
* Refactor middlewares. [https://github.com/loco-rs/loco/pull/785](https://github.com/loco-rs/loco/pull/785). Middleware selection, configuration, and tweaking is MUCH more powerful and convenient now. You can keep the `middleware:` section empty or remove it now, see more in [the middleware docs](https://loco.rs/docs/the-app/controller/#middleware)
* **NEW (BREAKING)** background worker subsystem is now queue agnostic. Providing for both Redis and Postgres with a change of configuration. This means you can now use a full-Postgres stack to remove Redis as a dependency if you wish. Here are steps to migrate your codebase:

```rust
Expand All @@ -21,9 +21,11 @@ async fn connect_workers(ctx: &AppContext, queue: &Queue) -> Result<()>{
Ok(())
}

// in your app.rs, remove the `worker` module references.
// in your app.rs, replace the `worker` module references.
// REMOVE
worker::{AppWorker, Processor},
// REPLACE WITH
bgworker::{BackgroundWorker, Queue},

// in your workers change the signature, and add the `build` function

Expand All @@ -49,6 +51,14 @@ impl worker::AppWorker<DownloadWorkerArgs> for DownloadWorker {
}
```

Finally, update your `development.yaml` and `test.yaml` with a `kind`:

```yaml
queue:
kind: Redis # add this to the existing `queue` section
```
* **UPGRADED (BREAKING)**: `validator` crate was upgraded which require some small tweaks to work with the new API:

```rust
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ license = "Apache-2.0"

[package]
name = "loco-rs"
version = "0.9.0"
version = "0.10.1"
description = "The one-person framework for Rust"
homepage = "https://loco.rs/"
documentation = "https://docs.rs/loco-rs"
Expand Down
162 changes: 154 additions & 8 deletions docs-site/content/docs/the-app/controller.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,13 +261,148 @@ impl Hooks for App {

Loco comes with a set of built-in middleware out of the box. Some are enabled by default, while others need to be configured. Middleware registration is flexible and can be managed either through the `*.yaml` environment configuration or directly in the code.

## The default stack

You get all the enabled middlewares run the following command
<!-- <snip id="cli-middleware-list" inject_from="yaml" template="sh"> -->
```sh
cargo loco middleware --config
```
<!-- </snip> -->

This is the stack in `development` mode:

```sh
$ cargo loco middleware --config

limit_payload {"enable":true,"body_limit":2000000}
cors {"enable":true,"allow_origins":["any"],"allow_headers":["*"],"allow_methods":["*"],"max_age":null,"vary":["origin","access-control-request-method","access-control-request-headers"]}
catch_panic {"enable":true}
etag {"enable":true}
logger {"config":{"enable":true},"environment":"development"}
request_id {"enable":true}
fallback {"enable":true,"code":200,"file":null,"not_found":null}
powered_by {"ident":"loco.rs"}


remote_ip (disabled)
compression (disabled)
timeout (disabled)
static_assets (disabled)
secure_headers (disabled)
```

### Example: disable all middleware

Take what ever is enabled, and use `enable: false` with the relevant field. If `middlewares:` section in `server` is missing, add it.

```yaml
server:
middlewares:
limit_payload:
enable: false
cors:
enable: false
catch_panic:
enable: false
etag:
enable: false
logger:
enable: false
request_id:
enable: false
fallback:
enable: false
```
The result:
```sh
$ cargo loco middleware --config
powered_by {"ident":"loco.rs"}


limit_payload (disabled)
cors (disabled)
catch_panic (disabled)
etag (disabled)
remote_ip (disabled)
compression (disabled)
timeout_request (disabled)
static (disabled)
secure_headers (disabled)
logger (disabled)
request_id (disabled)
fallback (disabled)
```

You can control the `powered_by` middleware by changing the value for `server.ident`:

```yaml
server:
ident: my-server #(or empty string to disable)
```
### Example: add a non-default middleware
Lets add the _Remote IP_ middleware to the stack. This is done just by configuration:
```yaml
server:
middlewares:
remote_ip:
enable: true
```
The result:
```sh
$ cargo loco middleware --config

limit_payload {"enable":true,"body_limit":2000000}
cors {"enable":true,"allow_origins":["any"],"allow_headers":["*"],"allow_methods":["*"],"max_age":null,"vary":["origin","access-control-request-method","access-control-request-headers"]}
catch_panic {"enable":true}
etag {"enable":true}
remote_ip {"enable":true,"trusted_proxies":null}
logger {"config":{"enable":true},"environment":"development"}
request_id {"enable":true}
fallback {"enable":true,"code":200,"file":null,"not_found":null}
powered_by {"ident":"loco.rs"}
```

### Example: change a configuration for an enabled middleware

Let's change the request body limit to `5mb`. When overriding a middleware configuration, rememeber to keep an `enable: true`:

```yaml
middlewares:
limit_payload:
enable: true
body_limit: 5mb
```
The result:
```sh
$ cargo loco middleware --config

limit_payload {"enable":true,"body_limit":5000000}
cors {"enable":true,"allow_origins":["any"],"allow_headers":["*"],"allow_methods":["*"],"max_age":null,"vary":["origin","access-control-request-method","access-control-request-headers"]}
catch_panic {"enable":true}
etag {"enable":true}
logger {"config":{"enable":true},"environment":"development"}
request_id {"enable":true}
fallback {"enable":true,"code":200,"file":null,"not_found":null}
powered_by {"ident":"loco.rs"}


remote_ip (disabled)
compression (disabled)
timeout_request (disabled)
static (disabled)
secure_headers (disabled)
```

### Authentication
In the `Loco` framework, middleware plays a crucial role in authentication. `Loco` supports various authentication methods, including JSON Web Token (JWT) and API Key authentication. This section outlines how to configure and use authentication middleware in your application.

Expand Down Expand Up @@ -523,6 +658,16 @@ server:
foo: bar
```
To support `htmx`, You can add the following override, to allow some inline running of scripts:

```yaml
secure_headers:
preset: github
overrides:
# this allows you to use HTMX, and has unsafe-inline. Remove or consider in production
"Content-Security-Policy": "default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src 'unsafe-inline' 'self' https:; style-src 'self' https: 'unsafe-inline'"
```

## Compression

`Loco` leverages [CompressionLayer](https://docs.rs/tower-http/0.5.0/tower_http/compression/index.html) to enable a `one click` solution.
Expand Down Expand Up @@ -554,14 +699,7 @@ middlewares:
precompressed: true
```

## Handler and Route based middleware

`Loco` also allow us to apply [layers](https://docs.rs/tower/latest/tower/trait.Layer.html) to specific handlers or
routes.
For more information on handler and route based middleware, refer to the [middleware](/docs/the-app/middlewares)
documentation.

## Cors
## CORS
This middleware enables Cross-Origin Resource Sharing (CORS) by allowing configurable origins, methods, and headers in HTTP requests.
It can be tailored to fit various application requirements, supporting permissive CORS or specific rules as defined in the middleware configuration.

Expand All @@ -585,6 +723,14 @@ middlewares:

```

## Handler and Route based middleware

`Loco` also allow us to apply [layers](https://docs.rs/tower/latest/tower/trait.Layer.html) to specific handlers or
routes.
For more information on handler and route based middleware, refer to the [middleware](/docs/the-app/middlewares)
documentation.


### Handler based middleware:

Apply a layer to a specific handler using `layer` method.
Expand Down
2 changes: 1 addition & 1 deletion examples/demo/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

53 changes: 1 addition & 52 deletions examples/demo/config/development.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,58 +30,7 @@ server:
port: {{ get_env(name="NODE_PORT", default=5150) }}
# The UI hostname or IP address that mailers will point to.
host: http://localhost
# Out of the box middleware configuration. to disable middleware you can changed the `enable` field to `false` of comment the middleware block
# </snip>
middlewares:
# Allows to limit the payload size request. payload that bigger than this file will blocked the request.
limit_payload:
# Enable/Disable the middleware.
enable: true
# the limit size. can be b,kb,kib,mb,mib,gb,gib
body_limit: 5mb
# set secure headers
secure_headers:
preset: github
overrides:
# this allows you to use HTMX, and has unsafe-inline. Remove or consider in production
"Content-Security-Policy": "default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src 'unsafe-inline' 'self' https:; style-src 'self' https: 'unsafe-inline'"
# Generating a unique request ID and enhancing logging with additional information such as the start and completion of request processing, latency, status code, and other request details.
logger:
# Enable/Disable the middleware.
enable: true
# when your code is panicked, the request still returns 500 status code.
catch_panic:
# Enable/Disable the middleware.
enable: true
# Timeout for incoming requests middleware. requests that take more time from the configuration will cute and 408 status code will returned.
timeout_request:
# Enable/Disable the middleware.
enable: true
# Duration time in milliseconds.
timeout: 5000
compression:
# Enable/Disable the middleware.
enable: true
static_assets:
enable: true
must_exist: true
precompressed: true
folder:
path: assets
fallback: index.html
cors:
enable: true
# Set the value of the [`Access-Control-Allow-Origin`][mdn] header
# allow_origins:
# - https://loco.rs
# Set the value of the [`Access-Control-Allow-Headers`][mdn] header
# allow_headers:
# - Content-Type
# Set the value of the [`Access-Control-Allow-Methods`][mdn] header
# allow_methods:
# - POST
# Set the value of the [`Access-Control-Max-Age`][mdn] header in seconds
# max_age: 3600
# </snip>

# Worker Configuration
workers:
Expand Down
2 changes: 1 addition & 1 deletion loco-extras/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ mongodb = { version = "2.8.0", optional = true }

[dependencies.loco-rs]
path = "../"
version = "0.9.0"
version = "*"
default-features = true
features = ["with-db", "auth_jwt"]

Expand Down
7 changes: 6 additions & 1 deletion src/bgworker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl Queue {
#[cfg(feature = "bg_pg")]
Self::Postgres(_, registry, _) => {
let mut r = registry.lock().await;
r.register_worker(W::class_name(), worker);
r.register_worker(W::class_name(), worker)?;
}
_ => {}
}
Expand Down Expand Up @@ -250,6 +250,11 @@ pub trait BackgroundWorker<A: Send + Sync + serde::Serialize + 'static>: Send +
async fn perform(&self, args: A) -> crate::Result<()>;
}

/// Initialize the system according to configuration
///
/// # Errors
///
/// This function will return an error if it fails
pub async fn converge(queue: &Queue, config: &QueueConfig) -> Result<()> {
queue.setup().await?;
match config {
Expand Down
Loading

0 comments on commit 19a52ab

Please sign in to comment.