Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

has_response marks webhook as returning a response. #15

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ pub struct Command {

#[serde(default = "default_stdin")]
stdin: Stdin,
#[serde(default = "default_has_response")]
has_response: bool,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -177,6 +179,10 @@ fn default_stdin() -> Stdin {
Stdin::Nothing
}

fn default_has_response() -> bool {
false
}

impl<'de> Deserialize<'de> for MaybeBound {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down Expand Up @@ -224,6 +230,10 @@ impl Command {
pub fn wants_request_body(&self) -> bool {
self.stdin == Stdin::RequestBody
}

pub fn has_response(&self) -> bool {
self.has_response
}
}

impl CommandArgs {
Expand Down
58 changes: 39 additions & 19 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use logging::LogLevel;
use tokio::net::TcpListener;
use tokio::sync::{oneshot, watch};
use tokio_stream::StreamExt;
use tokio::io::AsyncReadExt;

mod config;
mod logging;
Expand Down Expand Up @@ -228,10 +229,18 @@ impl HookScheduler {
let hook = self.hook.clone();
Box::pin(async move {
for cmd in &hook.commands {
if let Err(()) = run_command(cmd, &hook, &request, &body, remote_addr).await {
// Ignore errors: other end of channel was dropped, nobody cares about our response anymore.
done_tx.send(generic_error()).unwrap_or(());
return;
match run_command(cmd, &hook, &request, &body, remote_addr).await {
Ok(x) => {
if cmd.has_response() {
done_tx.send(simple_response(StatusCode::OK, x)).unwrap_or(());
return;
}
},
Err(_)=> {
// Ignore errors: other end of channel was dropped, nobody cares about our response anymore.
done_tx.send(generic_error()).unwrap_or(());
return;
}
}
}
// Ignore errors: other end of channel was dropped, nobody cares about our response anymore.
Expand Down Expand Up @@ -284,7 +293,7 @@ async fn handle_request(hooks: &BTreeMap<String, HookScheduler>, mut request: Re
Ok(hook.post(request, body, remote_addr).await)
}

async fn run_command(cmd: &config::Command, hook: &Hook, request: &Request, body: &[u8], remote_addr: SocketAddr) -> Result<(), ()> {
async fn run_command(cmd: &config::Command, hook: &Hook, request: &Request, body: &[u8], remote_addr: SocketAddr) -> Result<Vec<u8>, ()> {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio_stream::wrappers::LinesStream;

Expand Down Expand Up @@ -320,27 +329,38 @@ async fn run_command(cmd: &config::Command, hook: &Hook, request: &Request, body
.map_err(|e| log::error!("{}: failed to write request body to stdin of command {:?}: {}", hook.url, cmd.cmd(), e))?;
}

let stdout = LinesStream::new(BufReader::new(subprocess.stdout.take().unwrap()).lines());
let stderr = LinesStream::new(BufReader::new(subprocess.stderr.take().unwrap()).lines());
let mut output = stdout.merge(stderr);

while let Some(line) = output.next().await {
let line = match line {
Ok(x) => x,
Err(e) => {
log::error!("{}: failed to read command {:?} output: {}", hook.url, cmd.cmd(), e);
break;
},
};
log::info!("{}: {}: {}", hook.url, cmd.cmd(), line);
let mut stdout = Vec::new();
if cmd.has_response() {
if let Some(mut stdout_pipe) = subprocess.stdout.take() {
// Use AsyncReadExt to read data into the stdout buffer
stdout_pipe
.read_to_end(&mut stdout)
.await
.map_err(|e| log::error!("{}: failed to read command {:?} stdout: {}", hook.url, cmd.cmd(), e))?;
}
} else {
let stdout = LinesStream::new(BufReader::new(subprocess.stdout.take().unwrap()).lines());
let stderr = LinesStream::new(BufReader::new(subprocess.stderr.take().unwrap()).lines());
let mut output = stdout.merge(stderr);

while let Some(line) = output.next().await {
let line = match line {
Ok(x) => x,
Err(e) => {
log::error!("{}: failed to read command {:?} output: {}", hook.url, cmd.cmd(), e);
break;
},
};
log::info!("{}: {}: {}", hook.url, cmd.cmd(), line);
}
}

let status = subprocess
.wait()
.await
.map_err(|e| log::error!("{}: failed to wait for command {:?}: {}", hook.url, cmd.cmd(), e))?;
if status.success() {
Ok(())
Ok(stdout)
} else {
log::error!("{}: command {:?} exitted with {}", hook.url, cmd.cmd(), status);
Err(())
Expand Down