Skip to content

Commit

Permalink
api_server: add option to start api server in background
Browse files Browse the repository at this point in the history
The existing serve function returns a future that must be awaited on for
the server to run. This causes the caller to block and does not allow
the server to be halted unless the process is terminated.

This is not ideal when using the server as a crate (or in a test).

Instead, add a function that returns a server which can then be awaited
on or run in the background.

Signed-off-by: Tobin Feldman-Fitzthum <[email protected]>
  • Loading branch information
fitzthum committed Dec 10, 2024
1 parent 050b619 commit 6ebd64b
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions kbs/src/api_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,51 @@ impl ApiServer {
.await
.map_err(|e| Error::HTTPFailed { source: e.into() })
}

/// Setup API server
pub fn server(self) -> Result<actix_web::dev::Server> {
info!(
"Starting HTTP{} server at {:?}",
if !self.config.http_server.insecure_http {
"S"
} else {
""
},
self.config.http_server.sockets
);

let http_config = self.config.http_server.clone();
let http_server = HttpServer::new({
move || {
let api_server = self.clone();
App::new()
.wrap(middleware::Logger::default())
.app_data(web::Data::new(api_server))
.service(
web::resource([kbs_path!("{base_path}{additional_path:.*}")])
.route(web::get().to(api))
.route(web::post().to(api)),
)
}
});

if !http_config.insecure_http {
let tls_server = http_server
.bind_openssl(
&http_config.sockets[..],
crate::http::tls_config(&http_config)
.map_err(|e| Error::HTTPSFailed { source: e })?,
)
.map_err(|e| Error::HTTPSFailed { source: e.into() })?;

return Ok(tls_server.run());
}

Ok(http_server
.bind(&http_config.sockets[..])
.map_err(|e| Error::HTTPFailed { source: e.into() })?
.run())
}
}

/// APIs
Expand Down

0 comments on commit 6ebd64b

Please sign in to comment.