Skip to content

Instantly share code, notes, and snippets.

@tazjin
Created May 10, 2018 14:51
Show Gist options
  • Save tazjin/b8a7531b34f2408babd64cc0b9556b00 to your computer and use it in GitHub Desktop.
Save tazjin/b8a7531b34f2408babd64cc0b9556b00 to your computer and use it in GitHub Desktop.
Storing Rust crius circuit breakers in structs
extern crate crius;
use crius::command::{RunnableCommand, Command, CommandError};
/// Convenience type alias for breaker function pointers.
pub type BreakerFn<I, O> = fn(I) -> Result<O, Box<CommandError>>;
/// Convenience type alias for working with crius commands:
pub type Breaker<I, O> =
RunnableCommand<I, O,
BreakerFn<I,O>,
fn(Box<CommandError>) -> O>;
/// Helper function for creating a breaker and preventing rustc from
/// inferring a closure type instead of a function pointer without
/// extra type annotations.
pub fn create_breaker<I, O>(f: BreakerFn<I, O>) -> Breaker<I, O> where
I: Send,
O: Send {
Command::define(f).create()
}
/// Test struct capable that stores an example circuit breaker.
pub struct BreakerOwner {
pub breaker: Breaker<u8, String>,
}
pub fn make_breaker_owner() -> BreakerOwner {
BreakerOwner {
breaker: create_breaker(|num| Ok(format!("Number is {}", num)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_breaker_struct() {
let mut b = make_breaker_owner();
let res = b.breaker.run(10).recv()
.expect("Channel failed")
.expect("Breaker command failed");
assert_eq!(res, "Number is 10")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment