neo3 1.1.1

Production-ready Rust SDK for Neo N3 blockchain with high-level API, unified error handling, and enterprise features
Documentation
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use crate::neo_error::{Neo3Error, Neo3Result};
use std::{
	sync::{
		atomic::{AtomicU32, Ordering},
		Arc,
	},
	time::{Duration, Instant},
};
use tokio::sync::RwLock;

/// Circuit breaker states
#[derive(Debug, Clone, PartialEq, Default)]
pub enum CircuitState {
	/// Circuit is closed, requests flow normally
	#[default]
	Closed,
	/// Circuit is open, requests are rejected immediately
	Open,
	/// Circuit is half-open, testing if service has recovered
	HalfOpen,
}

/// Circuit breaker configuration
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CircuitBreakerConfig {
	/// Number of failures before opening the circuit
	pub failure_threshold: u32,
	/// Time to wait before transitioning from Open to HalfOpen
	pub timeout: Duration,
	/// Number of successful requests needed to close the circuit from HalfOpen
	pub success_threshold: u32,
	/// Time window for counting failures
	pub failure_window: Duration,
	/// Maximum number of requests allowed in HalfOpen state
	pub half_open_max_requests: u32,
}

impl CircuitBreakerConfig {
	/// Creates a new builder for the configuration
	pub fn builder() -> CircuitBreakerConfigBuilder {
		CircuitBreakerConfigBuilder::default()
	}
}

/// Builder for `CircuitBreakerConfig`
#[derive(Debug, Default, Clone)]
pub struct CircuitBreakerConfigBuilder {
	failure_threshold: Option<u32>,
	timeout: Option<Duration>,
	success_threshold: Option<u32>,
	failure_window: Option<Duration>,
	half_open_max_requests: Option<u32>,
}

impl CircuitBreakerConfigBuilder {
	/// Sets the failure threshold
	pub fn failure_threshold(mut self, val: u32) -> Self {
		self.failure_threshold = Some(val);
		self
	}

	/// Sets the timeout
	pub fn timeout(mut self, val: Duration) -> Self {
		self.timeout = Some(val);
		self
	}

	/// Sets the success threshold
	pub fn success_threshold(mut self, val: u32) -> Self {
		self.success_threshold = Some(val);
		self
	}

	/// Sets the failure window
	pub fn failure_window(mut self, val: Duration) -> Self {
		self.failure_window = Some(val);
		self
	}

	/// Sets the maximum number of requests allowed in HalfOpen state
	pub fn half_open_max_requests(mut self, val: u32) -> Self {
		self.half_open_max_requests = Some(val);
		self
	}

	/// Builds the `CircuitBreakerConfig`
	pub fn build(self) -> CircuitBreakerConfig {
		let default = CircuitBreakerConfig::default();
		CircuitBreakerConfig {
			failure_threshold: self.failure_threshold.unwrap_or(default.failure_threshold),
			timeout: self.timeout.unwrap_or(default.timeout),
			success_threshold: self.success_threshold.unwrap_or(default.success_threshold),
			failure_window: self.failure_window.unwrap_or(default.failure_window),
			half_open_max_requests: self
				.half_open_max_requests
				.unwrap_or(default.half_open_max_requests),
		}
	}
}

impl Default for CircuitBreakerConfig {
	fn default() -> Self {
		Self {
			failure_threshold: 5,
			timeout: Duration::from_secs(60),
			success_threshold: 3,
			failure_window: Duration::from_secs(60),
			half_open_max_requests: 3,
		}
	}
}

/// Circuit breaker statistics
#[derive(Debug, Default)]
pub struct CircuitBreakerStats {
	pub total_requests: u64,
	pub successful_requests: u64,
	pub failed_requests: u64,
	pub rejected_requests: u64,
	pub state_transitions: u64,
	pub current_state: CircuitState,
	pub last_failure_time: Option<Instant>,
	pub last_success_time: Option<Instant>,
}

/// Circuit breaker implementation for protecting against cascading failures
pub struct CircuitBreaker {
	config: CircuitBreakerConfig,
	state: Arc<RwLock<CircuitState>>,
	failure_count: AtomicU32,
	success_count: AtomicU32,
	half_open_requests: AtomicU32,
	last_failure_time: Arc<RwLock<Option<Instant>>>,
	last_success_time: Arc<RwLock<Option<Instant>>>,
	stats: Arc<RwLock<CircuitBreakerStats>>,
}

impl CircuitBreaker {
	/// Create a new circuit breaker with the given configuration
	pub fn new(config: CircuitBreakerConfig) -> Self {
		Self {
			config,
			state: Arc::new(RwLock::new(CircuitState::Closed)),
			failure_count: AtomicU32::new(0),
			success_count: AtomicU32::new(0),
			half_open_requests: AtomicU32::new(0),
			last_failure_time: Arc::new(RwLock::new(None)),
			last_success_time: Arc::new(RwLock::new(None)),
			stats: Arc::new(RwLock::new(CircuitBreakerStats::default())),
		}
	}

	/// Execute a request through the circuit breaker
	pub async fn call<F, T>(&self, operation: F) -> Neo3Result<T>
	where
		F: std::future::Future<Output = Neo3Result<T>>,
	{
		// Update total requests
		{
			let mut stats = self.stats.write().await;
			stats.total_requests += 1;
		}

		// Check if we should allow the request
		if !self.should_allow_request().await {
			let mut stats = self.stats.write().await;
			stats.rejected_requests += 1;
			return Err(Neo3Error::Network(crate::neo_error::NetworkError::RateLimitExceeded));
		}

		// Execute the operation
		match operation.await {
			Ok(result) => {
				self.on_success().await;
				Ok(result)
			},
			Err(error) => {
				self.on_failure().await;
				Err(error)
			},
		}
	}

	/// Check if a request should be allowed based on current state
	async fn should_allow_request(&self) -> bool {
		let state = self.state.read().await;
		match *state {
			CircuitState::Closed => true,
			CircuitState::Open => {
				// Check if timeout has elapsed
				if let Some(last_failure) = *self.last_failure_time.read().await {
					if last_failure.elapsed() >= self.config.timeout {
						drop(state);
						self.transition_to_half_open().await;
						true
					} else {
						false
					}
				} else {
					false
				}
			},
			CircuitState::HalfOpen => {
				// Allow limited requests in half-open state
				let current_requests = self.half_open_requests.load(Ordering::Relaxed);
				current_requests < self.config.half_open_max_requests
			},
		}
	}

	/// Handle successful request
	async fn on_success(&self) {
		let mut stats = self.stats.write().await;
		stats.successful_requests += 1;
		stats.last_success_time = Some(Instant::now());
		drop(stats);

		*self.last_success_time.write().await = Some(Instant::now());

		let state = self.state.read().await;
		match *state {
			CircuitState::Closed => {
				// Reset failure count on success
				self.failure_count.store(0, Ordering::Relaxed);
			},
			CircuitState::HalfOpen => {
				let success_count = self.success_count.fetch_add(1, Ordering::Relaxed) + 1;
				if success_count >= self.config.success_threshold {
					drop(state);
					self.transition_to_closed().await;
				}
			},
			CircuitState::Open => {
				// This shouldn't happen, but reset if it does
				drop(state);
				self.transition_to_closed().await;
			},
		}
	}

	/// Handle failed request
	async fn on_failure(&self) {
		let mut stats = self.stats.write().await;
		stats.failed_requests += 1;
		stats.last_failure_time = Some(Instant::now());
		drop(stats);

		*self.last_failure_time.write().await = Some(Instant::now());

		let state = self.state.read().await;
		match *state {
			CircuitState::Closed => {
				let failure_count = self.failure_count.fetch_add(1, Ordering::Relaxed) + 1;
				if failure_count >= self.config.failure_threshold {
					drop(state);
					self.transition_to_open().await;
				}
			},
			CircuitState::HalfOpen => {
				// Any failure in half-open state transitions back to open
				drop(state);
				self.transition_to_open().await;
			},
			CircuitState::Open => {
				// Already open, nothing to do
			},
		}
	}

	/// Transition to closed state
	async fn transition_to_closed(&self) {
		let mut state = self.state.write().await;
		if *state != CircuitState::Closed {
			*state = CircuitState::Closed;
			self.failure_count.store(0, Ordering::Relaxed);
			self.success_count.store(0, Ordering::Relaxed);
			self.half_open_requests.store(0, Ordering::Relaxed);

			let mut stats = self.stats.write().await;
			stats.state_transitions += 1;
			stats.current_state = CircuitState::Closed;
		}
	}

	/// Transition to open state
	async fn transition_to_open(&self) {
		let mut state = self.state.write().await;
		if *state != CircuitState::Open {
			*state = CircuitState::Open;
			self.success_count.store(0, Ordering::Relaxed);
			self.half_open_requests.store(0, Ordering::Relaxed);

			let mut stats = self.stats.write().await;
			stats.state_transitions += 1;
			stats.current_state = CircuitState::Open;
		}
	}

	/// Transition to half-open state
	async fn transition_to_half_open(&self) {
		let mut state = self.state.write().await;
		if *state != CircuitState::HalfOpen {
			*state = CircuitState::HalfOpen;
			self.success_count.store(0, Ordering::Relaxed);
			self.half_open_requests.store(0, Ordering::Relaxed);

			let mut stats = self.stats.write().await;
			stats.state_transitions += 1;
			stats.current_state = CircuitState::HalfOpen;
		}
	}

	/// Get current circuit breaker state
	pub async fn get_state(&self) -> CircuitState {
		let state = self.state.read().await;
		state.clone()
	}

	/// Get circuit breaker statistics
	pub async fn get_stats(&self) -> CircuitBreakerStats {
		let stats = self.stats.read().await;
		CircuitBreakerStats {
			total_requests: stats.total_requests,
			successful_requests: stats.successful_requests,
			failed_requests: stats.failed_requests,
			rejected_requests: stats.rejected_requests,
			state_transitions: stats.state_transitions,
			current_state: stats.current_state.clone(),
			last_failure_time: stats.last_failure_time,
			last_success_time: stats.last_success_time,
		}
	}

	/// Reset the circuit breaker to closed state
	pub async fn reset(&self) {
		self.transition_to_closed().await;
		*self.last_failure_time.write().await = None;
		*self.last_success_time.write().await = None;

		let mut stats = self.stats.write().await;
		*stats = CircuitBreakerStats::default();
	}

	/// Force the circuit breaker to open state
	pub async fn force_open(&self) {
		self.transition_to_open().await;
	}

	/// Get failure rate (failures / total requests)
	pub async fn get_failure_rate(&self) -> f64 {
		let stats = self.stats.read().await;
		if stats.total_requests == 0 {
			0.0
		} else {
			stats.failed_requests as f64 / stats.total_requests as f64
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use tokio::time::{sleep, Duration};

	#[tokio::test]
	async fn test_circuit_breaker_closed_state() {
		let config = CircuitBreakerConfig { failure_threshold: 3, ..Default::default() };
		let cb = CircuitBreaker::new(config);

		// Successful requests should keep circuit closed
		for _ in 0..5 {
			let result = cb.call(async { Ok::<(), Neo3Error>(()) }).await;
			assert!(result.is_ok());
		}

		assert_eq!(cb.get_state().await, CircuitState::Closed);
	}

	#[tokio::test]
	async fn test_circuit_breaker_opens_on_failures() {
		let config = CircuitBreakerConfig { failure_threshold: 3, ..Default::default() };
		let cb = CircuitBreaker::new(config);

		// Generate failures to open circuit
		for _ in 0..3 {
			let result = cb
				.call(async {
					Err::<(), Neo3Error>(Neo3Error::Network(
						crate::neo_error::NetworkError::ConnectionFailed("test".to_string()),
					))
				})
				.await;
			assert!(result.is_err());
		}

		assert_eq!(cb.get_state().await, CircuitState::Open);
	}

	#[tokio::test]
	async fn test_circuit_breaker_half_open_transition() {
		let config = CircuitBreakerConfig {
			failure_threshold: 2,
			timeout: Duration::from_millis(100),
			..Default::default()
		};
		let cb = CircuitBreaker::new(config);

		// Open the circuit
		for _ in 0..2 {
			let _ = cb
				.call(async {
					Err::<(), Neo3Error>(Neo3Error::Network(
						crate::neo_error::NetworkError::ConnectionFailed("test".to_string()),
					))
				})
				.await;
		}
		assert_eq!(cb.get_state().await, CircuitState::Open);

		// Wait for timeout
		sleep(Duration::from_millis(150)).await;

		// Next request should transition to half-open
		let result = cb.call(async { Ok::<(), Neo3Error>(()) }).await;
		assert!(result.is_ok());
		assert_eq!(cb.get_state().await, CircuitState::HalfOpen);
	}

	#[tokio::test]
	async fn test_circuit_breaker_stats() {
		let cb = CircuitBreaker::new(CircuitBreakerConfig::default());

		// Make some requests
		let _ = cb.call(async { Ok::<(), Neo3Error>(()) }).await;
		let _ = cb
			.call(async {
				Err::<(), Neo3Error>(Neo3Error::Network(
					crate::neo_error::NetworkError::ConnectionFailed("test".to_string()),
				))
			})
			.await;

		let stats = cb.get_stats().await;
		assert_eq!(stats.total_requests, 2);
		assert_eq!(stats.successful_requests, 1);
		assert_eq!(stats.failed_requests, 1);
	}
}