Skip to content

Commit

Permalink
Merge #731 'Save typing on anyhow::Result'
Browse files Browse the repository at this point in the history
Most files don't use any other kind of Result; might as well omit `anyhow::`.
  • Loading branch information
mergify[bot] committed Jan 27, 2022
2 parents 1e4aa56 + 3846578 commit dd9b7f7
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 56 deletions.
12 changes: 6 additions & 6 deletions server/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::query::engine::SqlWithArguments;
use crate::runtime;
use crate::types::{ObjectType, Type, OAUTHUSER_TYPE_NAME};
use crate::JsonObject;
use anyhow::anyhow;
use anyhow::{anyhow, Result};
use futures::{Future, FutureExt};
use hyper::{header, Request, Response, StatusCode};
use serde_json::json;
Expand All @@ -33,7 +33,7 @@ fn bad_request(msg: String) -> Response<Body> {
.unwrap()
}

pub(crate) fn get_oauth_user_type() -> anyhow::Result<Arc<ObjectType>> {
pub(crate) fn get_oauth_user_type() -> Result<Arc<ObjectType>> {
match runtime::get()
.type_system
.lookup_builtin_type(OAUTHUSER_TYPE_NAME)
Expand All @@ -44,7 +44,7 @@ pub(crate) fn get_oauth_user_type() -> anyhow::Result<Arc<ObjectType>> {
}

/// Upserts username into OAuthUser type, returning its ID.
async fn insert_user_into_db(username: &str) -> anyhow::Result<String> {
async fn insert_user_into_db(username: &str) -> Result<String> {
let oauth_user_type = get_oauth_user_type()?;
let mut user = JsonObject::new();
let query_engine = { runtime::get().query_engine.clone() };
Expand Down Expand Up @@ -76,7 +76,7 @@ async fn insert_user_into_db(username: &str) -> anyhow::Result<String> {

fn handle_callback(
req: Request<hyper::Body>,
) -> Pin<Box<dyn Future<Output = Result<Response<Body>, anyhow::Error>>>> {
) -> Pin<Box<dyn Future<Output = Result<Response<Body>>>>> {
// TODO: Grab state out of the request, validate it, and grab the referrer URL out of it.
async move {
let params = req.uri().query();
Expand Down Expand Up @@ -105,7 +105,7 @@ fn handle_callback(
.boxed_local()
}

async fn lookup_user(req: Request<hyper::Body>) -> anyhow::Result<Response<Body>> {
async fn lookup_user(req: Request<hyper::Body>) -> Result<Response<Body>> {
match get_username(&req).await {
None => anyhow::bail!("Error finding logged-in user; perhaps no one is logged in?"),
Some(username) => Ok(response_template().body(username.into()).unwrap()),
Expand All @@ -124,7 +124,7 @@ pub(crate) fn init(api: &mut ApiService) {
}

/// Returns the user ID corresponding to the token in req. If token is absent, returns None.
pub(crate) async fn get_user(req: &Request<hyper::Body>) -> anyhow::Result<Option<String>> {
pub(crate) async fn get_user(req: &Request<hyper::Body>) -> Result<Option<String>> {
match req.headers().get("ChiselStrikeToken") {
Some(token) => {
let meta = { crate::runtime::get().meta.clone() };
Expand Down
12 changes: 3 additions & 9 deletions server/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ struct PolicyApplyingStream {
}

impl Stream for PolicyApplyingStream {
type Item = anyhow::Result<JsonObject>;
type Item = Result<JsonObject>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
let columns = this.columns.clone();
Expand Down Expand Up @@ -322,19 +322,13 @@ fn sql_backing_store(
Query::Stream(pstream)
}

fn map_stream_item(
columns: &HashSet<String>,
o: anyhow::Result<JsonObject>,
) -> anyhow::Result<JsonObject> {
fn map_stream_item(columns: &HashSet<String>, o: Result<JsonObject>) -> Result<JsonObject> {
let mut o = o?;
o.retain(|k, _| columns.contains(k));
Ok(o)
}

fn filter_stream_item(
o: &anyhow::Result<JsonObject>,
restrictions: &HashMap<String, SqlValue>,
) -> bool {
fn filter_stream_item(o: &Result<JsonObject>, restrictions: &HashMap<String, SqlValue>) -> bool {
let o = match o {
Ok(o) => o,
Err(_) => return true,
Expand Down
2 changes: 1 addition & 1 deletion server/src/deno.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ async fn op_chisel_user(_: Rc<RefCell<OpState>>, _: (), _: ()) -> Result<serde_j
}

// Used by deno to format names in errors
fn op_format_file_name(_: &mut OpState, file_name: String, _: ()) -> anyhow::Result<String> {
fn op_format_file_name(_: &mut OpState, file_name: String, _: ()) -> Result<String> {
Ok(file_name)
}

Expand Down
7 changes: 4 additions & 3 deletions server/src/policies.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: © 2021 ChiselStrike <info@chiselstrike.com>

use crate::prefix_map::PrefixMap;
use anyhow::Result;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::path::Path;
Expand Down Expand Up @@ -57,7 +58,7 @@ impl UserAuthorization {

/// Authorizes users matching a regex to execute any endpoint under this path. Longer paths override existing
/// prefixes. Error if this same path has already been added.
pub fn add(&mut self, path: &str, users: regex::Regex) -> Result<(), anyhow::Error> {
pub fn add(&mut self, path: &str, users: regex::Regex) -> Result<()> {
if self.paths.insert(path.into(), users).is_some() {
anyhow::bail!("Repeated path in user authorization: {:?}", path);
}
Expand All @@ -81,15 +82,15 @@ impl Policies {
&mut self,
version: K,
yaml: Y,
) -> anyhow::Result<()> {
) -> Result<()> {
let v = VersionPolicy::from_yaml(yaml)?;
self.versions.insert(version.to_string(), v);
Ok(())
}
}

impl VersionPolicy {
pub(crate) fn from_yaml<S: AsRef<str>>(config: S) -> anyhow::Result<Self> {
pub(crate) fn from_yaml<S: AsRef<str>>(config: S) -> Result<Self> {
let mut policies = Self::default();
let mut labels = vec![];

Expand Down
7 changes: 4 additions & 3 deletions server/src/query/dbconn.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: © 2021 ChiselStrike <info@chiselstrike.com>
//

use crate::query::QueryError;
use anyhow::Result;
use sea_query::{PostgresQueryBuilder, SchemaBuilder, SqliteQueryBuilder};
use sqlx::any::{AnyConnectOptions, AnyKind, AnyPool, AnyPoolOptions};
use std::str::FromStr;
Expand Down Expand Up @@ -40,7 +41,7 @@ pub(crate) struct DbConnection {
}

impl DbConnection {
pub(crate) async fn connect(uri: &str) -> anyhow::Result<Self> {
pub(crate) async fn connect(uri: &str) -> Result<Self> {
let opts = AnyConnectOptions::from_str(uri).map_err(QueryError::ConnectionFailed)?;
let pool = AnyPoolOptions::new()
.connect(uri)
Expand All @@ -55,7 +56,7 @@ impl DbConnection {
})
}

pub(crate) async fn local_connection(&self) -> anyhow::Result<Self> {
pub(crate) async fn local_connection(&self) -> Result<Self> {
match self.kind {
Kind::Postgres => Self::connect(&self.conn_uri).await,
Kind::Sqlite => Ok(self.clone()),
Expand Down
50 changes: 22 additions & 28 deletions server/src/query/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::db::{sql, sql_restrictions, Relation, Restriction, SqlValue};
use crate::query::{DbConnection, Kind, QueryError};
use crate::types::{Field, ObjectDelta, ObjectType, Type, OAUTHUSER_TYPE_NAME};
use crate::JsonObject;
use anyhow::{anyhow, Context as AnyhowContext};
use anyhow::{anyhow, Context as AnyhowContext, Result};
use futures::stream::BoxStream;
use futures::stream::Stream;
use futures::StreamExt;
Expand All @@ -22,10 +22,10 @@ use std::task::{Context, Poll};
use uuid::Uuid;

// Results directly out of the database
pub(crate) type RawSqlStream = BoxStream<'static, anyhow::Result<AnyRow>>;
pub(crate) type RawSqlStream = BoxStream<'static, Result<AnyRow>>;

// Results with policies applied
pub(crate) type SqlStream = BoxStream<'static, anyhow::Result<JsonObject>>;
pub(crate) type SqlStream = BoxStream<'static, Result<JsonObject>>;

#[pin_project]
struct QueryResults<T> {
Expand All @@ -44,8 +44,8 @@ pub(crate) fn new_query_results(raw_query: String, pool: &AnyPool) -> RawSqlStre
Box::pin(QueryResults { raw_query, stream })
}

impl<T: Stream<Item = anyhow::Result<AnyRow>>> Stream for QueryResults<T> {
type Item = anyhow::Result<AnyRow>;
impl<T: Stream<Item = Result<AnyRow>>> Stream for QueryResults<T> {
type Item = Result<AnyRow>;

fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.project().stream.poll_next(cx)
Expand All @@ -54,7 +54,7 @@ impl<T: Stream<Item = anyhow::Result<AnyRow>>> Stream for QueryResults<T> {

impl TryFrom<&Field> for ColumnDef {
type Error = anyhow::Error;
fn try_from(field: &Field) -> anyhow::Result<Self> {
fn try_from(field: &Field) -> Result<Self> {
let mut column_def = ColumnDef::new(Alias::new(&field.name));
match field.type_ {
Type::String => column_def.text(),
Expand Down Expand Up @@ -144,7 +144,7 @@ impl QueryEngine {
Self { kind, pool }
}

pub(crate) async fn local_connection(conn: &DbConnection) -> anyhow::Result<Self> {
pub(crate) async fn local_connection(conn: &DbConnection) -> Result<Self> {
let local = conn.local_connection().await?;
Ok(Self::new(local.kind, local.pool))
}
Expand All @@ -153,7 +153,7 @@ impl QueryEngine {
&self,
transaction: &mut Transaction<'_, Any>,
ty: &ObjectType,
) -> anyhow::Result<()> {
) -> Result<()> {
let drop_table = Table::drop()
.table(Alias::new(ty.backing_table()))
.to_owned();
Expand All @@ -167,17 +167,15 @@ impl QueryEngine {
Ok(())
}

pub(crate) async fn start_transaction(&self) -> anyhow::Result<Transaction<'_, Any>> {
pub(crate) async fn start_transaction(&self) -> Result<Transaction<'_, Any>> {
Ok(self
.pool
.begin()
.await
.map_err(QueryError::ConnectionFailed)?)
}

pub(crate) async fn commit_transaction(
transaction: Transaction<'_, Any>,
) -> anyhow::Result<()> {
pub(crate) async fn commit_transaction(transaction: Transaction<'_, Any>) -> Result<()> {
transaction
.commit()
.await
Expand All @@ -189,7 +187,7 @@ impl QueryEngine {
&self,
transaction: &mut Transaction<'_, Any>,
ty: &ObjectType,
) -> anyhow::Result<()> {
) -> Result<()> {
let mut create_table = Table::create()
.table(Alias::new(ty.backing_table()))
.if_not_exists()
Expand All @@ -214,7 +212,7 @@ impl QueryEngine {
transaction: &mut Transaction<'_, Any>,
old_ty: &ObjectType,
delta: ObjectDelta,
) -> anyhow::Result<()> {
) -> Result<()> {
// using a macro as async closures are unstable
macro_rules! do_query {
( $table:expr ) => {{
Expand Down Expand Up @@ -291,7 +289,7 @@ impl QueryEngine {
&self,
ty: &ObjectType,
ty_value: &JsonObject,
) -> anyhow::Result<serde_json::Value> {
) -> Result<serde_json::Value> {
let (inserts, id_tree) = self.prepare_insertion(ty, ty_value)?;
self.run_sql_queries(&inserts).await?;
Ok(id_tree.to_json())
Expand All @@ -301,7 +299,7 @@ impl QueryEngine {
&self,
ty: &ObjectType,
restrictions: Vec<Restriction>,
) -> anyhow::Result<()> {
) -> Result<()> {
let sql = format!(
"DELETE FROM {} {}",
&ty.backing_table(),
Expand All @@ -321,17 +319,17 @@ impl QueryEngine {
&self,
ty: &ObjectType,
ty_value: &JsonObject,
) -> anyhow::Result<()> {
) -> Result<()> {
let query = self.prepare_insertion_shallow(ty, ty_value)?;
self.run_sql_queries(&[query]).await?;
Ok(())
}

pub(crate) async fn fetch_one(&self, q: SqlWithArguments) -> anyhow::Result<AnyRow> {
pub(crate) async fn fetch_one(&self, q: SqlWithArguments) -> Result<AnyRow> {
Ok(q.get_sqlx().fetch_one(&self.pool).await?)
}

async fn run_sql_queries(&self, queries: &[SqlWithArguments]) -> anyhow::Result<()> {
async fn run_sql_queries(&self, queries: &[SqlWithArguments]) -> Result<()> {
let mut transaction = self.start_transaction().await?;
for q in queries {
transaction
Expand All @@ -351,7 +349,7 @@ impl QueryEngine {
&self,
ty: &ObjectType,
ty_value: &JsonObject,
) -> anyhow::Result<(Vec<SqlWithArguments>, IdTree)> {
) -> Result<(Vec<SqlWithArguments>, IdTree)> {
let mut child_ids = HashMap::<String, IdTree>::new();
let mut obj_id = Option::<String>::None;
let mut query_args = Vec::<SqlValue>::new();
Expand Down Expand Up @@ -417,11 +415,7 @@ impl QueryEngine {

/// Converts `field` with value `ty_value` into SqlValue while ensuring the
/// generation of default and generable values.
fn convert_to_argument(
&self,
field: &Field,
ty_value: &JsonObject,
) -> anyhow::Result<SqlValue> {
fn convert_to_argument(&self, field: &Field, ty_value: &JsonObject) -> Result<SqlValue> {
macro_rules! parse_default_value {
(str, $value:expr) => {{
$value
Expand Down Expand Up @@ -461,7 +455,7 @@ impl QueryEngine {

/// For given object of type `ty` and its value `ty_value` computes a string
/// representing SQL query which inserts the object into database.
fn make_insert_query(&self, ty: &ObjectType, ty_value: &JsonObject) -> anyhow::Result<String> {
fn make_insert_query(&self, ty: &ObjectType, ty_value: &JsonObject) -> Result<String> {
let mut field_binds = String::new();
let mut field_names = vec![];
let mut id_name = String::new();
Expand Down Expand Up @@ -515,7 +509,7 @@ impl QueryEngine {
&self,
ty: &ObjectType,
ty_value: &JsonObject,
) -> anyhow::Result<SqlWithArguments> {
) -> Result<SqlWithArguments> {
let mut query_args = Vec::<SqlValue>::new();
for field in ty.all_fields() {
let arg = self.convert_to_argument(field, ty_value).with_context(|| {
Expand All @@ -534,7 +528,7 @@ impl QueryEngine {
pub(crate) fn relational_row_to_json(
columns: &[(String, Type)],
row: &AnyRow,
) -> anyhow::Result<JsonObject> {
) -> Result<JsonObject> {
let mut ret = JsonObject::default();
for (query_column, result_column) in zip(columns, row.columns()) {
let i = result_column.ordinal();
Expand Down
10 changes: 5 additions & 5 deletions server/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl GlobalRpcState {
meta: MetaService,
query_engine: QueryEngine,
commands: Vec<CoordinatorChannel>,
) -> anyhow::Result<Self> {
) -> Result<Self> {
let type_system = meta.load_type_system().await?;
let routes = meta.load_endpoints().await?;
let policies = meta.load_policies().await?;
Expand Down Expand Up @@ -98,7 +98,7 @@ impl RpcService {
async fn delete_aux(
&self,
request: Request<ChiselDeleteRequest>,
) -> anyhow::Result<Response<ChiselDeleteResponse>> {
) -> Result<Response<ChiselDeleteResponse>> {
let mut state = self.state.lock().await;
let apply_request = request.into_inner();
let api_version = apply_request.version;
Expand Down Expand Up @@ -159,7 +159,7 @@ impl RpcService {
async fn populate_aux(
&self,
request: Request<PopulateRequest>,
) -> anyhow::Result<Response<PopulateResponse>> {
) -> Result<Response<PopulateResponse>> {
let request = request.into_inner();

let to = request.to_version.clone();
Expand All @@ -182,7 +182,7 @@ impl RpcService {
async fn apply_aux(
&self,
request: Request<ChiselApplyRequest>,
) -> anyhow::Result<Response<ChiselApplyResponse>> {
) -> Result<Response<ChiselApplyResponse>> {
let apply_request = request.into_inner();
let api_version = apply_request.version;
let mut state = self.state.lock().await;
Expand Down Expand Up @@ -531,7 +531,7 @@ pub(crate) fn spawn(
addr: SocketAddr,
start_wait: impl core::future::Future<Output = ()> + Send + 'static,
shutdown: impl core::future::Future<Output = ()> + Send + 'static,
) -> tokio::task::JoinHandle<anyhow::Result<()>> {
) -> tokio::task::JoinHandle<Result<()>> {
tokio::task::spawn(async move {
start_wait.await;

Expand Down
2 changes: 1 addition & 1 deletion server/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl ModulesDirectory {
self.dir.path()
}

pub async fn materialize(&self, path: &str, code: &str) -> anyhow::Result<()> {
pub async fn materialize(&self, path: &str, code: &str) -> Result<()> {
// Path.join() doesn't work when path can be absolute, which it usually is here
// Also has to force .ts here, otherwise /dev/foo.ts becomes /dev/foo endpoints,
// and then later trying /dev/foo/bar clashes and fails
Expand Down

0 comments on commit dd9b7f7

Please sign in to comment.