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
use std::collections::BTreeMap;
use std::fs;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use http::HeaderName;
use http::header::{LOCATION, SET_COOKIE};
use http_body_util::BodyExt;
use serde_json::json;
use tokio::sync::{Notify, oneshot};

use super::*;
use crate::api::FormData;
use crate::constants::X_VORMA_CLIENT_BUILD_ID;
use crate::core::{Middleware, Middlewares, Resource, ResourceKind, Resources, View, Views};
use crate::manifest::{ClientModule, Manifest};
use crate::mux::{InputError, InputParser};
use crate::r#static::PUBLIC_ASSET_CACHE_CONTROL;

fn temp_dist_dir(name: &str) -> PathBuf {
	let nanos = SystemTime::now()
		.duration_since(UNIX_EPOCH)
		.unwrap()
		.as_nanos();
	let root = std::env::temp_dir().join(format!(
		"vorma-runtime-host-{name}-{}-{nanos}",
		std::process::id()
	));
	fs::create_dir_all(root.join(".vorma/static/public")).unwrap();
	root
}

fn cfg(dist_dir: &Path) -> Config {
	Config {
		root_dir: dist_dir.to_path_buf(),
		dist_dir: ".".to_owned(),
		path_config: crate::config::PathConfig {
			public_static_base: "/static/".to_owned(),
			api_base: "/api/".to_owned(),
		},
		..Config::default()
	}
}

fn app(
	config: Config,
	views: Views<(), &'static str>,
	resources: Resources<(), &'static str>,
	middlewares: Middlewares<(), &'static str>,
	document: DocumentBuilder,
) -> App<(), &'static str> {
	let Config {
		root_dir,
		server_config,
		dist_dir,
		path_config,
		frontend_config,
		ts_gen_config,
		dev_watch_config,
	} = config;
	App::from_app_config(crate::AppConfig {
		root_dir,
		server_config,
		dist_dir,
		path_config,
		frontend_config,
		ts_gen_config,
		dev_watch_config,
		state: (),
		views,
		resources,
		middlewares,
		tasks_options: vorma_tasks::TasksOptions::default(),
		document,
		request_body_limit: crate::DEFAULT_REQUEST_BODY_LIMIT,
	})
}

fn default_app(
	config: Config,
	views: Views<(), &'static str>,
	resources: Resources<(), &'static str>,
	middlewares: Middlewares<(), &'static str>,
) -> App<(), &'static str> {
	app(
		config,
		views,
		resources,
		middlewares,
		DocumentBuilder::default(),
	)
}

fn runtime_host(
	dist_dir: &Path,
	views: Views<(), &'static str>,
	resources: Resources<(), &'static str>,
	middlewares: Middlewares<(), &'static str>,
) -> RuntimeHost<(), &'static str> {
	RuntimeHost::new(default_app(cfg(dist_dir), views, resources, middlewares)).unwrap()
}

fn runtime_host_with_document(
	dist_dir: &Path,
	views: Views<(), &'static str>,
	resources: Resources<(), &'static str>,
	middlewares: Middlewares<(), &'static str>,
	document: DocumentBuilder,
) -> RuntimeHost<(), &'static str> {
	RuntimeHost::new(app(cfg(dist_dir), views, resources, middlewares, document)).unwrap()
}

fn empty_request(method: Method, uri: &str) -> Request<Bytes> {
	request_with_body(method, uri, Bytes::new())
}

struct DropSignal(Arc<Mutex<Option<oneshot::Sender<()>>>>);

impl Drop for DropSignal {
	fn drop(&mut self) {
		if let Some(tx) = self.0.lock().unwrap().take() {
			let _ = tx.send(());
		}
	}
}

fn request_with_body(method: Method, uri: &str, body: Bytes) -> Request<Bytes> {
	Request::builder()
		.method(method)
		.uri(uri)
		.body(body)
		.unwrap()
}

fn manifest() -> Manifest {
	Manifest {
		vorma_version: "0.1.0".to_owned(),
		public_static_base_path: "/static/".to_owned(),
		api_mount_root: "/api/".to_owned(),
		ui_variant: "react".to_owned(),
		root_document_shell_hash: "shell".to_owned(),
		public_filepaths: vec![
			"/static/app.css".to_owned(),
			"/static/favicon.ico".to_owned(),
		],
		public_filemap: BTreeMap::from([
			("app.css".to_owned(), "/static/app.css".to_owned()),
			("favicon.ico".to_owned(), "/static/favicon.ico".to_owned()),
		]),
		client_entry: ClientModule {
			url: "/static/entry.js".to_owned(),
			..ClientModule::default()
		},
		..Manifest::default()
	}
}

fn write_manifest(dist_dir: &Path) {
	fs::write(
		dist_dir.join(".vorma/static/vorma.manifest.prod.json"),
		serde_json::to_vec(&manifest()).unwrap(),
	)
	.unwrap();
}

#[test]
fn vercel_runtime_static_out_dir_uses_current_dir_manifest_when_configured_manifest_is_missing() {
	let configured_root = temp_dist_dir("vercel-configured-root-missing-manifest");
	let current_root = temp_dist_dir("vercel-current-root-with-manifest");
	write_manifest(&current_root);
	let config = cfg(&configured_root);
	let configured_static_out = configured_root.join(".vorma/static");

	let got = vercel_runtime_static_out_dir_from_current_root(
		&config,
		&configured_static_out,
		ManifestMode::Prod,
		current_root.clone(),
	)
	.unwrap();

	assert_eq!(got, current_root.join(".vorma/static").clean());
	fs::remove_dir_all(configured_root).unwrap();
	fs::remove_dir_all(current_root).unwrap();
}

#[test]
fn vercel_runtime_static_out_dir_reports_configured_and_current_manifest_paths_when_missing() {
	let configured_root = temp_dist_dir("vercel-configured-root-without-manifest");
	let current_root = temp_dist_dir("vercel-current-root-without-manifest");
	let config = cfg(&configured_root);
	let configured_static_out = configured_root.join(".vorma/static");

	let error = vercel_runtime_static_out_dir_from_current_root(
		&config,
		&configured_static_out,
		ManifestMode::Prod,
		current_root.clone(),
	)
	.unwrap_err();

	assert!(
		error.contains(
			&configured_root
				.join(".vorma/static/vorma.manifest.prod.json")
				.display()
				.to_string()
		)
	);
	assert!(
		error.contains(
			&current_root
				.join(".vorma/static/vorma.manifest.prod.json")
				.display()
				.to_string()
		)
	);
	fs::remove_dir_all(configured_root).unwrap();
	fs::remove_dir_all(current_root).unwrap();
}

fn write_manifest_with_api_mount_root(dist_dir: &Path, api_mount_root: &str) -> Manifest {
	let mut manifest = manifest();
	manifest.api_mount_root = api_mount_root.to_owned();
	fs::write(
		dist_dir.join(".vorma/static/vorma.manifest.prod.json"),
		serde_json::to_vec(&manifest).unwrap(),
	)
	.unwrap();
	manifest
}

fn manifest_with_view_assets() -> Manifest {
	Manifest {
		critical_css: "body { color: black; }".to_owned(),
		client_entry: ClientModule {
			url: "/static/entry.js".to_owned(),
			dep_urls: vec![
				"/static/entry.js".to_owned(),
				"/static/shared.js".to_owned(),
			],
			css_bundle_urls: vec![
				"/static/entry.css".to_owned(),
				"/static/shared.css".to_owned(),
			],
		},
		client_views: BTreeMap::from([(
			"/items/:id".to_owned(),
			ClientModule {
				url: "/static/items.js".to_owned(),
				dep_urls: vec![
					"/static/shared.js".to_owned(),
					"/static/items.js".to_owned(),
				],
				css_bundle_urls: vec![
					"/static/shared.css".to_owned(),
					"/static/items.css".to_owned(),
					"/static/entry.css".to_owned(),
				],
			},
		)]),
		search_schemas: BTreeMap::from([("/items/:id".to_owned(), serde_json::Value::Null)]),
		..manifest()
	}
}

fn write_view_manifest(dist_dir: &Path) {
	let manifest = manifest_with_view_assets();
	fs::write(
		dist_dir.join(".vorma/static/vorma.manifest.prod.json"),
		serde_json::to_vec(&manifest).unwrap(),
	)
	.unwrap();
}

fn write_root_base_view_manifest(dist_dir: &Path) {
	let mut manifest = manifest_with_view_assets();
	manifest.public_static_base_path = "/".to_owned();
	fs::write(
		dist_dir.join(".vorma/static/vorma.manifest.prod.json"),
		serde_json::to_vec(&manifest).unwrap(),
	)
	.unwrap();
}

fn write_nested_view_manifest(dist_dir: &Path) {
	let mut manifest = manifest_with_view_assets();
	manifest.client_views.insert(
		"/items".to_owned(),
		ClientModule {
			url: "/static/items-parent.js".to_owned(),
			..ClientModule::default()
		},
	);
	manifest
		.search_schemas
		.insert("/items".to_owned(), serde_json::Value::Null);
	fs::write(
		dist_dir.join(".vorma/static/vorma.manifest.prod.json"),
		serde_json::to_vec(&manifest).unwrap(),
	)
	.unwrap();
}

fn host(dist_dir: &Path) -> RuntimeHost<(), &'static str> {
	let views = Views::new();
	let mut resources = Resources::new();
	resources.push(Resource::new(
		Method::GET,
		"/ping",
		Some(ResourceKind::Query),
		InputParser::<()>::default_input(),
		|_: crate::core::ResourceCtx<(), &'static str, ()>| async { Ok(json!({"pong": true})) },
	));
	let middlewares = Middlewares::new();
	runtime_host(dist_dir, views, resources, middlewares)
}

fn middleware_host(dist_dir: &Path) -> RuntimeHost<(), &'static str> {
	let views = Views::new();
	let mut resources = Resources::new();
	let mut middlewares = Middlewares::new();
	middlewares.push(Middleware::new(|ctx| async move {
		ctx.response().set_header(
			HeaderName::from_static("x-vorma-global-mw"),
			HeaderValue::from_static("1"),
		);
		Ok(())
	}));
	middlewares.push(Middleware::new(|ctx| async move {
		if ctx.request().method() != Method::GET {
			return Ok(());
		}
		ctx.response().set_header(
			HeaderName::from_static("x-vorma-method-mw"),
			HeaderValue::from_static("1"),
		);
		Ok(())
	}));
	middlewares.push(Middleware::new(|ctx| async move {
		if ctx.matched_pattern() != "/ping" {
			return Ok(());
		}
		ctx.response().set_header(
			HeaderName::from_static("x-vorma-pattern-mw"),
			HeaderValue::from_static("1"),
		);
		Ok(())
	}));
	let ping = Resource::new(
		Method::GET,
		"/ping",
		Some(ResourceKind::Query),
		InputParser::<()>::default_input(),
		|_: crate::core::ResourceCtx<(), &'static str, ()>| async { Ok(json!({"pong": true})) },
	);
	resources.push(ping);
	runtime_host(dist_dir, views, resources, middlewares)
}

fn static_json_resource(
	ctx: crate::core::ErasedRequestCtx<(), &'static str>,
) -> crate::core::ErasedRouteFuture<&'static str> {
	crate::core::run_static_resource::<(), &'static str, serde_json::Value, (), serde_json::Value>(
		ctx,
		static_json_api_handler,
	)
}

fn static_json_api_handler(
	_: crate::core::ResourceCtx<(), &'static str, serde_json::Value>,
) -> crate::core::RouteFuture<serde_json::Value, &'static str> {
	Box::pin(async { panic!("bad JSON should fail before the API handler runs") })
}

fn static_form_data_resource(
	ctx: crate::core::ErasedRequestCtx<(), &'static str>,
) -> crate::core::ErasedRouteFuture<&'static str> {
	crate::core::run_static_resource::<(), &'static str, FormData, (), serde_json::Value>(
		ctx,
		static_form_data_api_handler,
	)
}

fn static_form_data_api_handler(
	ctx: crate::core::ResourceCtx<(), &'static str, FormData>,
) -> crate::core::RouteFuture<serde_json::Value, &'static str> {
	Box::pin(async move {
		Ok(json!({
			"name": ctx.input().text("name"),
			"tags": ctx.input().texts("tag").collect::<Vec<_>>(),
			"content_type": ctx.input().content_type(),
		}))
	})
}

fn view_host(dist_dir: &Path) -> RuntimeHost<(), &'static str> {
	view_host_with_document(dist_dir, DocumentBuilder::default())
}

fn view_host_with_document(
	dist_dir: &Path,
	document: DocumentBuilder,
) -> RuntimeHost<(), &'static str> {
	let mut views = Views::new();
	views.push(View::new(
		"/items/:id",
		"items.tsx",
		InputParser::<()>::default_input(),
		|ctx: crate::core::ViewCtx<(), &'static str, ()>| async move {
			Ok(json!({
				"id": ctx.param("id"),
				"filter": ctx.request().query().unwrap_or_default(),
			}))
		},
	));
	runtime_host_with_document(
		dist_dir,
		views,
		Resources::new(),
		Middlewares::new(),
		document,
	)
}

fn custom_document() -> DocumentBuilder {
	DocumentBuilder::new(|ctx| async move {
		let favicon = ctx.public_url("favicon.ico")?;
		let mut document = crate::Document::new();
		document.html().data("shell", "custom");
		document.body().data("body", "custom");
		document.head().title("Default Title");
		document
			.head()
			.description("Default description from document");
		let head = document.head();
		head.link([head.rel("icon").into(), head.href(favicon).into()]);
		document.push_body_prefix(Element {
			tag: "div".to_owned(),
			attributes: BTreeMap::from([("data-document-prefix".to_owned(), "1".to_owned())]),
			text_content: "Document prefix".to_owned(),
			..Element::default()
		});
		Ok(document)
	})
}

fn assert_substrings_in_order(body: &str, expected: &[&str]) {
	let mut last_idx = Option::None;
	for substring in expected {
		let idx = body
			.find(substring)
			.unwrap_or_else(|| panic!("expected body to contain {substring:?}"));
		if let Some(last_idx) = last_idx {
			assert!(
				idx > last_idx,
				"expected {substring:?} after previous substring"
			);
		}
		last_idx = Some(idx);
	}
}

mod document_and_view_shell;
mod method_and_request_boundaries;
mod middleware_and_effects;
mod public_assets_and_resources;
mod service_body_and_context;