Create the scaffolding in Tide for Contaminate, nothing but /v2/* is implemented

This commit is contained in:
R Tyler Croy 2020-02-01 08:03:35 -08:00
parent df8c932a0c
commit d8768d12ae
No known key found for this signature in database
GPG Key ID: E5C92681BEF6CEA2
1 changed files with 68 additions and 2 deletions

View File

@ -4,9 +4,12 @@
extern crate config;
extern crate pretty_env_logger;
extern crate surf;
extern crate tide;
use async_std::task;
use log::*;
use tide::{Request, Response};
/**
* Load the settings based on the hierarchy.
@ -27,16 +30,79 @@ fn load_settings() -> config::Config {
.merge(config::Environment::with_prefix("CT"))
.expect("Failed to load settings defined by CT_* env vars");
debug!("Loaded configuration: {:?}", settings);
return settings;
}
/**
* AppState is a simple struct to carry information into request handlers
*/
struct AppState {
conf: config::Config,
upstream: String,
}
/**
* Proxy the given response to the upstream registry and return the response
* back to the client request it.
*/
async fn proxy_upstream(req: Request<AppState>) -> Response {
let full_url = format!("{}{}", req.state().upstream, req.uri());
info!("Proxying request upstream to {}", full_url);
if let Ok(mut u_res) = surf::get(full_url).await {
let status = u_res.status().as_u16();
let body = u_res.body_string().await;
match body {
Ok(body) => {
Response::new(status).body_string(body)
},
Err(err) => {
error!("Failed to make upstream request: {:?}", err);
Response::new(500)
},
}
}
else {
Response::new(500)
}
}
async fn fetch_digest(_req: Request<AppState>) -> String {
format!("fetch_digest")
}
async fn fetch_blob(_req: Request<AppState>) -> String {
format!("fetch_blob")
}
fn main() -> Result<(), std::io::Error> {
pretty_env_logger::init();
let conf = load_settings();
let upstream_url = conf.get_str("registry")
.expect("`registry` not properly configured, must be a string");
info!("Starting with the following upstream: {}", upstream_url);
let state = AppState {
conf: conf,
upstream: upstream_url,
};
task::block_on(async {
let mut app = tide::new();
let mut app = tide::with_state(state);
app.at("/").get(|_| async move { "Hello, world!" });
app.listen("127.0.0.1:9000").await?;
app.at("/v2/:org/:image/manifests/:digest").get(fetch_digest);
app.at("/v2/:org/:image/blobs/:sha").get(fetch_blob);
/*
* The catch-all for the remainder of the v2 API calls should proxy to
* the upstream repository, since Contaminate does not implement a full
* registry API
*/
app.at("/v2/*").get(proxy_upstream);
app.listen("127.0.0.1:9090").await?;
Ok(())
})
}