reinhardt-views 0.1.2

View layer aggregator for viewsets and views-core
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Batch operations support for ViewSets
//!
//! Provides functionality for performing multiple operations in a single request:
//! - Batch create (create multiple resources at once)
//! - Batch update (update multiple resources at once)
//! - Batch delete (delete multiple resources at once)
//! - Batch partial update (partial update of multiple resources)

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Batch operation request
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "operation")]
pub enum BatchOperation<T> {
	/// Create operation
	#[serde(rename = "create")]
	Create {
		/// Data for the new resource.
		data: T,
	},
	/// Update operation (full update)
	#[serde(rename = "update")]
	Update {
		/// Identifier of the resource to update.
		id: String,
		/// Complete replacement data.
		data: T,
	},
	/// Partial update operation
	#[serde(rename = "partial_update")]
	PartialUpdate {
		/// Identifier of the resource to partially update.
		id: String,
		/// Partial data to merge into the resource.
		data: T,
	},
	/// Delete operation
	#[serde(rename = "delete")]
	Delete {
		/// Identifier of the resource to delete.
		id: String,
	},
}

/// Batch operation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchOperationResult<T> {
	/// Operation index in the request
	pub index: usize,
	/// Whether the operation succeeded
	pub success: bool,
	/// Result data (for create/update operations)
	pub data: Option<T>,
	/// Error message (if failed)
	pub error: Option<String>,
}

impl<T> BatchOperationResult<T> {
	/// Create a success result
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::BatchOperationResult;
	///
	/// let result = BatchOperationResult::success(0, Some("created".to_string()));
	/// assert!(result.success);
	/// assert_eq!(result.index, 0);
	/// ```
	pub fn success(index: usize, data: Option<T>) -> Self {
		Self {
			index,
			success: true,
			data,
			error: None,
		}
	}

	/// Create a failure result
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::BatchOperationResult;
	///
	/// let result: BatchOperationResult<String> = BatchOperationResult::failure(0, "Not found");
	/// assert!(!result.success);
	/// assert_eq!(result.error, Some("Not found".to_string()));
	/// ```
	pub fn failure(index: usize, error: impl Into<String>) -> Self {
		Self {
			index,
			success: false,
			data: None,
			error: Some(error.into()),
		}
	}
}

/// Batch request wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchRequest<T> {
	/// List of operations to perform
	pub operations: Vec<BatchOperation<T>>,
	/// Whether to stop on first error
	#[serde(default)]
	pub atomic: bool,
}

impl<T> BatchRequest<T> {
	/// Create a new batch request
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::{BatchRequest, BatchOperation};
	///
	/// let request: BatchRequest<String> = BatchRequest::new(vec![
	///     BatchOperation::Create { data: "item1".to_string() },
	///     BatchOperation::Create { data: "item2".to_string() },
	/// ]);
	/// assert_eq!(request.operations.len(), 2);
	/// ```
	pub fn new(operations: Vec<BatchOperation<T>>) -> Self {
		Self {
			operations,
			atomic: false,
		}
	}

	/// Set atomic mode
	pub fn atomic(mut self) -> Self {
		self.atomic = true;
		self
	}

	/// Get the number of operations
	pub fn len(&self) -> usize {
		self.operations.len()
	}

	/// Check if batch is empty
	pub fn is_empty(&self) -> bool {
		self.operations.is_empty()
	}
}

/// Batch response wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchResponse<T> {
	/// Results of operations
	pub results: Vec<BatchOperationResult<T>>,
	/// Total number of operations
	pub total: usize,
	/// Number of successful operations
	pub succeeded: usize,
	/// Number of failed operations
	pub failed: usize,
}

impl<T> BatchResponse<T> {
	/// Create a new batch response
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::{BatchResponse, BatchOperationResult};
	///
	/// let results = vec![
	///     BatchOperationResult::success(0, Some("created".to_string())),
	///     BatchOperationResult::failure(1, "Error"),
	/// ];
	/// let response = BatchResponse::new(results);
	/// assert_eq!(response.total, 2);
	/// assert_eq!(response.succeeded, 1);
	/// assert_eq!(response.failed, 1);
	/// ```
	pub fn new(results: Vec<BatchOperationResult<T>>) -> Self {
		let total = results.len();
		let succeeded = results.iter().filter(|r| r.success).count();
		let failed = total - succeeded;

		Self {
			results,
			total,
			succeeded,
			failed,
		}
	}

	/// Check if all operations succeeded
	pub fn all_succeeded(&self) -> bool {
		self.failed == 0
	}

	/// Check if any operation failed
	pub fn any_failed(&self) -> bool {
		self.failed > 0
	}
}

/// Batch operation processor
pub struct BatchProcessor;

impl BatchProcessor {
	/// Process a batch request
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_views::viewsets::{BatchProcessor, BatchRequest, BatchOperation};
	///
	/// let request: BatchRequest<String> = BatchRequest::new(vec![
	///     BatchOperation::Create { data: "item1".to_string() },
	/// ]);
	///
	/// let response = BatchProcessor::process(request, |op, index| {
	///     match op {
	///         BatchOperation::Create { data } => {
	///             Ok(format!("Created: {}", data))
	///         }
	///         _ => Err("Unsupported operation".to_string()),
	///     }
	/// });
	///
	/// assert!(response.all_succeeded());
	/// ```
	pub fn process<T, F>(request: BatchRequest<T>, mut handler: F) -> BatchResponse<T>
	where
		F: FnMut(&BatchOperation<T>, usize) -> std::result::Result<T, String>,
	{
		let mut results = Vec::new();

		for (index, operation) in request.operations.iter().enumerate() {
			match handler(operation, index) {
				Ok(data) => {
					results.push(BatchOperationResult::success(index, Some(data)));
				}
				Err(error) => {
					results.push(BatchOperationResult::failure(index, error));

					// Stop on first error in atomic mode
					if request.atomic {
						break;
					}
				}
			}
		}

		BatchResponse::new(results)
	}

	/// Validate batch request size
	pub fn validate_size<T>(
		request: &BatchRequest<T>,
		max_size: usize,
	) -> std::result::Result<(), String> {
		if request.operations.len() > max_size {
			return Err(format!(
				"Batch size {} exceeds maximum {}",
				request.operations.len(),
				max_size
			));
		}
		Ok(())
	}
}

/// Batch operation statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchStatistics {
	/// Number of operations by type
	pub by_type: HashMap<String, usize>,
	/// Total processing time (ms)
	pub processing_time_ms: u64,
}

impl BatchStatistics {
	/// Create a new batch statistics
	pub fn new() -> Self {
		Self {
			by_type: HashMap::new(),
			processing_time_ms: 0,
		}
	}

	/// Increment count for an operation type
	pub fn increment(&mut self, operation_type: impl Into<String>) {
		*self.by_type.entry(operation_type.into()).or_insert(0) += 1;
	}

	/// Set processing time
	pub fn set_processing_time(&mut self, ms: u64) {
		self.processing_time_ms = ms;
	}
}

impl Default for BatchStatistics {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_batch_operation_result_success() {
		let result = BatchOperationResult::success(0, Some("data".to_string()));
		assert!(result.success);
		assert_eq!(result.index, 0);
		assert_eq!(result.data, Some("data".to_string()));
		assert_eq!(result.error, None);
	}

	#[test]
	fn test_batch_operation_result_failure() {
		let result: BatchOperationResult<String> =
			BatchOperationResult::failure(1, "Error message");
		assert!(!result.success);
		assert_eq!(result.index, 1);
		assert_eq!(result.data, None);
		assert_eq!(result.error, Some("Error message".to_string()));
	}

	#[test]
	fn test_batch_request_new() {
		let operations = vec![
			BatchOperation::Create {
				data: "item1".to_string(),
			},
			BatchOperation::Create {
				data: "item2".to_string(),
			},
		];

		let request = BatchRequest::new(operations);
		assert_eq!(request.len(), 2);
		assert!(!request.atomic);
	}

	#[test]
	fn test_batch_request_atomic() {
		let request: BatchRequest<String> = BatchRequest::new(vec![]).atomic();
		assert!(request.atomic);
	}

	#[test]
	fn test_batch_response_statistics() {
		let results = vec![
			BatchOperationResult::success(0, Some("data1".to_string())),
			BatchOperationResult::success(1, Some("data2".to_string())),
			BatchOperationResult::failure(2, "Error"),
		];

		let response = BatchResponse::new(results);
		assert_eq!(response.total, 3);
		assert_eq!(response.succeeded, 2);
		assert_eq!(response.failed, 1);
		assert!(!response.all_succeeded());
		assert!(response.any_failed());
	}

	#[test]
	fn test_batch_processor_all_success() {
		let request = BatchRequest::new(vec![
			BatchOperation::Create {
				data: "item1".to_string(),
			},
			BatchOperation::Create {
				data: "item2".to_string(),
			},
		]);

		let response = BatchProcessor::process(request, |op, _index| match op {
			BatchOperation::Create { data } => Ok(format!("Created: {}", data)),
			_ => Err("Unsupported".to_string()),
		});

		assert_eq!(response.total, 2);
		assert_eq!(response.succeeded, 2);
		assert!(response.all_succeeded());
	}

	#[test]
	fn test_batch_processor_with_errors() {
		let request = BatchRequest::new(vec![
			BatchOperation::Create {
				data: "item1".to_string(),
			},
			BatchOperation::Create {
				data: "fail".to_string(),
			},
			BatchOperation::Create {
				data: "item3".to_string(),
			},
		]);

		let response = BatchProcessor::process(request, |op, _index| match op {
			BatchOperation::Create { data } => {
				if data == "fail" {
					Err("Failed".to_string())
				} else {
					Ok(format!("Created: {}", data))
				}
			}
			_ => Err("Unsupported".to_string()),
		});

		assert_eq!(response.total, 3);
		assert_eq!(response.succeeded, 2);
		assert_eq!(response.failed, 1);
	}

	#[test]
	fn test_batch_processor_atomic_mode() {
		let request = BatchRequest::new(vec![
			BatchOperation::Create {
				data: "item1".to_string(),
			},
			BatchOperation::Create {
				data: "fail".to_string(),
			},
			BatchOperation::Create {
				data: "item3".to_string(),
			},
		])
		.atomic();

		let response = BatchProcessor::process(request, |op, _index| match op {
			BatchOperation::Create { data } => {
				if data == "fail" {
					Err("Failed".to_string())
				} else {
					Ok(format!("Created: {}", data))
				}
			}
			_ => Err("Unsupported".to_string()),
		});

		// Only 2 operations should be processed (1 success + 1 failure)
		assert_eq!(response.results.len(), 2);
		assert_eq!(response.succeeded, 1);
		assert_eq!(response.failed, 1);
	}

	#[test]
	fn test_batch_processor_validate_size() {
		let request: BatchRequest<String> = BatchRequest::new(vec![
			BatchOperation::Create {
				data: "item1".to_string(),
			},
			BatchOperation::Create {
				data: "item2".to_string(),
			},
		]);

		assert!(BatchProcessor::validate_size(&request, 5).is_ok());
		assert!(BatchProcessor::validate_size(&request, 1).is_err());
	}

	#[test]
	fn test_batch_statistics() {
		let mut stats = BatchStatistics::new();
		stats.increment("create");
		stats.increment("create");
		stats.increment("update");
		stats.set_processing_time(1000);

		assert_eq!(stats.by_type.get("create"), Some(&2));
		assert_eq!(stats.by_type.get("update"), Some(&1));
		assert_eq!(stats.processing_time_ms, 1000);
	}

	#[test]
	fn test_batch_operation_serialization() {
		let op = BatchOperation::Create {
			data: "test".to_string(),
		};
		let json = serde_json::to_string(&op).unwrap();
		assert!(json.contains("\"operation\":\"create\""));
		assert!(json.contains("\"data\":\"test\""));
	}

	#[test]
	fn test_batch_request_is_empty() {
		let empty_request: BatchRequest<String> = BatchRequest::new(vec![]);
		assert!(empty_request.is_empty());

		let non_empty = BatchRequest::new(vec![BatchOperation::Create {
			data: "item".to_string(),
		}]);
		assert!(!non_empty.is_empty());
	}
}