Function merino_web::run

source · []
pub fn run(
    listener: TcpListener,
    metrics_client: StatsdClient,
    settings: Settings,
    providers: SuggestionProviderRef
) -> Result<Server, Error>
Expand description

Run the web server

The returned server is a Future that must either be .awaited, or run it as a background task using tokio::spawn.

Most of the details from settings will be respected, except for those that go into building the listener (the host and port). If you want to respect the settings specified in that object, you must include them in the construction of listener.

Context

The code initialized here emits logs and metrics, assuming global defaults have been set. Logs are emitted via tracing, and metrics via cadence.

Errors

Returns an error if the server cannot be started on the provided listener.

Examples

Run the server in the foreground. This will only return if there is an error that causes the server to shut down. This is used to run Merino as a service, such as in production.

let listener = std::net::TcpListener::bind("127.0.0.1:8080")
    .expect("Failed to bind port");
let settings = merino_settings::Settings::load().await
    .expect("Failed to load settings");
let metrics_client = cadence::StatsdClient::from_sink("merino", cadence::NopMetricSink);
let providers = merino_web::providers::SuggestionProviderRef::init(settings.clone(), metrics_client.clone())
                .await
                .expect("Could not create providers");
let server = merino_web::run(listener, metrics_client, settings, providers)
    .expect("Failed to start server")
    .await
    .expect("Fatal error while running server");

Run the server as a background task. This will return immediately and process requests. This is useful for tests.

use std::net::TcpListener;
use merino_settings::Settings;

let listener = TcpListener::bind("127.0.0.1:8080")
    .expect("Failed to bind port");
let settings = merino_settings::Settings::load().await
    .expect("Failed to load settings");
let metrics_client = cadence::StatsdClient::from_sink("merino", cadence::NopMetricSink);
let providers = merino_web::providers::SuggestionProviderRef::init(settings.clone(), metrics_client.clone())
                .await
                .expect("Could not create providers");
let server = merino_web::run(listener, metrics_client, settings, providers)
    .expect("Failed to start server");

/// The server can be stopped with `join_handle::abort()`, if needed.
let join_handle = tokio::spawn(server);