use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::time::Duration;
use url::Url;
use crate::error::Error;
use crate::http::{Method, StatusCode};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct OperationInfo {
pub service: &'static str,
pub operation: &'static str,
pub resource_type: &'static str,
pub is_mutation: bool,
pub project_id: Option<i64>,
pub resource_id: Option<i64>,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RequestInfo {
pub method: Method,
pub url: Url,
pub attempt: u32,
}
#[derive(Debug)]
#[non_exhaustive]
pub struct RequestResult<'a> {
pub status: Option<StatusCode>,
pub duration: Duration,
pub error: Option<&'a Error>,
pub retry_after: Option<u32>,
}
#[derive(Debug)]
#[non_exhaustive]
pub struct OperationResult<'a> {
pub error: Option<&'a Error>,
pub duration: Duration,
}
pub trait Hooks: Send + Sync {
fn on_operation_start(&self, _info: &OperationInfo) {}
fn on_operation_end(&self, _info: &OperationInfo, _result: &OperationResult<'_>) {}
fn on_request_start(&self, _info: &RequestInfo) {}
fn on_request_end(&self, _info: &RequestInfo, _result: &RequestResult<'_>) {}
fn on_retry(&self, _info: &RequestInfo, _next_attempt: u32, _error: &Error, _delay: Duration) {}
}
impl<H: Hooks + ?Sized> Hooks for Arc<H> {
fn on_operation_start(&self, info: &OperationInfo) {
(**self).on_operation_start(info);
}
fn on_operation_end(&self, info: &OperationInfo, result: &OperationResult<'_>) {
(**self).on_operation_end(info, result);
}
fn on_request_start(&self, info: &RequestInfo) {
(**self).on_request_start(info);
}
fn on_request_end(&self, info: &RequestInfo, result: &RequestResult<'_>) {
(**self).on_request_end(info, result);
}
fn on_retry(&self, info: &RequestInfo, next_attempt: u32, error: &Error, delay: Duration) {
(**self).on_retry(info, next_attempt, error, delay);
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoopHooks;
impl Hooks for NoopHooks {}
pub struct ChainHooks {
hooks: Vec<Arc<dyn Hooks>>,
}
impl ChainHooks {
pub fn new(hooks: Vec<Arc<dyn Hooks>>) -> ChainHooks {
ChainHooks { hooks }
}
}
impl Hooks for ChainHooks {
fn on_operation_start(&self, info: &OperationInfo) {
for hook in &self.hooks {
guarded(|| hook.on_operation_start(info));
}
}
fn on_operation_end(&self, info: &OperationInfo, result: &OperationResult<'_>) {
for hook in self.hooks.iter().rev() {
guarded(|| hook.on_operation_end(info, result));
}
}
fn on_request_start(&self, info: &RequestInfo) {
for hook in &self.hooks {
guarded(|| hook.on_request_start(info));
}
}
fn on_request_end(&self, info: &RequestInfo, result: &RequestResult<'_>) {
for hook in self.hooks.iter().rev() {
guarded(|| hook.on_request_end(info, result));
}
}
fn on_retry(&self, info: &RequestInfo, next_attempt: u32, error: &Error, delay: Duration) {
for hook in &self.hooks {
guarded(|| hook.on_retry(info, next_attempt, error, delay));
}
}
}
pub(crate) fn guarded(call: impl FnOnce()) {
if catch_unwind(AssertUnwindSafe(call)).is_err() {
eprintln!("basecamp-sdk: a hook panicked; the operation continues");
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use super::*;
struct Recorder {
name: &'static str,
log: Arc<Mutex<Vec<String>>>,
}
impl Hooks for Recorder {
fn on_operation_start(&self, info: &OperationInfo) {
self.log
.lock()
.unwrap()
.push(format!("{} start {}", self.name, info.operation));
}
fn on_operation_end(&self, info: &OperationInfo, _result: &OperationResult<'_>) {
self.log
.lock()
.unwrap()
.push(format!("{} end {}", self.name, info.operation));
}
}
struct Panicking;
impl Hooks for Panicking {
fn on_operation_start(&self, _info: &OperationInfo) {
panic!("boom");
}
}
fn info() -> OperationInfo {
OperationInfo {
service: "Projects",
operation: "ListProjects",
resource_type: "project",
is_mutation: false,
project_id: None,
resource_id: None,
}
}
#[test]
fn a_chain_runs_forwards_and_unwinds_backwards_and_survives_a_panic() {
let log = Arc::new(Mutex::new(Vec::new()));
let chain = ChainHooks::new(vec![
Arc::new(Recorder {
name: "first",
log: log.clone(),
}),
Arc::new(Panicking),
Arc::new(Recorder {
name: "second",
log: log.clone(),
}),
]);
chain.on_operation_start(&info());
chain.on_operation_end(
&info(),
&OperationResult {
error: None,
duration: Duration::from_millis(1),
},
);
assert_eq!(
*log.lock().unwrap(),
[
"first start ListProjects",
"second start ListProjects",
"second end ListProjects",
"first end ListProjects"
]
);
}
}