1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
//! This crate provides functionalities to //! define [trackable](trait.Trackable.html) objects and track those. //! //! Below is an example that tracks failure of an I/O operation: //! //! ```no_run //! #[macro_use] //! extern crate trackable; //! //! use trackable::error::{Failed, Failure, ErrorKindExt}; //! //! fn foo() -> Result<(), Failure> { //! track_try!(std::fs::File::open("/path/to/non_existent_file") //! .map_err(|e| Failed.cause(e))); //! Ok(()) //! } //! fn bar() -> Result<(), Failure> { //! track_try!(foo()); //! Ok(()) //! } //! fn baz() -> Result<(), Failure> { //! track_try!(bar()); //! Ok(()) //! } //! //! fn main() { //! let result = baz(); //! assert!(result.is_err()); //! //! let error = result.err().unwrap(); //! assert_eq!(format!("\r{}", error), r#" //! Failed (cause; No such file or directory) //! HISTORY: //! [0] at <anon>:7 //! [1] at <anon>:12 //! [2] at <anon>:16 //! "#); //! } //! ``` //! //! This example used the built-in `Failure` type, //! but you can easily define your own trackable error types. //! See the documentaion of [error](error/index.html) module for more details. #![warn(missing_docs)] extern crate rand; use std::fmt; pub mod error; mod macros; /// This trait allows to track an instance of an implementation type. /// /// A trackable instance has following three properties: /// /// 1. **Tracking history**: /// - It manages own backtrace-like (but more general) /// [history](struct.History.html) for tracking. /// - You can add entries to the history by calling tracking macros /// (e.g., [track!](macro.track.html), [track_try!](macro.track_try.html)). /// 2. **Tracking mode**: /// - You can enable (resp. disable) tracking by calling /// `enable_tracking` (resp. `disable_tracking`) method of this trait. /// - If some instances of a type are not needed to be trackable (e.g., non critical errors), /// it may be useful to disable tracking of those for reducing runtime overhead. /// 3. **Tracking number**: /// - It is possible to assign a randomly generated [tracking number](struct.TrackingNumber.html) /// to a `Trackable` instance by calling `assign_tracking_number` method. /// /// See [TrackableError](error/struct.TrackableError.html) as a typical implementaion of this trait. /// /// # Examples /// /// Defines a trackable type. /// /// ``` /// #[macro_use] /// extern crate trackable; /// /// use trackable::{Trackable, History, Location, TrackingNumber}; /// /// #[derive(Default)] /// struct TrackableObject { /// history: Option<History<Location>>, /// tracking_number: Option<TrackingNumber>, /// } /// impl Trackable for TrackableObject { /// type Event = Location; /// fn assign_tracking_number(&mut self) { /// if self.tracking_number.is_none() { /// self.tracking_number = Some(TrackingNumber::generate()); /// } /// } /// fn tracking_number(&self) -> Option<TrackingNumber> { /// self.tracking_number /// } /// fn enable_tracking(mut self) -> Self where Self: Sized { /// if self.history.is_none() { /// self.history = Some(History::new()); /// } /// self /// } /// fn disable_tracking(mut self) -> Self where Self: Sized { /// self.history = None; /// self /// } /// fn history(&self) -> Option<&History<Self::Event>> { /// self.history.as_ref() /// } /// fn history_mut(&mut self) -> Option<&mut History<Self::Event>> { /// self.history.as_mut() /// } /// } /// /// fn main() { /// let o = TrackableObject::default(); /// let o = track!(o); // Ignored /// /// let o = o.enable_tracking(); /// let o = track!(o); /// let o = track!(o, "Hello"); /// let o = track!(o, "Hello {}", "World!"); /// /// assert_eq!(format!("\n{}", o.history().unwrap()), r#" /// HISTORY: /// [0] at <anon>:44 /// [1] at <anon>:45; Hello /// [2] at <anon>:46; Hello World! /// "#); /// } /// ``` pub trait Trackable { /// Event type which a history of an instance of this type can have. type Event: From<Location>; /// Add an event into the tail of the history of this instance. /// /// Typically, this is called via [track!](macro.track.html) macro. fn track<F>(&mut self, f: F) where F: FnOnce() -> Self::Event { self.history_mut().map(|h| h.add(f())); } /// Assigns a randomly generated [tracking number](struct.TrackingNumber.html) to this instance. /// /// Note that implementations must simply ignore the second and subsequent calls of this method. fn assign_tracking_number(&mut self); /// Returns the tracking number of this instance if it has been assigned. fn tracking_number(&self) -> Option<TrackingNumber>; /// Returns `true` if tracking of this instance is enabled, otherwise `false`. fn in_tracking(&self) -> bool { self.history().is_some() } /// Enables tracking of this instance. fn enable_tracking(self) -> Self where Self: Sized; /// Disables tracking of this intance. fn disable_tracking(self) -> Self where Self: Sized; /// Returns the reference of the tracking history of this instance. fn history(&self) -> Option<&History<Self::Event>>; /// Returns the mutable reference of the tracking history of this instance. fn history_mut(&mut self) -> Option<&mut History<Self::Event>>; } impl<T: Trackable> Trackable for Option<T> { type Event = T::Event; fn assign_tracking_number(&mut self) { self.as_mut().map(|t| t.assign_tracking_number()); } fn tracking_number(&self) -> Option<TrackingNumber> { self.as_ref().and_then(|t| t.tracking_number()) } fn enable_tracking(self) -> Self where Self: Sized { self.map(|t| t.enable_tracking()) } fn disable_tracking(self) -> Self where Self: Sized { self.map(|t| t.disable_tracking()) } fn history(&self) -> Option<&History<Self::Event>> { self.as_ref().and_then(|t| t.history()) } fn history_mut(&mut self) -> Option<&mut History<Self::Event>> { self.as_mut().and_then(|t| t.history_mut()) } } impl<T, E: Trackable> Trackable for Result<T, E> { type Event = E::Event; fn assign_tracking_number(&mut self) { self.as_mut().err().map(|t| t.assign_tracking_number()); } fn tracking_number(&self) -> Option<TrackingNumber> { self.as_ref().err().and_then(|t| t.tracking_number()) } fn enable_tracking(self) -> Self where Self: Sized { self.map_err(|t| t.enable_tracking()) } fn disable_tracking(self) -> Self where Self: Sized { self.map_err(|t| t.disable_tracking()) } fn history(&self) -> Option<&History<Self::Event>> { self.as_ref().err().and_then(|t| t.history()) } fn history_mut(&mut self) -> Option<&mut History<Self::Event>> { self.as_mut().err().and_then(|t| t.history_mut()) } } /// The tracking history of a target. /// /// A history is a sequence of the tracked events. /// /// # Examples /// /// ``` /// use std::fmt::{Display, Formatter, Result}; /// use trackable::History; /// /// struct Event(&'static str); /// impl Display for Event { /// fn fmt(&self, f: &mut Formatter) -> Result { /// write!(f, "event: {}", self.0) /// } /// } /// /// let mut history = History::new(); /// history.add(Event("foo")); /// history.add(Event("bar")); /// /// assert_eq!(format!("\n{}", history), r#" /// HISTORY: /// [0] event: foo /// [1] event: bar /// "#); /// ``` #[derive(Debug, Clone)] pub struct History<Event>(Vec<Event>); impl<Event> History<Event> { /// Makes an empty history. pub fn new() -> Self { History(Vec::new()) } /// Adds an event to the tail of this history. pub fn add(&mut self, event: Event) { self.0.push(event); } /// Returns the tracked events in this history. pub fn events(&self) -> &[Event] { &self.0[..] } } impl<Event: fmt::Display> fmt::Display for History<Event> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "HISTORY:")?; for (i, e) in self.events().iter().enumerate() { writeln!(f, " [{}] {}", i, e)?; } Ok(()) } } /// The location of interest in source code files. /// /// Typically this is created in the macros which defined in this crate. #[derive(Debug, Clone)] pub struct Location { module_path: &'static str, file: &'static str, line: u32, message: String, } impl Location { /// Makes a new `Location` instance. /// /// # Examples /// /// ``` /// use trackable::Location; /// /// let location = Location::new(module_path!(), file!(), line!(), "Hello".to_string()); /// assert_eq!(location.message(), "Hello"); /// ``` pub fn new(module_path: &'static str, file: &'static str, line: u32, message: String) -> Self { Location { module_path: module_path, file: file, line: line, message: message, } } /// Gets the crate name of this location. pub fn crate_name(&self) -> &'static str { if let Some(end) = self.module_path.find(":") { &self.module_path[..end] } else { self.module_path } } /// Gets the module path of this location. pub fn module_path(&self) -> &'static str { self.module_path } /// Gets the file name of this location. pub fn file(&self) -> &'static str { self.file } /// Gets the line of this location. pub fn line(&self) -> u32 { self.line } /// Gets the message left at this location. pub fn message(&self) -> &str { &self.message } } impl fmt::Display for Location { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "at {}:{}", self.file(), self.line())?; if !self.message().is_empty() { write!(f, "; {}", self.message())?; } Ok(()) } } /// Randomly generated tracking number. /// /// This is provided to help identifying a tracking target object. /// /// Note that the numbers are generated by `rand::random()` function, /// thus it is not guaranteed to have strict uniqueness. /// /// # Examples /// /// ```no_run /// use trackable::TrackingNumber; /// /// let n0 = TrackingNumber::generate(); /// let n1 = TrackingNumber::generate(); /// /// // NOTE: The actual values will change every time the below code is executed. /// assert_ne!(n0, n1); /// assert_eq!(n0.to_string(), "91fe3f35b6022840"); /// assert_eq!(n1.to_string(), "3d1a76ec17fb838f"); /// ``` #[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct TrackingNumber(pub u64); impl TrackingNumber { /// Generates a new tracking number. pub fn generate() -> Self { TrackingNumber(rand::random()) } } impl fmt::Display for TrackingNumber { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:08x}", self.0) } }