-
Notifications
You must be signed in to change notification settings - Fork 233
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Updating the async API client example
Added some code to show how you can run blocking Rust code inside a foreign task queue.
- Loading branch information
Showing
8 changed files
with
305 additions
and
132 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
/* This Source Code Form is subject to the terms of the Mozilla Public | ||
* License, v. 2.0. If a copy of the MPL was not distributed with this | ||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
||
use crate::{run_task, ApiError, Result, TaskRunner}; | ||
use std::sync::Arc; | ||
|
||
#[async_trait::async_trait] | ||
pub trait HttpClient: Send + Sync { | ||
async fn fetch(&self, url: String, credentials: String) -> Result<String>; | ||
} | ||
|
||
impl From<serde_json::Error> for ApiError { | ||
fn from(e: serde_json::Error) -> Self { | ||
Self::Json { | ||
reason: e.to_string(), | ||
} | ||
} | ||
} | ||
|
||
#[derive(Debug, serde::Deserialize)] | ||
pub struct Issue { | ||
pub url: String, | ||
pub title: String, | ||
pub state: IssueState, | ||
} | ||
|
||
#[derive(Debug, serde::Deserialize)] | ||
pub enum IssueState { | ||
#[serde(rename = "open")] | ||
Open, | ||
#[serde(rename = "closed")] | ||
Closed, | ||
} | ||
|
||
pub struct ApiClient { | ||
http_client: Arc<dyn HttpClient>, | ||
task_runner: Arc<dyn TaskRunner>, | ||
} | ||
|
||
impl ApiClient { | ||
// Pretend this is a blocking call that needs to load the credentials from disk/network | ||
fn load_credentials_sync(&self) -> String { | ||
String::from("username:password") | ||
} | ||
|
||
async fn load_credentials(self: Arc<Self>) -> String { | ||
let self_cloned = Arc::clone(&self); | ||
run_task(&self.task_runner, move || { | ||
self_cloned.load_credentials_sync() | ||
}) | ||
.await | ||
} | ||
} | ||
|
||
impl ApiClient { | ||
pub fn new(http_client: Arc<dyn HttpClient>, task_runner: Arc<dyn TaskRunner>) -> Self { | ||
Self { | ||
http_client, | ||
task_runner, | ||
} | ||
} | ||
|
||
pub async fn get_issue( | ||
self: Arc<Self>, | ||
owner: String, | ||
repository: String, | ||
issue_number: u32, | ||
) -> Result<Issue> { | ||
let credentials = self.clone().load_credentials().await; | ||
let url = | ||
format!("https://api.github.com/repos/{owner}/{repository}/issues/{issue_number}"); | ||
let body = self.http_client.fetch(url, credentials).await?; | ||
Ok(serde_json::from_str(&body)?) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
/* This Source Code Form is subject to the terms of the Mozilla Public | ||
* License, v. 2.0. If a copy of the MPL was not distributed with this | ||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
||
use std::sync::{Arc, Mutex}; | ||
|
||
#[async_trait::async_trait] | ||
pub trait TaskRunner: Send + Sync { | ||
async fn run_task(&self, task: Arc<dyn RustTask>); | ||
} | ||
|
||
pub trait RustTask: Send + Sync { | ||
fn execute(&self); | ||
} | ||
|
||
pub async fn run_task<F, T>(runner: &Arc<dyn TaskRunner>, closure: F) -> T | ||
where | ||
F: FnOnce() -> T + Send + Sync + 'static, | ||
T: Send + 'static, | ||
{ | ||
let closure = Arc::new(TaskClosure::new(closure)); | ||
runner | ||
.run_task(Arc::clone(&closure) as Arc<dyn RustTask>) | ||
.await; | ||
closure.into_result() | ||
} | ||
|
||
struct TaskClosure<F, T> | ||
where | ||
F: FnOnce() -> T + Send + Sync, | ||
T: Send, | ||
{ | ||
inner: Mutex<TaskClosureInner<F, T>>, | ||
} | ||
|
||
enum TaskClosureInner<F, T> | ||
where | ||
F: FnOnce() -> T + Send + Sync, | ||
T: Send, | ||
{ | ||
Pending(F), | ||
Running, | ||
Complete(T), | ||
Finished, | ||
} | ||
|
||
impl<F, T> TaskClosure<F, T> | ||
where | ||
F: FnOnce() -> T + Send + Sync, | ||
T: Send, | ||
{ | ||
fn new(closure: F) -> Self { | ||
Self { | ||
inner: Mutex::new(TaskClosureInner::Pending(closure)), | ||
} | ||
} | ||
|
||
fn into_result(&self) -> T { | ||
let mut inner = self.inner.lock().unwrap(); | ||
match *inner { | ||
TaskClosureInner::Pending(_) => panic!("Task never ran"), | ||
TaskClosureInner::Running => panic!("Task still running"), | ||
TaskClosureInner::Finished => panic!("Task already finished"), | ||
TaskClosureInner::Complete(_) => (), | ||
}; | ||
match std::mem::replace(&mut *inner, TaskClosureInner::Finished) { | ||
TaskClosureInner::Complete(v) => v, | ||
_ => unreachable!(), | ||
} | ||
} | ||
} | ||
|
||
impl<F, T> RustTask for TaskClosure<F, T> | ||
where | ||
F: FnOnce() -> T + Send + Sync, | ||
T: Send, | ||
{ | ||
fn execute(&self) { | ||
let mut inner = self.inner.lock().unwrap(); | ||
match std::mem::replace(&mut *inner, TaskClosureInner::Running) { | ||
TaskClosureInner::Pending(f) => { | ||
let result = f(); | ||
*inner = TaskClosureInner::Complete(result) | ||
} | ||
TaskClosureInner::Running => panic!("Task already started"), | ||
TaskClosureInner::Complete(_) => panic!("Task already executed"), | ||
TaskClosureInner::Finished => panic!("Task already finished"), | ||
} | ||
} | ||
} |
Oops, something went wrong.