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
//! `ViewSetHandler` — action mapping and dispatch from HTTP `Method` to a
//! ViewSet `Action`.
//!
//! This module is responsible for:
//!
//! - Mapping incoming HTTP methods to named viewset actions via `action_map`
//! - Extracting path parameters (DRF-style `kwargs`)
//! - Running viewset middleware via `process_request` before dispatch
//! - Producing a `405 Method Not Allowed` response with a populated `Allow`
//!   header when the request method is not in the mapping
//!
//! Note: only the pre-dispatch hook (`process_request`) is invoked here.
//! A post-response hook is not yet wired in; if/when middleware grows a
//! `process_response` method, it should be invoked after `dispatch` below.

use crate::{Action, ViewSet};
use async_trait::async_trait;
use hyper::Method;
use parking_lot::RwLock;
use reinhardt_http::{Handler, Request, Response, Result};
use std::collections::HashMap;
use std::sync::Arc;

/// Handler implementation that wraps a `ViewSet`.
pub struct ViewSetHandler<V: ViewSet> {
	viewset: Arc<V>,
	action_map: HashMap<Method, String>,
	// Allow dead_code: stored for DRF-compatible handler identification in URL reversing
	#[allow(dead_code)]
	name: Option<String>,
	// Allow dead_code: stored for DRF-compatible view suffix (e.g. "List", "Instance") in URL reversing
	#[allow(dead_code)]
	suffix: Option<String>,

	// Attributes set after as_view() is called
	// These mirror Django REST Framework's behavior
	args: RwLock<Option<Vec<String>>>,
	kwargs: RwLock<Option<HashMap<String, String>>>,
	has_handled_request: RwLock<bool>,
}

// parking_lot::RwLock does not use poisoning, so the locks in
// ViewSetHandler do not introduce unwind-safety hazards. The unwind
// safety of the handler still depends on the underlying ViewSet,
// so we only assert RefUnwindSafe when V is itself RefUnwindSafe.
impl<V: ViewSet + std::panic::RefUnwindSafe> std::panic::RefUnwindSafe for ViewSetHandler<V> {}

impl<V: ViewSet> ViewSetHandler<V> {
	/// Create a new `ViewSetHandler` with the given viewset and action mapping.
	pub fn new(
		viewset: Arc<V>,
		action_map: HashMap<Method, String>,
		name: Option<String>,
		suffix: Option<String>,
	) -> Self {
		Self {
			viewset,
			action_map,
			name,
			suffix,
			args: RwLock::new(None),
			kwargs: RwLock::new(None),
			has_handled_request: RwLock::new(false),
		}
	}

	/// Check if args attribute is set (for testing)
	pub fn has_args(&self) -> bool {
		self.args.read().is_some()
	}

	/// Check if kwargs attribute is set (for testing)
	pub fn has_kwargs(&self) -> bool {
		self.kwargs.read().is_some()
	}

	/// Check if request attribute is set (for testing)
	pub fn has_request(&self) -> bool {
		*self.has_handled_request.read()
	}

	/// Check if action_map is set (for testing)
	pub fn has_action_map(&self) -> bool {
		!self.action_map.is_empty()
	}
}

#[async_trait]
impl<V: ViewSet + 'static> Handler for ViewSetHandler<V> {
	async fn handle(&self, mut request: Request) -> Result<Response> {
		// Set attributes when handling request (DRF behavior)
		*self.has_handled_request.write() = true;
		*self.args.write() = Some(Vec::new());

		// Extract path parameters from URI
		let kwargs = extract_path_params(&request);
		*self.kwargs.write() = Some(kwargs);

		// Process middleware before ViewSet
		if let Some(middleware) = self.viewset.get_middleware()
			&& let Some(response) = middleware.process_request(&mut request).await?
		{
			return Ok(response);
		}

		// Resolve action from HTTP method
		let action_name = match self.action_map.get(&request.method) {
			Some(name) => name,
			None => {
				let allowed: Vec<String> = self.action_map.keys().map(|m| m.to_string()).collect();
				let mut response = Response::new(hyper::StatusCode::METHOD_NOT_ALLOWED);
				match allowed.join(", ").parse() {
					Ok(header_value) => {
						response.headers.insert(hyper::header::ALLOW, header_value);
					}
					Err(e) => {
						tracing::warn!(
							error = %e,
							"Failed to parse allowed methods as header value"
						);
					}
				}
				return Ok(response);
			}
		};

		// Create Action from name
		let action = Action::from_name(action_name);

		// Dispatch to ViewSet
		let response = self.viewset.dispatch(request, action).await?;

		// Post-response middleware hook is not yet implemented; when the
		// middleware trait gains a `process_response` method, invoke it here.
		Ok(response)
	}
}

/// Extract path parameters from request.
///
/// Simple implementation — in production this would use the router's path
/// matching. If the path has a pattern like `/resource/123/`, `123` is
/// captured as the `id` parameter.
pub(crate) fn extract_path_params(request: &Request) -> HashMap<String, String> {
	let mut params = HashMap::new();

	// Simple extraction: if path has pattern like /resource/123/
	// extract "123" as the "id" parameter
	let path = request.uri.path();
	let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

	// If we have at least 2 segments, treat the second as an ID parameter.
	// Accept any non-empty segment (numeric, UUID, slug, etc.)
	if segments.len() >= 2 {
		params.insert("id".to_string(), segments[1].to_string());
	}

	params
}

#[cfg(test)]
mod tests {
	use super::*;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method, Version};
	use reinhardt_http::Request;
	use rstest::rstest;
	use std::thread;

	fn build_request(uri: &str) -> Request {
		Request::builder()
			.method(Method::GET)
			.uri(uri)
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap()
	}

	#[rstest]
	fn test_parking_lot_rwlock_does_not_poison_after_panic() {
		// Arrange
		// parking_lot::RwLock does not poison, so after a thread panics
		// while holding the lock, subsequent access should succeed.
		let lock = RwLock::new(42);

		// Act - panic while holding write lock
		let lock_ref = &lock;
		let result = thread::scope(|s| {
			let handle = s.spawn(|| {
				let mut guard = lock_ref.write();
				*guard = 100;
				panic!("intentional panic while holding write lock");
			});
			let _ = handle.join(); // Thread panicked

			// Assert - lock is still usable (no poisoning)
			*lock_ref.read()
		});

		// parking_lot recovers the lock after panic
		assert!(result == 42 || result == 100);
	}

	#[rstest]
	fn test_rwlock_concurrent_read_access() {
		// Arrange
		let lock = RwLock::new(String::from("test_value"));

		// Act - multiple readers should not block each other
		let guard1 = lock.read();
		let guard2 = lock.read();

		// Assert
		assert_eq!(*guard1, "test_value");
		assert_eq!(*guard2, "test_value");
	}

	#[rstest]
	fn test_extract_path_params_numeric_segment_treated_as_id() {
		// Arrange
		let request = build_request("/resource/123/");

		// Act
		let params = extract_path_params(&request);

		// Assert
		assert_eq!(params.get("id"), Some(&"123".to_string()));
	}

	#[rstest]
	fn test_extract_path_params_non_numeric_segment_treated_as_id() {
		// Arrange
		let request = build_request("/resource/username/");

		// Act
		let params = extract_path_params(&request);

		// Assert
		assert_eq!(params.get("id"), Some(&"username".to_string()));
	}

	#[rstest]
	fn test_extract_path_params_slug_segment_treated_as_id() {
		// Arrange
		let request = build_request("/resource/my-slug/");

		// Act
		let params = extract_path_params(&request);

		// Assert
		assert_eq!(params.get("id"), Some(&"my-slug".to_string()));
	}

	#[rstest]
	fn test_extract_path_params_uuid_segment_treated_as_id() {
		// Arrange
		let request = build_request("/resource/550e8400-e29b-41d4-a716-446655440000/");

		// Act
		let params = extract_path_params(&request);

		// Assert
		assert_eq!(
			params.get("id"),
			Some(&"550e8400-e29b-41d4-a716-446655440000".to_string())
		);
	}

	#[rstest]
	fn test_extract_path_params_single_segment_no_id() {
		// Arrange
		let request = build_request("/resource/");

		// Act
		let params = extract_path_params(&request);

		// Assert
		assert_eq!(params.get("id"), None);
	}

	/// Minimal ViewSet implementation for testing ViewSetHandler
	struct MockViewSet;

	#[async_trait]
	impl ViewSet for MockViewSet {
		fn get_basename(&self) -> &str {
			"mock"
		}

		async fn dispatch(
			&self,
			_request: reinhardt_http::Request,
			_action: crate::Action,
		) -> reinhardt_http::Result<reinhardt_http::Response> {
			Ok(reinhardt_http::Response::ok())
		}
	}

	/// Helper to build a ViewSetHandler with a specific action_map
	fn build_handler(methods: Vec<Method>) -> ViewSetHandler<MockViewSet> {
		let mut action_map = HashMap::new();
		for method in methods {
			action_map.insert(method, "mock_action".to_string());
		}
		ViewSetHandler::new(Arc::new(MockViewSet), action_map, None, None)
	}

	/// Helper to build a minimal request with the given method
	fn build_method_request(method: Method) -> reinhardt_http::Request {
		reinhardt_http::Request::builder()
			.method(method)
			.uri("/mock/")
			.version(hyper::Version::HTTP_11)
			.headers(hyper::HeaderMap::new())
			.body(bytes::Bytes::new())
			.build()
			.unwrap()
	}

	#[rstest]
	#[tokio::test]
	async fn test_unregistered_method_returns_405() {
		// Arrange
		let handler = build_handler(vec![Method::GET]);
		let request = build_method_request(Method::DELETE);

		// Act
		let response = Handler::handle(&handler, request).await.unwrap();

		// Assert
		assert_eq!(response.status, hyper::StatusCode::METHOD_NOT_ALLOWED);
	}

	#[rstest]
	#[tokio::test]
	async fn test_405_response_allow_header_contains_registered_methods() {
		// Arrange
		let handler = build_handler(vec![Method::GET, Method::POST]);
		let request = build_method_request(Method::DELETE);

		// Act
		let response = Handler::handle(&handler, request).await.unwrap();

		// Assert
		assert_eq!(response.status, hyper::StatusCode::METHOD_NOT_ALLOWED);
		let allow_header = response
			.headers
			.get(hyper::header::ALLOW)
			.expect("Allow header must be present");
		let allow_str = allow_header.to_str().unwrap();
		// Both registered methods must appear in the Allow header
		assert!(allow_str.contains("GET"), "Allow header must contain GET");
		assert!(allow_str.contains("POST"), "Allow header must contain POST");
	}

	#[rstest]
	#[tokio::test]
	async fn test_405_response_allow_header_comma_separated_format() {
		// Arrange
		let handler = build_handler(vec![Method::GET, Method::PUT]);
		let request = build_method_request(Method::PATCH);

		// Act
		let response = Handler::handle(&handler, request).await.unwrap();

		// Assert
		assert_eq!(response.status, hyper::StatusCode::METHOD_NOT_ALLOWED);
		let allow_header = response
			.headers
			.get(hyper::header::ALLOW)
			.expect("Allow header must be present");
		let allow_str = allow_header.to_str().unwrap();
		// Verify comma-separated format: each method is separated by ", "
		let methods: Vec<&str> = allow_str.split(", ").collect();
		assert_eq!(
			methods.len(),
			2,
			"Allow header must contain exactly 2 methods"
		);
		for method in &methods {
			assert!(
				*method == "GET" || *method == "PUT",
				"Unexpected method in Allow header: {}",
				method
			);
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_registered_method_does_not_return_405() {
		// Arrange
		let handler = build_handler(vec![Method::GET]);
		let request = build_method_request(Method::GET);

		// Act
		let response = Handler::handle(&handler, request).await.unwrap();

		// Assert
		assert_eq!(response.status, hyper::StatusCode::OK);
	}
}