vorma 0.86.0-pre.5

Rust-first full-stack web framework: typed views and resources, generated TypeScript contracts, and a Vite-integrated frontend.
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
//! What handlers return: a render, a response, a continuation, a redirect, or
//! a failure, each built with its HTTP metadata. Every handler returns
//! `Result<Success, TerminalOutcome<DeclaredError>>`.
//!
//! Each value is a builder. Methods that start with `set_` replace an earlier
//! value of the same kind, such as a status, a header's values, or a cookie
//! with the same name, path, and domain. Methods that start with `add_` add to
//! what came before, such as another value of a header or another head element.
//! Header changes apply in call order.
//!
//! Each value also has methods that read what its builder methods collected,
//! such as `status`, `headers`, `cookies`, and `output`, so that a test can
//! call a handler and check the value that it returned. A reading method
//! reports this one value's contributions. The response of a request merges
//! the contributions of every handler that ran for it.

use std::any::{TypeId, type_name};
use std::error::Error as StdError;
use std::fmt;

use cookie::Cookie;
use http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
use primitives_rs::tsgen::{FieldDef, FieldPresence, TsGen, TypeDef, TypeRef, TypeRegistry};
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};

use crate::document::{AttrValue, DocumentParts, HeadEl, HeadItem};
use crate::pattern::{ApiPatternParams, ViewPatternParams};

/// One header change. Changes apply in call order, after the changes of
/// earlier results.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum HeaderChange {
	/// Replaces every value that the header has so far with this value.
	Set {
		name: HeaderName,
		value: HeaderValue,
	},
	/// Adds another field line with this value and keeps the header's existing
	/// values.
	Add {
		name: HeaderName,
		value: HeaderValue,
	},
}

impl HeaderChange {
	/// Applies the change to the headers that earlier changes produced. An
	/// added value is its own field line, so values that cannot share one
	/// line stay intact.
	pub(crate) fn apply_to(&self, headers: &mut HeaderMap) {
		match self {
			Self::Set { name, value } => {
				headers.insert(name.clone(), value.clone());
			}
			Self::Add { name, value } => {
				headers.append(name.clone(), value.clone());
			}
		}
	}
}

/// The HTTP metadata that one result's builder methods collect.
#[derive(Clone, Debug, Default)]
pub(crate) struct ResponseMeta {
	pub(crate) status: Option<StatusCode>,
	pub(crate) header_changes: Vec<HeaderChange>,
	/// The cookies in call order, without a cookie that a later call replaced.
	pub(crate) cookies: Vec<Cookie<'static>>,
	/// The first invalid header that a builder method received. Vorma reports
	/// it when it reads the result.
	pub(crate) invalid_header: Option<String>,
	/// The first invalid cookie that a builder method received. Vorma reports
	/// it when it reads the result.
	pub(crate) invalid_cookie: Option<String>,
}

impl ResponseMeta {
	fn change_header<Name, Value>(
		&mut self,
		name: Name,
		value: Value,
		create_header_change_fn: fn(HeaderName, HeaderValue) -> HeaderChange,
	) where
		Name: TryInto<HeaderName>,
		<Name as TryInto<HeaderName>>::Error: Into<http::Error>,
		Value: TryInto<HeaderValue>,
		<Value as TryInto<HeaderValue>>::Error: Into<http::Error>,
	{
		let name = match name.try_into() {
			Ok(name) => name,
			Err(error) => return self.record_invalid_header(format!("{}", error.into())),
		};
		match value.try_into() {
			Ok(value) => self
				.header_changes
				.push(create_header_change_fn(name, value)),
			Err(error) => {
				self.record_invalid_header(format!("header {name}: {}", error.into()));
			}
		}
	}

	fn record_invalid_header(&mut self, problem: String) {
		if self.invalid_header.is_none() {
			self.invalid_header = Some(problem);
		}
	}

	fn headers(&self) -> HeaderMap {
		let mut headers = HeaderMap::new();
		for change in &self.header_changes {
			change.apply_to(&mut headers);
		}
		headers
	}

	fn set_cookie(&mut self, cookie: Cookie<'static>) {
		match check_cookie(&cookie) {
			Ok(()) => {
				self.cookies
					.retain(|existing| !is_same_cookie(existing, &cookie));
				self.cookies.push(cookie);
			}
			Err(problem) => {
				if self.invalid_cookie.is_none() {
					self.invalid_cookie = Some(problem);
				}
			}
		}
	}
}

/// Whether a browser treats two cookies as the same cookie: it identifies a
/// cookie by its name, path, and domain. A leading dot and letter case in a
/// domain do not distinguish cookies, and a cookie without a `Path` or without
/// a `Domain` is distinct from a cookie that has one.
pub(crate) fn is_same_cookie(first: &Cookie<'_>, second: &Cookie<'_>) -> bool {
	first.name() == second.name()
		&& first.path() == second.path()
		&& match (first.domain(), second.domain()) {
			(Some(first_domain), Some(second_domain)) => {
				first_domain.eq_ignore_ascii_case(second_domain)
			}
			(None, None) => true,
			_ => false,
		}
}

/// Whether `byte` is an RFC 7230 `tchar`, a character of an HTTP token.
fn is_token_byte(byte: u8) -> bool {
	byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte)
}

/// Whether `byte` is an RFC 6265 `cookie-octet`: printable ASCII except
/// space, `"`, `,`, `;`, and `\`.
fn is_cookie_value_byte(byte: u8) -> bool {
	matches!(byte, 0x21 | 0x23..=0x2B | 0x2D..=0x3A | 0x3C..=0x5B | 0x5D..=0x7E)
}

/// Checks that Vorma can write the cookie as given. The message never
/// contains the value.
fn check_cookie(cookie: &Cookie<'_>) -> Result<(), String> {
	let name = cookie.name();
	if name.is_empty() || !name.bytes().all(is_token_byte) {
		return Err(format!(
			"the cookie name {name:?} is not a valid HTTP token"
		));
	}
	if !cookie.value().bytes().all(is_cookie_value_byte) {
		return Err(format!(
			"the value of the cookie {name:?} has a character outside RFC 6265's cookie characters; \
			 encode the value before setting it"
		));
	}
	for (attr, setting) in [("Path", cookie.path()), ("Domain", cookie.domain())] {
		if setting.is_some_and(|text| {
			text.chars()
				.any(|character| character == ';' || character.is_control())
		}) {
			return Err(format!(
				"the {attr} of the cookie {name:?} contains ';' or a control character"
			));
		}
	}
	if HeaderValue::from_str(&cookie.to_string()).is_err() {
		return Err(format!(
			"the cookie {name:?} cannot be written as a header value"
		));
	}
	Ok(())
}

/// Defines the header and cookie methods that every result value has.
macro_rules! response_meta_methods {
	($type:ty $(, $generic:ident)?) => {
		impl$(<$generic>)? $type {
			/// Replaces the header's values with this value. The name and value
			/// accept anything that converts to a header name or value, as
			/// `http`'s response builder does. An invalid name or value makes the
			/// result invalid: Vorma reports it and answers 500.
			pub fn set_header<Name, Value>(mut self, name: Name, value: Value) -> Self
			where
				Name: TryInto<HeaderName>,
				<Name as TryInto<HeaderName>>::Error: Into<http::Error>,
				Value: TryInto<HeaderValue>,
				<Value as TryInto<HeaderValue>>::Error: Into<http::Error>,
			{
				self.meta
					.change_header(name, value, |name, value| HeaderChange::Set { name, value });
				self
			}

			/// Adds a value to the header and keeps its existing values. The name
			/// and value convert as they do for `set_header`.
			pub fn add_header<Name, Value>(mut self, name: Name, value: Value) -> Self
			where
				Name: TryInto<HeaderName>,
				<Name as TryInto<HeaderName>>::Error: Into<http::Error>,
				Value: TryInto<HeaderValue>,
				<Value as TryInto<HeaderValue>>::Error: Into<http::Error>,
			{
				self.meta
					.change_header(name, value, |name, value| HeaderChange::Add { name, value });
				self
			}

			/// Sets a cookie, which replaces an earlier cookie with the same name,
			/// path, and domain, as a browser identifies a cookie. A cookie with
			/// another path or domain does not replace it, and the response
			/// carries both. A `cookie::CookieBuilder` converts into a cookie.
			///
			/// Vorma writes the cookie's name and value exactly as given, without
			/// percent-encoding. The name must be a valid HTTP token, and the
			/// value must contain only RFC 6265's cookie characters: printable
			/// ASCII except space, `"`, `,`, `;`, and `\`. The `Path` and
			/// `Domain` must not contain `;` or a control character. Otherwise the
			/// result is invalid: Vorma reports it and answers 500. An application that
			/// needs other characters in a value, such as binary data, encodes the
			/// value itself, for example as base64url, and decodes it when it reads
			/// the cookie.
			pub fn set_cookie(mut self, cookie: impl Into<Cookie<'static>>) -> Self {
				self.meta.set_cookie(cookie.into());
				self
			}

			/// The headers that this value's `set_header` and `add_header` calls
			/// produce, applied in call order to no headers. Cookies are not
			/// among them: [`cookies`](Self::cookies) returns those. A header
			/// with an invalid name or value is not among them either.
			pub fn headers(&self) -> HeaderMap {
				self.meta.headers()
			}

			/// The cookies that this value sets, in the order of the `set_cookie`
			/// calls, without a cookie that a later call replaced and without an
			/// invalid cookie.
			pub fn cookies(&self) -> &[Cookie<'static>] {
				&self.meta.cookies
			}
		}
	};
}

/// Defines the status method of every result value except redirects, whose
/// status is their redirect status.
macro_rules! status_method {
	($type:ty $(, $generic:ident)?) => {
		impl$(<$generic>)? $type {
			/// Sets the response status, which replaces an earlier status. A
			/// success must have a 2xx status; any other status makes the result
			/// invalid: Vorma reports it and answers 500. A page response always
			/// has a body, so 204 and 205 are also invalid for a result that
			/// contributes to a page. A redirect has its redirect status, and
			/// [`NotModified`] answers 304.
			pub fn set_status(mut self, status: StatusCode) -> Self {
				self.meta.status = Some(status);
				self
			}

			/// The status that `set_status` set, or `None` when this value sets
			/// no status.
			pub fn status(&self) -> Option<StatusCode> {
				self.meta.status
			}
		}
	};
}

/// Defines the document methods of the results that render a page.
macro_rules! document_methods {
	($type:ty $(, $generic:ident)?) => {
		impl$(<$generic>)? $type {
			/// Sets an attribute of `html`, which replaces an earlier value of
			/// that attribute.
			pub fn set_html_attr(mut self, name: impl Into<String>, value: impl Into<AttrValue>) -> Self {
				self.document.html_attrs.push((name.into(), value.into()));
				self
			}

			/// Sets an attribute of `head`, which replaces an earlier value of
			/// that attribute.
			pub fn set_head_attr(mut self, name: impl Into<String>, value: impl Into<AttrValue>) -> Self {
				self.document.head_attrs.push((name.into(), value.into()));
				self
			}

			/// Sets an attribute of `body`, which replaces an earlier value of
			/// that attribute, such as an ancestor loader's `class`.
			pub fn set_body_attr(mut self, name: impl Into<String>, value: impl Into<AttrValue>) -> Self {
				self.document.body_attrs.push((name.into(), value.into()));
				self
			}

			/// Adds an element to the head. Vorma places and deduplicates head
			/// elements: a later element with the same identity, such as a later
			/// `<title>`, replaces an earlier one, as the identity's
			/// [`crate::HeadReplacement`] says. A later `remove_head_el` call
			/// removes the element.
			pub fn add_head_el(mut self, el: HeadEl) -> Self {
				self.document.head_items.push(HeadItem::El(el));
				self
			}

			/// Removes the head elements with the identity that `el` names that
			/// were placed before this call, by earlier contributions or by
			/// earlier calls of this handler: the one element of a per-element
			/// identity, or the whole set of a per-contribution identity. A
			/// later element with the identity, including one that this handler
			/// adds after the call, takes the same position. A removal of an
			/// identity that nothing placed does nothing.
			///
			/// `el` carries its tag and the attributes that its identity
			/// names, without children, and matches a built-in identity or a
			/// [`crate::HeadDedupeRule`] by the rules of `add_head_el`. Any
			/// other `el` is an invalid server result. Raw HTML and elements
			/// that match no identity cannot be removed; an application
			/// declares a rule to make an element removable.
			pub fn remove_head_el(mut self, el: HeadEl) -> Self {
				self.document.head_items.push(HeadItem::Remove(el));
				self
			}

			/// Adds markup to the head unchanged, without escaping or
			/// deduplication.
			pub fn add_head_dangerous_raw_html(mut self, html: impl Into<String>) -> Self {
				self.document.head_items.push(HeadItem::DangerousRawHtml(html.into()));
				self
			}

			/// The settings of `html`'s attributes, in the order of the
			/// `set_html_attr` calls. A later setting of an attribute replaces an
			/// earlier one when Vorma renders the document.
			pub fn html_attrs(&self) -> &[(String, AttrValue)] {
				&self.document.html_attrs
			}

			/// The settings of `head`'s attributes, in the order of the
			/// `set_head_attr` calls.
			pub fn head_attrs(&self) -> &[(String, AttrValue)] {
				&self.document.head_attrs
			}

			/// The settings of `body`'s attributes, in the order of the
			/// `set_body_attr` calls.
			pub fn body_attrs(&self) -> &[(String, AttrValue)] {
				&self.document.body_attrs
			}

			/// What this value contributes to the head, in call order: each
			/// added element, each removal, and each piece of raw markup.
			pub fn head_items(&self) -> &[HeadItem] {
				&self.document.head_items
			}
		}
	};
}

/// A view loader's successful result: the view's output with its document
/// contributions and HTTP metadata.
#[derive(Debug)]
#[must_use]
pub struct Render<Output> {
	pub(crate) output: Output,
	pub(crate) document: DocumentParts,
	pub(crate) meta: ResponseMeta,
}

impl<Output> Render<Output> {
	/// Renders the view with this output. `()` means that the loader has no
	/// output.
	pub fn new(output: Output) -> Self {
		Self {
			output,
			document: DocumentParts::default(),
			meta: ResponseMeta::default(),
		}
	}
}

impl<Output> Render<Output> {
	/// The view's output.
	pub fn output(&self) -> &Output {
		&self.output
	}
}

impl<Output> From<Output> for Render<Output> {
	/// Renders the view with the output and no other metadata.
	fn from(output: Output) -> Self {
		Self::new(output)
	}
}

status_method!(Render<Output>, Output);
response_meta_methods!(Render<Output>, Output);
document_methods!(Render<Output>, Output);

/// An API endpoint's successful result: its output with HTTP metadata.
#[derive(Debug)]
#[must_use]
pub struct Respond<Output> {
	pub(crate) output: Output,
	pub(crate) meta: ResponseMeta,
}

impl<Output> Respond<Output> {
	/// Responds with this output. `()` means that the endpoint has no output,
	/// and the response has no body.
	pub fn new(output: Output) -> Self {
		Self {
			output,
			meta: ResponseMeta::default(),
		}
	}
}

impl<Output> Respond<Output> {
	/// The endpoint's output.
	pub fn output(&self) -> &Output {
		&self.output
	}
}

status_method!(Respond<Output>, Output);
response_meta_methods!(Respond<Output>, Output);

/// Task middleware's successful result: the request continues with these
/// contributions. Document contributions apply to page responses.
#[derive(Debug, Default)]
#[must_use]
pub struct Continue {
	pub(crate) document: DocumentParts,
	pub(crate) meta: ResponseMeta,
}

impl Continue {
	/// Lets the request continue without contributions.
	pub fn new() -> Self {
		Self::default()
	}
}

impl From<()> for Continue {
	/// Lets the request continue without contributions.
	fn from((): ()) -> Self {
		Self::new()
	}
}

status_method!(Continue);
response_meta_methods!(Continue);
document_methods!(Continue);

/// A redirect status.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RedirectStatus {
	/// 302 Found.
	Found,
	/// 303 See Other.
	SeeOther,
	/// 307 Temporary Redirect.
	TemporaryRedirect,
	/// 308 Permanent Redirect.
	PermanentRedirect,
}

impl RedirectStatus {
	pub(crate) fn to_status_code(self) -> StatusCode {
		match self {
			Self::Found => StatusCode::FOUND,
			Self::SeeOther => StatusCode::SEE_OTHER,
			Self::TemporaryRedirect => StatusCode::TEMPORARY_REDIRECT,
			Self::PermanentRedirect => StatusCode::PERMANENT_REDIRECT,
		}
	}
}

/// A page given by one of the application's view patterns, with its params, its
/// search input, and a hash. Two targets are equal when they have the same
/// pattern, params, search input, and hash.
#[derive(Clone, Debug, PartialEq)]
#[must_use]
pub struct PageTarget {
	pub(crate) pattern: &'static str,
	pub(crate) params: Vec<(String, String)>,
	pub(crate) splat_values: Vec<String>,
	pub(crate) input: Option<Result<serde_json::Value, String>>,
	pub(crate) hash: Option<String>,
}

impl PageTarget {
	/// Targets the page of the view pattern that these params belong to.
	pub fn new<Params: ViewPatternParams>(params: Params) -> Self {
		let decoded_match = params.into_decoded_match();
		Self {
			pattern: Params::PATTERN,
			params: decoded_match.params,
			splat_values: decoded_match.splat_values,
			input: None,
			hash: None,
		}
	}

	/// Sets the search input. Each loader at or above the pattern that
	/// declares search input reads its own fields from it. Input that cannot
	/// be serialized makes the result invalid: Vorma reports it and answers
	/// 500.
	pub fn set_input<Input: Serialize>(mut self, input: &Input) -> Self {
		self.input = Some(serde_json::to_value(input).map_err(|error| error.to_string()));
		self
	}

	/// Sets the URL fragment, written without its leading `#`.
	pub fn set_hash(mut self, hash: impl Into<String>) -> Self {
		self.hash = Some(hash.into());
		self
	}
}

/// An endpoint given by one of the application's API patterns, with its
/// params and, for a follow-up `GET` request, its search input. Two targets
/// are equal when they have the same pattern, params, and search input.
#[derive(Clone, Debug, PartialEq)]
#[must_use]
pub struct ApiEndpointTarget {
	pub(crate) pattern: &'static str,
	pub(crate) params: Vec<(String, String)>,
	pub(crate) splat_values: Vec<String>,
	pub(crate) input: Option<Result<serde_json::Value, String>>,
}

impl ApiEndpointTarget {
	/// Targets the endpoints of the pattern that these params belong to. The
	/// redirect's status and the request's method decide which method's
	/// endpoint receives the follow-up request.
	pub fn new<Params: ApiPatternParams>(params: Params) -> Self {
		let decoded_match = params.into_decoded_match();
		Self {
			pattern: Params::PATTERN,
			params: decoded_match.params,
			splat_values: decoded_match.splat_values,
			input: None,
		}
	}

	/// Sets search input for a follow-up `GET` request. Input that cannot be
	/// serialized makes the result invalid: Vorma reports it and answers 500.
	pub fn set_input<Input: Serialize>(mut self, input: &Input) -> Self {
		self.input = Some(serde_json::to_value(input).map_err(|error| error.to_string()));
		self
	}
}

/// Where a navigation redirect sends the browser.
#[derive(Clone, Debug, PartialEq)]
pub enum RedirectTarget {
	/// A URL that Vorma does not declare, used as the `location` unchanged.
	Url(String),
	/// A page given by one of the application's view patterns.
	Page(PageTarget),
}

impl From<PageTarget> for RedirectTarget {
	fn from(target: PageTarget) -> Self {
		Self::Page(target)
	}
}

/// A navigation redirect: it sends the user to a page or a URL. The Vorma
/// client receives it as a client redirect when it needs one; any other
/// caller receives a 3xx response. View loaders, API endpoints, and task
/// middleware can return it.
#[derive(Debug)]
#[must_use]
pub struct Redirect {
	pub(crate) target: RedirectTarget,
	pub(crate) status: RedirectStatus,
	pub(crate) meta: ResponseMeta,
}

impl Redirect {
	/// Redirects to a page or a URL with this redirect status.
	pub fn new(target: impl Into<RedirectTarget>, status: RedirectStatus) -> Self {
		Self {
			target: target.into(),
			status,
			meta: ResponseMeta::default(),
		}
	}
}

impl Redirect {
	/// Where the redirect sends the user.
	pub fn target(&self) -> &RedirectTarget {
		&self.target
	}

	/// The redirect status.
	pub fn status(&self) -> RedirectStatus {
		self.status
	}
}

response_meta_methods!(Redirect);

/// An endpoint redirect: an endpoint call receives another of the
/// application's endpoints' responses. It is a 3xx response that the caller's
/// HTTP client follows. A 303 response turns any method except `HEAD` into
/// `GET`, a 302 response turns `POST` into `GET`, and 307 and 308 responses
/// keep the method and the body. The target endpoint must have the redirecting
/// endpoint's output and declared-error types, and its input type when the
/// body is sent again; otherwise the result is invalid.
#[derive(Debug)]
#[must_use]
pub struct ApiEndpointRedirect {
	pub(crate) target: ApiEndpointTarget,
	pub(crate) status: RedirectStatus,
	pub(crate) meta: ResponseMeta,
}

impl ApiEndpointRedirect {
	/// Redirects the call to an endpoint with this redirect status.
	pub fn new(target: ApiEndpointTarget, status: RedirectStatus) -> Self {
		Self {
			target,
			status,
			meta: ResponseMeta::default(),
		}
	}
}

impl ApiEndpointRedirect {
	/// The endpoint that answers the call.
	pub fn target(&self) -> &ApiEndpointTarget {
		&self.target
	}

	/// The redirect status.
	pub fn status(&self) -> RedirectStatus {
		self.status
	}
}

response_meta_methods!(ApiEndpointRedirect);

/// A `304 Not Modified` answer from a `GET` API endpoint. Vorma sends it
/// without a body, with its protocol headers and the headers and cookies set
/// on it. Any other endpoint method makes the result invalid: Vorma reports it
/// and answers 500.
///
/// Its purpose is a handler that checks a cheap validator, such as a version
/// number, before it does its work. The handler compares the request's
/// `If-None-Match` header with the validator, using the `headers` crate's
/// typed `IfNoneMatch`, and returns `NotModified::new()` with the validator's
/// `ETag` header when they match. The browser's HTTP cache then answers the
/// call with its stored body.
///
/// An `ETag` computed from a response body belongs in the host server's
/// middleware, which wraps Vorma's handler. Such a middleware saves transfer
/// only, because the handler has already done its work.
#[derive(Debug, Default)]
#[must_use]
pub struct NotModified {
	pub(crate) meta: ResponseMeta,
}

impl NotModified {
	/// Answers 304 without a body.
	pub fn new() -> Self {
		Self::default()
	}
}

response_meta_methods!(NotModified);

/// An API endpoint's successful result. A handler returns
/// `Ok(value.into())`, where the value is a [`Respond`], an
/// [`ApiEndpointRedirect`], a [`NotModified`], or the endpoint's output. A
/// navigation redirect is a [`TerminalOutcome`].
#[derive(Debug)]
pub enum ApiEndpointResult<Output> {
	/// Responds with output.
	Respond(Respond<Output>),
	/// Answers with another of the application's endpoints instead.
	Redirect(ApiEndpointRedirect),
	/// Answers 304 without a body.
	NotModified(NotModified),
}

impl<Output: Serialize> From<Output> for ApiEndpointResult<Output> {
	/// Responds with the output and no other metadata.
	fn from(output: Output) -> Self {
		Self::Respond(Respond::new(output))
	}
}

impl<Output> From<Respond<Output>> for ApiEndpointResult<Output> {
	fn from(respond: Respond<Output>) -> Self {
		Self::Respond(respond)
	}
}

impl<Output> From<ApiEndpointRedirect> for ApiEndpointResult<Output> {
	fn from(redirect: ApiEndpointRedirect) -> Self {
		Self::Redirect(redirect)
	}
}

impl<Output> From<NotModified> for ApiEndpointResult<Output> {
	fn from(not_modified: NotModified) -> Self {
		Self::NotModified(not_modified)
	}
}

/// The declared public error type of a handler that declares none.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum NoDeclaredError {}

impl TsGen for NoDeclaredError {
	fn type_ref() -> TypeRef {
		TypeRef::Union(Vec::new())
	}
}

/// The fixed public failure of task middleware. The browser receives its
/// `client_msg`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RequestRejected {
	/// Text that the browser receives.
	pub client_msg: String,
}

impl Serialize for RequestRejected {
	fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
		let mut state = serializer.serialize_struct("RequestRejected", 1)?;
		state.serialize_field("client_msg", &self.client_msg)?;
		state.end()
	}
}

const REQUEST_REJECTED_TYPE_KEY: &str = "vorma::RequestRejected";

impl TsGen for RequestRejected {
	fn type_ref() -> TypeRef {
		TypeRef::named_with_key(REQUEST_REJECTED_TYPE_KEY, "RequestRejected")
	}

	fn collect_type_defs(registry: &mut TypeRegistry) -> primitives_rs::tsgen::Result<()> {
		registry.try_define(TypeDef::new(
			REQUEST_REJECTED_TYPE_KEY,
			"RequestRejected",
			TypeRef::Object(vec![FieldDef::new(
				"client_msg",
				TypeRef::String,
				FieldPresence::Required,
			)]),
		))?;
		Ok(())
	}
}

/// A handler failure: an expected outcome such as "not found", or an error
/// that the application does not declare. It states its HTTP status, and its
/// headers and cookies apply.
///
/// [`Failure::from_declared`] sends the declared error's serialized form to
/// the browser; it is an outcome that the application chose, so Vorma logs it
/// at the debug level. [`Failure::from_undeclared`] has no public payload;
/// Vorma logs it at the error level with its cause chain.
///
/// `?` converts a failure into a [`TerminalOutcome`], and it converts any error
/// that implements [`std::error::Error`], `Send`, and `Sync` into an undeclared
/// failure with status 500. A boxed error or an `anyhow::Error` does not
/// implement [`std::error::Error`], so it needs [`Failure::from_undeclared`].
/// `?` on a value of the handler's declared error type is an invalid server
/// result, because it would hide the error from the browser: Vorma reports it
/// and answers 500. Use [`Failure::from_declared`] for a declared error.
///
/// # Document contributions
///
/// A failure has the document methods of [`Render`] and [`Continue`]. They
/// apply when the failure ends a page request, from a view loader or from task
/// middleware, and they have no effect when it ends an API endpoint's request.
///
/// The page then renders the application's error boundary with the document
/// that the positions contributed in order: the contributions of the positions
/// above the failing one remain, then the failure's contributions merge after
/// them, and the positions after the failing one contribute nothing. A failing
/// handler overrides or unsets what it does not want from the positions above
/// it, with [`AttrValue::Unset`] for an attribute or with a head element that
/// replaces an earlier one, such as another `<title>`.
#[must_use]
pub struct Failure<DeclaredError> {
	pub(crate) kind: FailureKind<DeclaredError>,
	pub(crate) status: StatusCode,
	pub(crate) document: DocumentParts,
	pub(crate) meta: ResponseMeta,
}

pub(crate) enum FailureKind<DeclaredError> {
	Declared(DeclaredError),
	Undeclared(Box<dyn StdError + Send + Sync>),
	/// The failure stands for an invalid server result, with the problem.
	Invalid(String),
}

impl<DeclaredError> Failure<DeclaredError> {
	fn new(kind: FailureKind<DeclaredError>, status: StatusCode) -> Self {
		Self {
			kind,
			status,
			document: DocumentParts::default(),
			meta: ResponseMeta::default(),
		}
	}

	/// A failure with a declared error and its status, which must be a 4xx or
	/// 5xx status; any other status makes the result invalid: Vorma reports it
	/// and answers 500. The browser receives the error's serialized form.
	pub fn from_declared(error: DeclaredError, status: StatusCode) -> Self {
		Self::new(FailureKind::Declared(error), status)
	}

	/// A failure without a public payload, with its status, which must be a
	/// 4xx or 5xx status; any other status makes the result invalid: Vorma
	/// reports it and answers 500.
	pub fn from_undeclared(
		error: impl Into<Box<dyn StdError + Send + Sync>>,
		status: StatusCode,
	) -> Self {
		Self::new(FailureKind::Undeclared(error.into()), status)
	}
}

impl<DeclaredError> Failure<DeclaredError> {
	/// The failure's status.
	pub fn status(&self) -> StatusCode {
		self.status
	}

	/// The declared error of a failure that [`Failure::from_declared`] made,
	/// or `None` for any other failure.
	pub fn declared_error(&self) -> Option<&DeclaredError> {
		match &self.kind {
			FailureKind::Declared(error) => Some(error),
			FailureKind::Undeclared(_) | FailureKind::Invalid(_) => None,
		}
	}

	/// The error of a failure that [`Failure::from_undeclared`] or `?` made,
	/// or `None` for any other failure.
	pub fn undeclared_error(&self) -> Option<&(dyn StdError + Send + Sync + 'static)> {
		match &self.kind {
			FailureKind::Undeclared(error) => Some(error.as_ref()),
			FailureKind::Declared(_) | FailureKind::Invalid(_) => None,
		}
	}
}

response_meta_methods!(Failure<DeclaredError>, DeclaredError);
document_methods!(Failure<DeclaredError>, DeclaredError);

impl<DeclaredError> fmt::Debug for Failure<DeclaredError> {
	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		let kind = match &self.kind {
			FailureKind::Declared(_) => "declared",
			FailureKind::Undeclared(_) => "undeclared",
			FailureKind::Invalid(_) => "invalid",
		};
		formatter
			.debug_struct("Failure")
			.field("kind", &kind)
			.field("status", &self.status)
			.field("meta", &self.meta)
			.finish()
	}
}

/// What ends a handler without its success value: a navigation redirect or a
/// failure. Every handler kind returns `Result<Success, TerminalOutcome<DeclaredError>>`,
/// so a helper that is generic over `DeclaredError` can redirect or fail in any
/// handler.
///
/// `?` converts a [`Redirect`], a [`Failure`], or any error that implements
/// [`std::error::Error`], `Send`, and `Sync`; the error becomes an undeclared
/// failure with status 500. `?` on a value of the declared error type is an
/// invalid server result; see [`Failure`]. A helper that uses `?` on standard
/// errors names the bound `DeclaredError: 'static`.
///
/// A redirect or a failure that a handler returns directly is written
/// `Err(value.into())`. The variants hold boxed values so that a handler's
/// `Result` stays small.
#[derive(Debug)]
#[must_use]
pub enum TerminalOutcome<DeclaredError> {
	/// Sends the user to a page or a URL instead of finishing the handler.
	Redirect(Box<Redirect>),
	/// Ends the handler with a failure.
	Failure(Box<Failure<DeclaredError>>),
}

impl<DeclaredError> From<Redirect> for TerminalOutcome<DeclaredError> {
	fn from(redirect: Redirect) -> Self {
		Self::Redirect(Box::new(redirect))
	}
}

impl<DeclaredError> From<Failure<DeclaredError>> for TerminalOutcome<DeclaredError> {
	fn from(failure: Failure<DeclaredError>) -> Self {
		Self::Failure(Box::new(failure))
	}
}

impl<DeclaredError: 'static, Error> From<Error> for TerminalOutcome<DeclaredError>
where
	Error: StdError + Send + Sync + 'static,
{
	fn from(error: Error) -> Self {
		if TypeId::of::<Error>() == TypeId::of::<DeclaredError>() {
			let name = type_name::<Error>();
			return Self::from(Failure::new(
				FailureKind::Invalid(format!(
					"`?` converted a value of the declared error type {name}; return \
					 `Failure::from_declared(error, status)` instead"
				)),
				StatusCode::INTERNAL_SERVER_ERROR,
			));
		}
		Self::from(Failure::from_undeclared(
			error,
			StatusCode::INTERNAL_SERVER_ERROR,
		))
	}
}