vorma 0.86.0-pre.1

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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use bytes::Buf;
use bytes::Bytes;
use http::header::{ALLOW, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue};
use http::{Method, Request, Response, StatusCode};
use http_body::Body;
use http_body_util::{BodyExt, Full, LengthLimitError, Limited};
use path_clean::PathClean;
use vorma_tasks::{CancelToken, Tasks};

use crate::App;
use crate::config::Config;
use crate::config::normalize_api_mount_root;
use crate::core::{RuntimeRoutes, runtime_routes_for};
use crate::document::{DocumentBuildCtx, DocumentBuilder};
use crate::envutil::{is_build, is_dev};
use crate::error::ViewErrorClientMsg;
use crate::handler::{
	ApiResponseInput, ViewResponseResultsInput, build_api_response,
	build_view_response_from_results, build_view_skew_response, refresh_script_inner_html,
	view_not_found_response,
};
use crate::htmlutil::{Element, compute_content_sha256};
use crate::mux::RawRequest;
use crate::response::response_with_client_build_id;
use crate::response::{
	internal_server_error_response, internal_server_error_with_client_build_id, plain_text_response,
};
use crate::r#static::{
	ManifestMode, RuntimeAssetSnapshot, RuntimeAssets, path_is_under_public_static_base,
	static_out_dir,
};

/// Runtime service that serves Vorma static assets, resources, and views.
pub struct RuntimeHost<S, E = Box<dyn std::error::Error + Send + Sync>> {
	state: Arc<S>,
	tasks: Tasks<E>,
	document: DocumentBuilder,
	routes: Arc<RuntimeRoutes<S, E>>,
	assets: Option<RuntimeAssets>,
	request_body_limit: usize,
}

impl<S, E> RuntimeHost<S, E>
where
	S: Send + Sync + 'static,
	E: ViewErrorClientMsg + Send + Sync + 'static,
{
	pub(crate) fn new(app: App<S, E>) -> Result<Self, String> {
		let App {
			config: cfg,
			state,
			views,
			resources,
			middlewares,
			tasks_options,
			document,
			request_body_limit,
		} = app;
		validate_runtime_config(&cfg)?;
		let assets = default_runtime_assets(&cfg);
		let initial_snapshot = assets
			.as_ref()
			.map(RuntimeAssets::snapshot)
			.transpose()
			.map_err(|err| format!("error initializing runtime assets: {err}"))?;
		let api_mount_root = initial_snapshot
			.as_ref()
			.map(|snapshot| snapshot.manifest().api_mount_root.as_str())
			.unwrap_or(&cfg.path_config.api_base);
		let api_mount_root = normalize_api_mount_root(api_mount_root)
			.map_err(|err| format!("error with API mount root: {err}"))?;
		let routes = runtime_routes_for(&views, &resources, &middlewares, &api_mount_root)
			.map_err(|err| err.to_string())?;
		Ok(Self {
			state: Arc::new(state),
			tasks: Tasks::new(tasks_options),
			document,
			routes: Arc::new(routes),
			assets,
			request_body_limit,
		})
	}

	/// Resolve a public static source path through the current runtime manifest.
	pub fn public_url(&self, src_path: &str) -> Result<String, String> {
		if is_build() {
			return Ok(String::new());
		}
		let snapshot = self.snapshot()?;
		snapshot
			.manifest()
			.public_url(src_path)
			.map(ToOwned::to_owned)
			.ok_or_else(|| format!("file {src_path} not found in manifest public filemap"))
	}

	/// Current deterministic client build ID.
	pub fn client_build_id(&self) -> Result<String, String> {
		if is_build() {
			return Ok(String::new());
		}
		let snapshot = self.snapshot()?;
		Ok(snapshot.client_build_id().to_owned())
	}

	/// SHA-256 content hash for the runtime critical CSS element.
	pub fn critical_css_content_sha256(&self) -> Result<String, String> {
		if is_build() {
			return Ok(String::new());
		}
		let snapshot = self.snapshot()?;
		Ok(snapshot.manifest().critical_css_content_sha256())
	}

	/// SHA-256 content hash for the dev refresh script element.
	pub fn dev_refresh_script_content_sha256(&self) -> Result<String, String> {
		if !is_dev() {
			return Ok(String::new());
		}
		let snapshot = self.snapshot()?;
		let inner_html = refresh_script_inner_html(snapshot.manifest());
		Ok(compute_content_sha256(&Element {
			dangerous_inner_html: inner_html,
			..Element::default()
		}))
	}

	/// Handle an already-collected request.
	///
	/// Mounting [`RuntimeHost`] as a Tower service is usually preferable because the
	/// service implementation enforces the configured request body limit before calling
	/// this lower-level entry point.
	pub async fn handle_request(&self, request: Request<Bytes>) -> Result<Response<Bytes>, String> {
		let head_request = request.method() == Method::HEAD;
		let response = self.handle_request_with_body(request).await?;
		if head_request {
			return Ok(head_response_without_body(response));
		}
		Ok(response)
	}

	async fn handle_request_with_body(
		&self,
		request: Request<Bytes>,
	) -> Result<Response<Bytes>, String> {
		if request.body().len() > self.request_body_limit {
			return Ok(payload_too_large_response());
		}

		if let Some(response) = dev_health_check_response(&request)? {
			return Ok(response);
		}

		let request = raw_request(request);

		if request_path_is_under_mount_root(request.path(), self.routes.resources.mount_root()) {
			return self.handle_api_request(request).await;
		}

		if let Some(response) = self.public_asset_response(request.method(), request.path())? {
			return Ok(response);
		}

		if request.method() == Method::GET || request.method() == Method::HEAD {
			return self.handle_view_request(request).await;
		}

		empty_response(StatusCode::NOT_FOUND)
	}

	async fn handle_api_request(&self, request: RawRequest) -> Result<Response<Bytes>, String> {
		if !self.routes.resources.method_is_allowed(request.method()) {
			let allow = self.api_allow_header();
			if !allow.is_empty() {
				return method_not_allowed_response(&allow);
			}
		}
		let snapshot = self
			.assets
			.as_ref()
			.map(RuntimeAssets::snapshot)
			.transpose()?;
		let client_build_id = snapshot
			.as_ref()
			.map(|snapshot| snapshot.client_build_id().to_owned())
			.unwrap_or_default();
		let public_filemap = Arc::new(
			snapshot
				.as_ref()
				.map(|snapshot| snapshot.manifest().public_filemap.clone())
				.unwrap_or_default(),
		);
		let raw_path = request.path().to_owned();
		let RequestExecCtx {
			exec_ctx,
			_cancel_on_drop,
		} = self.request_exec_ctx();
		let result = match self
			.routes
			.resources
			.execute_route(request, self.state.clone(), exec_ctx, public_filemap)
			.await
		{
			Ok(result) => result,
			Err(_) => return internal_server_error_with_client_build_id(&client_build_id),
		};
		let Some(result) = result else {
			if let Some(allow) = self.api_allow_header_for_path(&raw_path) {
				let response = method_not_allowed_response(&allow)?;
				return response_with_client_build_id(response, &client_build_id);
			}
			let response = empty_response(StatusCode::NOT_FOUND)?;
			return response_with_client_build_id(response, &client_build_id);
		};
		let response = match build_api_response(ApiResponseInput {
			expected_client_build_id: &client_build_id,
			result: &result,
		}) {
			Ok(response) => response,
			Err(_) => return internal_server_error_with_client_build_id(&client_build_id),
		};
		Ok(response)
	}

	async fn handle_view_request(&self, request: RawRequest) -> Result<Response<Bytes>, String> {
		let Some(assets) = &self.assets else {
			return empty_response(StatusCode::NOT_FOUND);
		};
		let snapshot = assets.snapshot()?;
		match build_view_skew_response(request.uri(), snapshot.client_build_id()) {
			Ok(Some(response)) => return Ok(response),
			Ok(Option::None) => {}
			Err(_) => {
				return internal_server_error_with_client_build_id(snapshot.client_build_id());
			}
		}
		let match_results = match self.routes.views.find_nested_matches(request.path()) {
			Ok(Some(match_results)) => match_results,
			Ok(Option::None) => return view_not_found_response(snapshot.client_build_id()),
			Err(_) => {
				return internal_server_error_with_client_build_id(snapshot.client_build_id());
			}
		};
		let RequestExecCtx {
			exec_ctx,
			_cancel_on_drop,
		} = self.request_exec_ctx();
		let public_filemap = Arc::new(snapshot.manifest().public_filemap.clone());
		let document = self.document.build(DocumentBuildCtx::manifest(
			snapshot.manifest_handle(),
			request.clone(),
		));
		let tasks_results = self.routes.views.run_nested_tasks(
			self.state.clone(),
			exec_ctx,
			request.clone(),
			match_results.clone(),
			public_filemap,
		);
		let (document, tasks_results) = match tokio::try_join!(document, async {
			tasks_results.await.map_err(|err| err.to_string())
		}) {
			Ok(results) => results,
			Err(_) => {
				return internal_server_error_with_client_build_id(snapshot.client_build_id());
			}
		};
		match build_view_response_from_results(ViewResponseResultsInput {
			expected_client_build_id: snapshot.client_build_id(),
			request: &request,
			manifest: snapshot.manifest(),
			document: &document,
			match_results: &match_results,
			tasks_results: &tasks_results,
		}) {
			Ok(response) => Ok(response),
			Err(_) => internal_server_error_with_client_build_id(snapshot.client_build_id()),
		}
	}

	fn public_asset_response(
		&self,
		method: &Method,
		path: &str,
	) -> Result<Option<Response<Bytes>>, String> {
		if method != Method::GET && method != Method::HEAD {
			return Ok(None);
		}
		let Some(assets) = &self.assets else {
			return Ok(None);
		};
		if method == Method::HEAD {
			let Some(asset) = assets.stat_public_asset(path)? else {
				return self.public_asset_missing_response(assets, path);
			};
			return public_asset_found_response(
				Bytes::new(),
				asset.content_length,
				asset.cache_control,
				asset.content_type,
			)
			.map(Some);
		}
		let Some(asset) = assets.read_public_asset(path)? else {
			return self.public_asset_missing_response(assets, path);
		};
		let content_length = asset.bytes.len() as u64;
		public_asset_found_response(
			Bytes::from(asset.bytes),
			content_length,
			asset.cache_control,
			asset.content_type,
		)
		.map(Some)
	}

	fn public_asset_missing_response(
		&self,
		assets: &RuntimeAssets,
		path: &str,
	) -> Result<Option<Response<Bytes>>, String> {
		let snapshot = assets.snapshot()?;
		if path_is_under_public_static_base(snapshot.manifest(), path) {
			return empty_response(StatusCode::NOT_FOUND).map(Some);
		}
		Ok(None)
	}

	fn api_allow_header_for_path(&self, path: &str) -> Option<String> {
		let methods = self.routes.resources.allowed_methods_for_path(path);
		if methods.is_empty() {
			return None;
		}
		Some(allow_header_value(&methods))
	}

	fn api_allow_header(&self) -> String {
		allow_header_value(&self.routes.resources.allowed_methods())
	}

	fn snapshot(&self) -> Result<Arc<RuntimeAssetSnapshot>, String> {
		self.assets
			.as_ref()
			.ok_or_else(|| "runtime assets are unavailable".to_owned())?
			.snapshot()
	}

	fn request_exec_ctx(&self) -> RequestExecCtx<E> {
		let cancel = CancelToken::new();
		RequestExecCtx {
			exec_ctx: self.tasks.exec_ctx(cancel.clone()),
			_cancel_on_drop: CancelOnDrop(cancel),
		}
	}
}

impl<S, E> Clone for RuntimeHost<S, E> {
	fn clone(&self) -> Self {
		Self {
			state: self.state.clone(),
			tasks: self.tasks.clone(),
			document: self.document.clone(),
			routes: self.routes.clone(),
			assets: self.assets.clone(),
			request_body_limit: self.request_body_limit,
		}
	}
}

impl<S, E, B> tower_service::Service<Request<B>> for RuntimeHost<S, E>
where
	S: Send + Sync + 'static,
	E: ViewErrorClientMsg + Send + Sync + 'static,
	B: Body + Send + 'static,
	B::Data: Buf + Send + 'static,
	B::Error:
		std::fmt::Display + Send + Sync + 'static + Into<Box<dyn std::error::Error + Send + Sync>>,
{
	type Response = Response<Full<Bytes>>;
	type Error = std::convert::Infallible;
	type Future = Pin<
		Box<
			dyn std::future::Future<Output = Result<Self::Response, std::convert::Infallible>>
				+ Send
				+ 'static,
		>,
	>;

	fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), std::convert::Infallible>> {
		Poll::Ready(Ok(()))
	}

	fn call(&mut self, request: Request<B>) -> Self::Future {
		let host = self.clone();
		Box::pin(async move {
			let head_request = request.method() == Method::HEAD;
			let response = match collect_http_request(request, host.request_body_limit).await {
				Ok(request) => host
					.handle_request_with_body(request)
					.await
					.unwrap_or_else(|_| internal_server_error_response()),
				Err(RequestBodyError::PayloadTooLarge) => payload_too_large_response(),
				Err(RequestBodyError::Read(_)) => internal_server_error_response(),
			};
			let response = if head_request {
				head_response_without_body(response)
			} else {
				response
			};
			Ok(bytes_response_to_full(response))
		})
	}
}

fn default_runtime_assets(cfg: &Config) -> Option<RuntimeAssets> {
	if is_build() {
		return None;
	}

	let static_out = static_out_dir(config_path(&cfg.root_dir, &cfg.dist_dir));
	if is_dev() {
		return Some(RuntimeAssets::live_fs(static_out, ManifestMode::Dev));
	}
	Some(RuntimeAssets::cached_fs(static_out, ManifestMode::Prod))
}

fn config_path(root_dir: &Path, path: &str) -> PathBuf {
	let path = PathBuf::from(path);
	if path.is_absolute() {
		return path.clean();
	}
	root_dir.join(path).clean()
}

fn validate_runtime_config(cfg: &Config) -> Result<(), String> {
	if cfg.root_dir.as_os_str().is_empty() {
		return Err("root_dir cannot be empty".to_owned());
	}
	if !cfg.root_dir.is_absolute() {
		return Err("root_dir must be absolute".to_owned());
	}
	if !cfg.root_dir.exists() {
		return Err(format!(
			"root dir does not exist: {}",
			cfg.root_dir.display()
		));
	}
	if !cfg.root_dir.is_dir() {
		return Err(format!(
			"root dir is not a directory: {}",
			cfg.root_dir.display()
		));
	}
	let root_dir = cfg.root_dir.clean();
	let dist_dir = config_path(&root_dir, &cfg.dist_dir);
	if !dist_dir.starts_with(&root_dir) {
		return Err("dist_dir must be inside root_dir".to_owned());
	}
	Ok(())
}

fn raw_request(request: Request<Bytes>) -> RawRequest {
	let (parts, body) = request.into_parts();
	RawRequest::with_extensions(
		parts.method,
		parts.uri,
		parts.headers,
		body,
		parts.extensions,
	)
}

struct CancelOnDrop(CancelToken);

impl Drop for CancelOnDrop {
	fn drop(&mut self) {
		self.0.cancel();
	}
}

struct RequestExecCtx<E> {
	exec_ctx: vorma_tasks::ExecCtx<E>,
	_cancel_on_drop: CancelOnDrop,
}

async fn collect_http_request<B>(
	request: Request<B>,
	limit: usize,
) -> Result<Request<Bytes>, RequestBodyError>
where
	B: Body + Send + 'static,
	B::Data: Buf + Send + 'static,
	B::Error:
		std::fmt::Display + Send + Sync + 'static + Into<Box<dyn std::error::Error + Send + Sync>>,
{
	let (parts, body) = request.into_parts();
	let bytes = match Limited::new(body, limit).collect().await {
		Ok(collected) => collected.to_bytes(),
		Err(error) if error.is::<LengthLimitError>() => {
			return Err(RequestBodyError::PayloadTooLarge);
		}
		Err(error) => {
			return Err(RequestBodyError::Read(error.to_string()));
		}
	};
	Ok(Request::from_parts(parts, bytes))
}

#[derive(Debug, Eq, PartialEq)]
enum RequestBodyError {
	PayloadTooLarge,
	Read(String),
}

fn bytes_response_to_full(response: Response<Bytes>) -> Response<Full<Bytes>> {
	let (parts, body) = response.into_parts();
	Response::from_parts(parts, Full::new(body))
}

fn payload_too_large_response() -> Response<Bytes> {
	plain_text_response(
		StatusCode::PAYLOAD_TOO_LARGE,
		Bytes::from_static(b"Payload Too Large\n"),
	)
}

fn dev_health_check_response(request: &Request<Bytes>) -> Result<Option<Response<Bytes>>, String> {
	if !is_dev() || request.method() != Method::GET || request.uri().path() != "/.vorma/healthz" {
		return Ok(None);
	}
	Response::builder()
		.status(StatusCode::OK)
		.body(Bytes::from_static(b"ok"))
		.map(Some)
		.map_err(|err| err.to_string())
}

fn empty_response(status: StatusCode) -> Result<Response<Bytes>, String> {
	Response::builder()
		.status(status)
		.body(Bytes::new())
		.map_err(|err| err.to_string())
}

fn method_not_allowed_response(allow: &str) -> Result<Response<Bytes>, String> {
	let mut response = plain_text_response(
		StatusCode::METHOD_NOT_ALLOWED,
		Bytes::from_static(b"Method Not Allowed\n"),
	);
	response.headers_mut().insert(
		ALLOW,
		HeaderValue::from_str(allow).map_err(|err| err.to_string())?,
	);
	Ok(response)
}

fn public_asset_found_response(
	body: Bytes,
	content_length: u64,
	cache_control: &'static str,
	content_type: String,
) -> Result<Response<Bytes>, String> {
	let mut response = Response::new(body);
	response
		.headers_mut()
		.insert(CACHE_CONTROL, HeaderValue::from_static(cache_control));
	response.headers_mut().insert(
		CONTENT_TYPE,
		HeaderValue::from_str(&content_type).map_err(|err| err.to_string())?,
	);
	response.headers_mut().insert(
		CONTENT_LENGTH,
		HeaderValue::from_str(&content_length.to_string()).map_err(|err| err.to_string())?,
	);
	Ok(response)
}

fn allow_header_value(methods: &std::collections::BTreeSet<String>) -> String {
	methods
		.iter()
		.map(String::as_str)
		.collect::<Vec<_>>()
		.join(", ")
}

fn head_response_without_body(response: Response<Bytes>) -> Response<Bytes> {
	let (mut parts, body) = response.into_parts();
	if !parts.headers.contains_key(CONTENT_LENGTH)
		&& !parts.headers.contains_key(http::header::TRANSFER_ENCODING)
	{
		let value = HeaderValue::from_str(&body.len().to_string())
			.expect("usize length should be a valid header value");
		parts.headers.insert(CONTENT_LENGTH, value);
	}
	Response::from_parts(parts, Bytes::new())
}

fn request_path_is_under_mount_root(path: &str, mount_root: &str) -> bool {
	let without_trailing = mount_root.trim_end_matches('/');
	path == without_trailing || path.starts_with(mount_root)
}

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