vorma 0.86.0-pre.3

Vorma framework.
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::borrow::Cow;
use std::future::Future;
#[cfg(test)]
use std::sync::Arc;

use http::Method;
#[cfg(test)]
use serde::Serialize;
use serde_json::Value;
#[cfg(test)]
use vorma_tasks::Result as TaskResult;

#[cfg(test)]
use crate::api;
#[cfg(test)]
use crate::mux::RouteExecutionError;
use crate::mux::{self, NestedRouter};
#[cfg(test)]
use crate::mux::{InputParser, None};
use crate::searchparams;
use crate::tsgen::{Type, TypePhase, TypeRef, TypeRegistry};

mod context;
mod contract;
#[cfg(test)]
use context::accepts_client_redirect;
pub use context::{HeadHandle, MiddlewareCtx, Params, ResourceCtx, ResponseHandle, ViewCtx};
use contract::RouteCollector;
pub use contract::{Contract, ResourceEntry, ViewEntry, contract_for};
#[cfg(test)]
use pattern::default_resource_kind_for_method;
use pattern::validate_declared_route_pattern;
pub use pattern::{
	default_resource_kind, params_for_pattern, pattern_is_splat, view_parents_for_patterns,
};
mod pattern;
pub(crate) use runtime::{RuntimeRoutes, runtime_routes_for};
mod runtime;
#[cfg(test)]
use runner::serialize_route_output;
pub use runner::{
	ErasedRequestCtx, ErasedRouteFuture, ErasedRouteHandler, PathParams, RouteFuture,
	run_static_resource, run_static_view,
};
use runner::{RouteRunner, run_route_runner};
mod runner;

#[doc(hidden)]
pub type TypeResolver = fn(TypePhase, &mut TypeRegistry) -> Result<TypeRef, String>;
#[doc(hidden)]
pub type SearchSchemaResolver = fn() -> Result<Value, String>;
#[cfg(test)]
type ResourceHandler<S, E, I, P, O> =
	dyn Fn(ResourceCtx<S, E, I, P>) -> RouteFuture<O, E> + Send + Sync;
#[cfg(test)]
type ViewHandler<S, E, I, P, O> = dyn Fn(ViewCtx<S, E, I, P>) -> RouteFuture<O, E> + Send + Sync;

#[doc(hidden)]
pub fn type_resolver<T>(phase: TypePhase, registry: &mut TypeRegistry) -> Result<TypeRef, String>
where
	T: Type,
{
	T::collect_type_defs_for(phase, registry).map_err(|err| err.to_string())?;
	Ok(T::type_ref_for(phase))
}

#[doc(hidden)]
pub fn search_schema_resolver<T>() -> Result<Value, String>
where
	T: Type,
{
	searchparams::schema_for_type::<T>().map_err(|err| err.to_string())
}

/// Request-scoped middleware declaration shared by views and resources.
pub struct Middleware<S, E = Box<dyn std::error::Error + Send + Sync>> {
	mw: mux::Middleware<S, E>,
}

impl<S, E> Middleware<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	/// Create middleware from an async handler.
	pub fn new<F, Fut, O>(handler: F) -> Self
	where
		F: Fn(MiddlewareCtx<S, E>) -> Fut + Send + Sync + 'static,
		Fut: Future<Output = vorma_tasks::Result<O, E>> + Send + 'static,
		O: Send + Sync + 'static,
	{
		Self {
			mw: mux::Middleware::new(move |ctx| {
				let future = handler(MiddlewareCtx::new(ctx));
				async move { future.await.map(|_| ()) }
			}),
		}
	}

	fn register_resource(&self, r: &mut mux::Router<S, E>) -> Result<(), mux::Error> {
		r.use_middleware_entry(&self.mw);
		Ok(())
	}

	fn register_view(&self, r: &mut NestedRouter<S, E>) -> Result<(), mux::Error> {
		r.use_middleware_entry(&self.mw);
		Ok(())
	}

	fn register_runtime(&self, routes: &mut RuntimeRoutes<S, E>) -> Result<(), mux::Error> {
		self.register_resource(&mut routes.resources)?;
		self.register_view(&mut routes.views)?;
		Ok(())
	}
}

/// Generated-client classification for a resource.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ResourceKind {
	/// Read-shaped resource. GET/HEAD resources default to this when no explicit kind is set.
	Query,
	/// Write-shaped resource. Non-GET/HEAD resources default to this when no explicit kind is set.
	Mutation,
}

impl ResourceKind {
	/// Return the generated TypeScript literal for this resource kind.
	pub fn as_str(self) -> &'static str {
		match self {
			Self::Query => "query",
			Self::Mutation => "mutation",
		}
	}
}

/// Nested view declaration.
pub struct View<S, E = Box<dyn std::error::Error + Send + Sync>> {
	pattern: Cow<'static, str>,
	handler: RouteRunner<S, E>,
	client_file: Cow<'static, str>,
	input_type: TypeResolver,
	output_type: TypeResolver,
	search_schema: SearchSchemaResolver,
}

impl<S, E> View<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	#[doc(hidden)]
	pub const fn from_static(
		pattern: &'static str,
		client_file: &'static str,
		input_type: TypeResolver,
		output_type: TypeResolver,
		search_schema: SearchSchemaResolver,
		handler: ErasedRouteHandler<S, E>,
	) -> Self {
		Self {
			pattern: Cow::Borrowed(pattern),
			handler: RouteRunner::Static(handler),
			client_file: Cow::Borrowed(client_file),
			input_type,
			output_type,
			search_schema,
		}
	}

	#[cfg(test)]
	pub(crate) fn new<I, P, O, F, Fut>(
		pattern: impl Into<String>,
		client_file: impl Into<String>,
		input_parser: InputParser<I>,
		handler: F,
	) -> Self
	where
		F: Fn(ViewCtx<S, E, I, P>) -> Fut + Send + Sync + 'static,
		Fut: Future<Output = TaskResult<O, E>> + Send + 'static,
		I: Type + api::ViewInput,
		P: PathParams,
		O: Type + Serialize + Send + Sync + 'static,
	{
		let handler: Arc<ViewHandler<S, E, I, P, O>> = Arc::new(move |ctx| Box::pin(handler(ctx)));
		Self {
			pattern: Cow::Owned(pattern.into()),
			handler: RouteRunner::Dynamic(Arc::new(move |ctx| {
				let input_parser = input_parser.clone();
				let handler = handler.clone();
				Box::pin(async move {
					let input = input_parser
						.parse(ctx.request())
						.await
						.map_err(RouteExecutionError::Input)?;
					let params = P::from_raw_path_params(ctx.params())
						.map_err(RouteExecutionError::Input)?;
					let output = handler(ViewCtx::new(ctx.with_input(input), params))
						.await
						.map_err(RouteExecutionError::Task)?;
					serialize_route_output(output)
				})
			})),
			client_file: Cow::Owned(client_file.into()),
			input_type: type_resolver::<I>,
			output_type: type_resolver::<O>,
			search_schema: search_schema_resolver::<I>,
		}
	}

	/// Registered view pattern.
	pub fn pattern(&self) -> &str {
		&self.pattern
	}

	/// Frontend client module associated with this view.
	pub fn client_file(&self) -> &str {
		&self.client_file
	}
}

/// Collection of middleware declarations.
#[derive(Default)]
pub struct Middlewares<S, E = Box<dyn std::error::Error + Send + Sync>> {
	middlewares: Vec<Middleware<S, E>>,
}

impl<S, E> Middlewares<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	/// Create an empty middleware collection.
	pub fn new() -> Self {
		Self {
			middlewares: Vec::new(),
		}
	}

	/// Append a middleware declaration.
	pub fn push(&mut self, middleware: Middleware<S, E>) -> &mut Self {
		self.middlewares.push(middleware);
		self
	}

	fn register_runtime(&self, routes: &mut RuntimeRoutes<S, E>) -> Result<(), mux::Error> {
		for middleware in &self.middlewares {
			middleware.register_runtime(routes)?;
		}
		Ok(())
	}
}

impl<S, E> View<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	fn register_contract(&self, collector: &mut RouteCollector) -> Result<(), String> {
		let input = (self.input_type)(TypePhase::Deserialize, &mut collector.types)?;
		let output = (self.output_type)(TypePhase::Serialize, &mut collector.types)?;
		collector.views.push(ViewEntry {
			pattern: self.pattern.to_string(),
			client_file: self.client_file.to_string(),
			input,
			output,
			search_schema: (self.search_schema)()
				.map_err(|err| format!("view {} input: {err}", self.pattern))?,
		});
		Ok(())
	}

	fn register_to_mux(&self, r: &mut NestedRouter<S, E>) -> Result<(), mux::Error> {
		validate_declared_route_pattern("view", &self.pattern)
			.map_err(mux::Error::InvalidPattern)?;
		let handler = self.handler.clone();
		r.add_handler_entry(
			self.pattern.to_string(),
			mux::erased_handler(move |ctx| {
				let handler = handler.clone();
				async move { run_route_runner(handler, ctx).await }
			}),
		)
	}
}

/// Resource declaration.
pub struct Resource<S, E = Box<dyn std::error::Error + Send + Sync>> {
	method: Method,
	pattern: Cow<'static, str>,
	kind: Option<ResourceKind>,
	handler: RouteRunner<S, E>,
	input_type: TypeResolver,
	output_type: TypeResolver,
}

impl<S, E> Resource<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	#[doc(hidden)]
	pub const fn from_static(
		method: Method,
		pattern: &'static str,
		kind: Option<ResourceKind>,
		input_type: TypeResolver,
		output_type: TypeResolver,
		handler: ErasedRouteHandler<S, E>,
	) -> Self {
		Self {
			method,
			pattern: Cow::Borrowed(pattern),
			kind,
			handler: RouteRunner::Static(handler),
			input_type,
			output_type,
		}
	}

	#[cfg(test)]
	pub(crate) fn new<I, P, O, F, Fut>(
		method: Method,
		pattern: impl Into<String>,
		kind: Option<ResourceKind>,
		input_parser: InputParser<I>,
		handler: F,
	) -> Self
	where
		F: Fn(ResourceCtx<S, E, I, P>) -> Fut + Send + Sync + 'static,
		Fut: Future<Output = TaskResult<O, E>> + Send + 'static,
		I: Type + api::ResourceInput,
		P: PathParams,
		O: Type + Serialize + Send + Sync + 'static,
	{
		let handler: Arc<ResourceHandler<S, E, I, P, O>> =
			Arc::new(move |ctx| Box::pin(handler(ctx)));
		Self {
			method,
			pattern: Cow::Owned(pattern.into()),
			kind,
			handler: RouteRunner::Dynamic(Arc::new(move |ctx| {
				let input_parser = input_parser.clone();
				let handler = handler.clone();
				Box::pin(async move {
					let input = input_parser
						.parse(ctx.request())
						.await
						.map_err(RouteExecutionError::Input)?;
					let params = P::from_raw_path_params(ctx.params())
						.map_err(RouteExecutionError::Input)?;
					let output = handler(ResourceCtx::new(ctx.with_input(input), params))
						.await
						.map_err(RouteExecutionError::Task)?;
					serialize_route_output(output)
				})
			})),
			input_type: type_resolver::<I>,
			output_type: type_resolver::<O>,
		}
	}

	/// HTTP method registered for this resource.
	pub fn method(&self) -> &Method {
		&self.method
	}

	/// Resource pattern relative to the configured API mount root.
	pub fn pattern(&self) -> &str {
		&self.pattern
	}

	/// Explicit generated-client kind override, when one was declared.
	pub fn kind(&self) -> Option<ResourceKind> {
		self.kind
	}
}

impl<S, E> Resource<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	#[cfg(test)]
	pub(crate) fn without_handler(
		method: Method,
		pattern: impl Into<String>,
		kind: Option<ResourceKind>,
	) -> Self {
		Self::new(
			method,
			pattern,
			kind,
			InputParser::default_input(),
			|_: ResourceCtx<S, E, (), ()>| async { Ok(None) },
		)
	}
}

impl<S, E> Resource<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	fn register_contract(&self, collector: &mut RouteCollector) -> Result<(), String> {
		let input = (self.input_type)(TypePhase::Deserialize, &mut collector.types)?;
		let output = (self.output_type)(TypePhase::Serialize, &mut collector.types)?;
		collector.resources.push(ResourceEntry {
			method: self.method.as_str().to_owned(),
			pattern: self.pattern.to_string(),
			kind: self.kind,
			input,
			output,
		});
		Ok(())
	}

	fn register_to_mux(&self, r: &mut mux::Router<S, E>) -> Result<(), mux::Error> {
		validate_declared_route_pattern("resource", &self.pattern)
			.map_err(mux::Error::InvalidPattern)?;
		let handler = self.handler.clone();
		r.add_handler_entry(
			self.method.clone(),
			self.pattern.to_string(),
			mux::erased_handler(move |ctx| {
				let handler = handler.clone();
				async move { run_route_runner(handler, ctx).await }
			}),
		)?;
		Ok(())
	}
}

/// Collection of nested view declarations.
#[derive(Default)]
pub struct Views<S, E = Box<dyn std::error::Error + Send + Sync>> {
	views: Vec<View<S, E>>,
}

impl<S, E> Views<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	/// Create an empty view collection.
	pub fn new() -> Self {
		Self { views: Vec::new() }
	}

	/// Append a view declaration.
	pub fn push(&mut self, view: View<S, E>) -> &mut Self {
		self.views.push(view);
		self
	}

	fn register_contract(&self, collector: &mut RouteCollector) -> Result<(), String> {
		for view in &self.views {
			view.register_contract(collector)?;
		}
		Ok(())
	}

	fn register_runtime(&self, routes: &mut RuntimeRoutes<S, E>) -> Result<(), mux::Error> {
		for view in &self.views {
			view.register_to_mux(&mut routes.views)?;
		}
		Ok(())
	}
}

/// Collection of resource declarations.
#[derive(Default)]
pub struct Resources<S, E = Box<dyn std::error::Error + Send + Sync>> {
	resources: Vec<Resource<S, E>>,
}

impl<S, E> Resources<S, E>
where
	S: Send + Sync + 'static,
	E: Send + Sync + 'static,
{
	/// Create an empty resource collection.
	pub fn new() -> Self {
		Self {
			resources: Vec::new(),
		}
	}

	/// Append a resource declaration.
	pub fn push(&mut self, resource: Resource<S, E>) -> &mut Self {
		self.resources.push(resource);
		self
	}

	fn register_contract(&self, collector: &mut RouteCollector) -> Result<(), String> {
		for resource in &self.resources {
			resource.register_contract(collector)?;
		}
		Ok(())
	}

	fn register_runtime(&self, routes: &mut RuntimeRoutes<S, E>) -> Result<(), mux::Error> {
		for resource in &self.resources {
			resource.register_to_mux(&mut routes.resources)?;
		}
		Ok(())
	}
}

#[cfg(test)]
#[path = "core_tests.rs"]
mod core_tests;