leptoskit_rpc 0.3.0

The app's operations: leptos server functions with retries and error classification, queries and mutations that run on the database, one client for every platform, and publishing it all to generated clients.
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
//! The RPC specification: what `#[api]` registers, and how it is exported.
//!
//! Every function annotated with [`api`](crate::api) registers an
//! [`ApiFnDescriptor`] in a process-wide registry when the crate is compiled
//! for the server (the `ssr` feature). [`collect`] walks that registry and
//! produces an [`ApiSpec`]: routes, HTTP encodings, docs, and a JSON Schema
//! for every argument and return value, generated by [`schemars`] so `serde`
//! attributes are honored exactly. The spec leaves the server in one of two
//! ways:
//!
//! - [`export_if_requested`], called first thing in `main`, writes the spec to
//!   the file named by the `LEPTOSKIT_RPC_SPEC_OUT` environment variable and
//!   exits. This is how `leptoskit rpc spec` and `leptoskit rpc generate`
//!   extract it: they build the server binary and run it with that variable
//!   set, so the spec always matches the code that was just compiled;
//! - [`openapi_router`] (feature `axum`) serves the public functions as an
//!   OpenAPI 3.1 document for Swagger UI, Redoc, or any OpenAPI toolchain.
//!
//! ```no_run
//! # #[cfg(feature = "ssr")]
//! fn main() {
//! 	leptoskit_rpc::spec::export_if_requested();
//! 	// ...start the server as usual
//! }
//! # #[cfg(not(feature = "ssr"))]
//! # fn main() {}
//! ```

use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;

use leptos::server_fn::ContentType;
use leptos::server_fn::Http;
use leptos::server_fn::ServerFn;
use leptos::server_fn::codec::Encoding;
use leptos::server_fn::error::FromServerFnError;
pub use leptoskit_rpc_codegen::ApiChannel;
pub use leptoskit_rpc_codegen::ApiFunction;
pub use leptoskit_rpc_codegen::ApiKind;
pub use leptoskit_rpc_codegen::ApiParam;
pub use leptoskit_rpc_codegen::ApiSpec;
pub use leptoskit_rpc_codegen::HttpInput;
pub use leptoskit_rpc_codegen::HttpOutput;
pub use leptoskit_rpc_codegen::spec::SPEC_DESCRIPTION_ENV;
pub use leptoskit_rpc_codegen::spec::SPEC_OUT_ENV;
pub use leptoskit_rpc_codegen::spec::SPEC_SERVERS_ENV;
pub use leptoskit_rpc_codegen::spec::SPEC_TITLE_ENV;
use leptoskit_rpc_codegen::spec::SPEC_VERSION;
pub use leptoskit_rpc_codegen::spec::SPEC_VERSION_ENV;
pub use schemars;
use schemars::Schema;
use schemars::SchemaGenerator;
use schemars::generate::SchemaSettings;

/// One `#[api]` function, as the macro registers it.
///
/// Every field is a compile-time constant or a function pointer so the
/// descriptor can live in a `static`; schemas are produced lazily, through a
/// shared [`SchemaGenerator`], when [`collect`] runs.
#[derive(Debug)]
pub struct ApiFnDescriptor {
	/// The operation name; the function name unless `#[api(name = "...")]`.
	pub name: &'static str,
	/// What kind of operation it is: a `#[server]` function is a
	/// [`ApiKind::Call`].
	pub kind: ApiKind,
	/// `module_path!()` at the definition.
	pub module_path: &'static str,
	/// The struct `#[server]` generated for the function.
	pub struct_name: &'static str,
	/// The doc comment, `///` markers stripped.
	pub docs: &'static str,
	/// The route, from `ServerFn::PATH`.
	pub path: &'static str,
	/// The HTTP method of the input encoding.
	pub method: http::Method,
	/// The request content type.
	pub input_content_type: &'static str,
	/// The success response content type.
	pub output_content_type: &'static str,
	/// The error response content type.
	pub error_content_type: &'static str,
	/// The arguments, in declaration order.
	pub params: &'static [ApiParamDescriptor],
	/// Produces the schema of the success value.
	pub output_schema: fn(&mut SchemaGenerator) -> Schema,
	/// `#[api(internal)]`.
	pub internal: bool,
	/// Whether the function carries `#[deprecated]`.
	pub deprecated: bool,
	/// `#[api(tag = "...")]`, in order.
	pub tags: &'static [&'static str],
	/// `#[api(scope = ...)]`: every scope a third-party app's access token
	/// must carry to call the function. Empty when only the app's own
	/// sessions may call it.
	pub scopes: &'static [&'static str],
}

/// One argument of an [`ApiFnDescriptor`].
#[derive(Debug)]
pub struct ApiParamDescriptor {
	/// The argument name, as it appears on the wire.
	pub name: &'static str,
	/// The argument's doc: its own doc comment, or else its entry in the
	/// `# Arguments` section of the function's doc comment.
	pub docs: &'static str,
	/// Produces the schema of the argument type.
	pub schema: fn(&mut SchemaGenerator) -> Schema,
	/// Whether the argument must be sent; `false` for `#[server(default)]`.
	pub required: bool,
}

inventory::collect!(ApiFnDescriptor);

/// One `#[api]` channel, as the macro registers it.
#[derive(Debug)]
pub struct ApiChannelDescriptor {
	/// The channel's name, `Channel::NAME`.
	pub name: &'static str,
	/// `module_path!()` at the definition.
	pub module_path: &'static str,
	/// The join argument struct's name.
	pub struct_name: &'static str,
	/// The doc comment, `///` markers stripped.
	pub docs: &'static str,
	/// The join arguments' wire names, in declaration order.
	pub fields: &'static [&'static str],
	/// Produces the schema of the join arguments.
	pub args_schema: fn(&mut SchemaGenerator) -> Schema,
	/// Produces the schema of a signal.
	pub message_schema: fn(&mut SchemaGenerator) -> Schema,
	/// Produces the schema of a member's presence.
	pub presence_schema: fn(&mut SchemaGenerator) -> Schema,
	/// `#[api(internal)]`.
	pub internal: bool,
	/// Whether the struct carries `#[deprecated]`.
	pub deprecated: bool,
	/// `#[api(tag = "...")]`, in order.
	pub tags: &'static [&'static str],
}

inventory::collect!(ApiChannelDescriptor);

/// The method queries and mutations are called with.
pub const OPERATION_METHOD: http::Method = http::Method::POST;

/// What the HTTP protocol of a server function looks like on the wire.
///
/// Implemented for every `Http<Input, Output>` protocol. `#[api]` rejects
/// websocket protocols and the streaming and multipart encodings by name, at
/// compile time, before this trait is involved; any other protocol has no
/// implementation, so a server build fails with the message below.
#[diagnostic::on_unimplemented(
	message = "`#[api]` only publishes server functions with an HTTP protocol, and `{Self}` is \
	           not one",
	label = "not an `Http<Input, Output>` protocol",
	note = "remove #[api] from this function, or give it an HTTP encoding such as `PostUrl`, \
	        `GetUrl`, or `Json`"
)]
pub trait HttpProtocolInfo {
	/// The request method.
	const METHOD: http::Method;
	/// The request content type.
	const INPUT_CONTENT_TYPE: &'static str;
	/// The success response content type.
	const OUTPUT_CONTENT_TYPE: &'static str;
}

impl<Input: Encoding, Output: Encoding> HttpProtocolInfo for Http<Input, Output> {
	const INPUT_CONTENT_TYPE: &'static str = Input::CONTENT_TYPE;
	const METHOD: http::Method = Input::METHOD;
	const OUTPUT_CONTENT_TYPE: &'static str = Output::CONTENT_TYPE;
}

/// The HTTP method a server function's requests use.
pub const fn method_of<T: ServerFn>() -> http::Method
where
	T::Protocol: HttpProtocolInfo,
{
	<T::Protocol as HttpProtocolInfo>::METHOD
}

/// The request content type of a server function.
pub const fn input_content_type_of<T: ServerFn>() -> &'static str
where
	T::Protocol: HttpProtocolInfo,
{
	<T::Protocol as HttpProtocolInfo>::INPUT_CONTENT_TYPE
}

/// The success response content type of a server function.
pub const fn output_content_type_of<T: ServerFn>() -> &'static str
where
	T::Protocol: HttpProtocolInfo,
{
	<T::Protocol as HttpProtocolInfo>::OUTPUT_CONTENT_TYPE
}

/// The error response content type of a server function.
pub const fn error_content_type_of<T: ServerFn>() -> &'static str {
	<<T::Error as FromServerFnError>::Encoder as ContentType>::CONTENT_TYPE
}

/// The metadata an exported spec carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpecOptions {
	/// The RPC title.
	pub title: String,
	/// The RPC version.
	pub version: String,
	/// A longer description.
	pub description: Option<String>,
	/// The base URLs the RPC is served from.
	pub servers: Vec<String>,
	/// Where the live socket is served, relative to each server URL;
	/// `/live` unless the app nests `Live::router` elsewhere.
	pub live_path: String,
}

impl SpecOptions {
	/// Options with a title and version.
	pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
		Self {
			title: title.into(),
			version: version.into(),
			description: None,
			servers: Vec::new(),
			live_path: leptoskit_rpc_codegen::DEFAULT_LIVE_PATH.to_owned(),
		}
	}

	/// Options from the `LEPTOSKIT_RPC_SPEC_*` environment variables the CLI
	/// sets, falling back to a generic title and version `0.0.0`.
	#[must_use]
	pub fn from_env() -> Self {
		Self::from_lookup(|name| std::env::var(name).ok())
	}

	/// [`SpecOptions::from_env`] over any variable source; empty values count
	/// as unset.
	pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Self {
		let read = |name: &str| lookup(name).filter(|value| !value.is_empty());
		Self {
			title: read(SPEC_TITLE_ENV).unwrap_or_else(|| "RPC".to_owned()),
			version: read(SPEC_VERSION_ENV).unwrap_or_else(|| "0.0.0".to_owned()),
			description: read(SPEC_DESCRIPTION_ENV),
			servers: read(SPEC_SERVERS_ENV)
				.map(|servers| {
					servers
						.split(',')
						.map(str::trim)
						.filter(|server| !server.is_empty())
						.map(ToOwned::to_owned)
						.collect()
				})
				.unwrap_or_default(),
			live_path: leptoskit_rpc_codegen::DEFAULT_LIVE_PATH.to_owned(),
		}
	}

	/// Sets the description.
	#[must_use]
	pub fn with_description(mut self, description: impl Into<String>) -> Self {
		self.description = Some(description.into());
		self
	}

	/// Sets where the live socket is served, such as `/realtime/live`.
	#[must_use]
	pub fn with_live_path(mut self, path: impl Into<String>) -> Self {
		self.live_path = path.into();
		self
	}

	/// Adds a server URL.
	#[must_use]
	pub fn with_server(mut self, url: impl Into<String>) -> Self {
		self.servers.push(url.into());
		self
	}
}

/// Every registered descriptor, sorted by name then module path.
pub fn descriptors() -> Vec<&'static ApiFnDescriptor> {
	let mut descriptors: Vec<&'static ApiFnDescriptor> =
		inventory::iter::<ApiFnDescriptor>().collect();
	descriptors.sort_by(|a, b| {
		a.name
			.cmp(b.name)
			.then_with(|| a.module_path.cmp(b.module_path))
	});
	descriptors
}

/// Every registered channel descriptor, sorted by name then module path.
pub fn channel_descriptors() -> Vec<&'static ApiChannelDescriptor> {
	let mut descriptors: Vec<&'static ApiChannelDescriptor> =
		inventory::iter::<ApiChannelDescriptor>().collect();
	descriptors.sort_by(|a, b| {
		a.name
			.cmp(b.name)
			.then_with(|| a.module_path.cmp(b.module_path))
	});
	descriptors
}

/// The scopes `#[api(scope = ...)]` requires of the function served at
/// `method` and `path`: `None` when no `#[api]` function is served there,
/// and an empty slice when one is but declares no scope.
///
/// A server that accepts third-party access tokens, such as
/// `leptoskit_idp`'s layer, lets such a token reach only the routes this
/// names with at least one scope, and only when the token carries every one
/// of them.
pub fn scopes_for(method: &http::Method, path: &str) -> Option<&'static [&'static str]> {
	inventory::iter::<ApiFnDescriptor>()
		.find(|descriptor| descriptor.method == *method && descriptor.path == path)
		.map(|descriptor| descriptor.scopes)
}

/// Builds the spec from every registered `#[api]` function, internal ones
/// included; filter with [`ApiSpec::public`] for publication.
///
/// # Errors
///
/// Returns [`SpecError::DuplicateName`] when two functions share a name and
/// [`SpecError::DuplicateRoute`] when two share a route and method: generated
/// clients could not tell them apart, and the server would silently route one
/// of them to the other's handler.
pub fn collect(options: &SpecOptions) -> Result<ApiSpec, SpecError> {
	collect_with_channels(&descriptors(), &channel_descriptors(), options)
}

/// Checks that every registered `#[api]` function has its own name and its
/// own route, without building any schemas.
///
/// leptos keeps one handler per route and method and silently drops the
/// others, so two functions on one route leave one of them unreachable.
/// [`export_if_requested`] runs this on every start, which is where a clash
/// surfaces first; call it yourself when `main` does not.
///
/// # Errors
///
/// As [`collect`].
pub fn check() -> Result<(), SpecError> {
	check_from(&descriptors())
}

/// [`check`] over an explicit set of descriptors.
///
/// # Errors
///
/// As [`collect`].
pub fn check_from(descriptors: &[&ApiFnDescriptor]) -> Result<(), SpecError> {
	let mut by_name: HashMap<&str, &ApiFnDescriptor> = HashMap::new();
	let mut by_route: HashMap<(&str, &str), &ApiFnDescriptor> = HashMap::new();
	for descriptor in descriptors.iter().copied() {
		if let Some(existing) = by_name.insert(descriptor.name, descriptor) {
			return Err(SpecError::DuplicateName {
				name: descriptor.name.to_owned(),
				first: existing.module_path.to_owned(),
				second: descriptor.module_path.to_owned(),
			});
		}
		let route = (descriptor.path, descriptor.method.as_str());
		if let Some(existing) = by_route.insert(route, descriptor) {
			return Err(SpecError::DuplicateRoute {
				method: descriptor.method.to_string(),
				path: descriptor.path.to_owned(),
				first: existing.name.to_owned(),
				second: descriptor.name.to_owned(),
			});
		}
	}
	Ok(())
}

/// [`collect`] over an explicit set of descriptors, in the order given.
///
/// # Errors
///
/// As [`collect`].
pub fn collect_from(
	descriptors: &[&ApiFnDescriptor],
	options: &SpecOptions,
) -> Result<ApiSpec, SpecError> {
	collect_with_channels(descriptors, &[], options)
}

/// [`collect_from`] with channels too, in the order given.
///
/// # Errors
///
/// As [`collect`], and [`SpecError::DuplicateName`] when two channels share
/// a name.
pub fn collect_with_channels(
	descriptors: &[&ApiFnDescriptor],
	channels: &[&ApiChannelDescriptor],
	options: &SpecOptions,
) -> Result<ApiSpec, SpecError> {
	check_from(descriptors)?;
	let mut channel_names: HashMap<&str, &ApiChannelDescriptor> = HashMap::new();

	for channel in channels.iter().copied() {
		if let Some(existing) = channel_names.insert(channel.name, channel) {
			return Err(SpecError::DuplicateName {
				name: channel.name.to_owned(),
				first: existing.module_path.to_owned(),
				second: channel.module_path.to_owned(),
			});
		}
	}

	let mut generator = SchemaSettings::draft2020_12()
		.with(|settings| {
			settings.definitions_path = "/components/schemas".into();
			settings.meta_schema = None;
		})
		.into_generator();
	let functions = descriptors
		.iter()
		.map(|descriptor| {
			let params = descriptor
				.params
				.iter()
				.map(|param| {
					ApiParam {
						name: param.name.to_owned(),
						docs: param.docs.to_owned(),
						schema: (param.schema)(&mut generator).to_value(),
						required: param.required,
					}
				})
				.collect();
			let output_schema = (descriptor.output_schema)(&mut generator).to_value();
			ApiFunction {
				name: descriptor.name.to_owned(),
				kind: descriptor.kind,
				module_path: descriptor.module_path.to_owned(),
				struct_name: descriptor.struct_name.to_owned(),
				docs: descriptor.docs.to_owned(),
				path: descriptor.path.to_owned(),
				method: descriptor.method.to_string(),
				input: classify_input(&descriptor.method, descriptor.input_content_type),
				output: classify_output(descriptor.output_content_type),
				error_content_type: descriptor.error_content_type.to_owned(),
				params,
				output_schema,
				internal: descriptor.internal,
				deprecated: descriptor.deprecated,
				tags: descriptor
					.tags
					.iter()
					.map(|tag| (*tag).to_owned())
					.collect(),
				scopes: descriptor
					.scopes
					.iter()
					.map(|scope| (*scope).to_owned())
					.collect(),
			}
		})
		.collect();
	let channels = channels
		.iter()
		.map(|channel| {
			ApiChannel {
				name: channel.name.to_owned(),
				module_path: channel.module_path.to_owned(),
				struct_name: channel.struct_name.to_owned(),
				docs: channel.docs.to_owned(),
				fields: channel
					.fields
					.iter()
					.map(|field| (*field).to_owned())
					.collect(),
				args_schema: (channel.args_schema)(&mut generator).to_value(),
				message_schema: (channel.message_schema)(&mut generator).to_value(),
				presence_schema: (channel.presence_schema)(&mut generator).to_value(),
				internal: channel.internal,
				deprecated: channel.deprecated,
				tags: channel.tags.iter().map(|tag| (*tag).to_owned()).collect(),
			}
		})
		.collect();
	let schemas: BTreeMap<String, serde_json::Value> =
		generator.take_definitions(false).into_iter().collect();

	Ok(ApiSpec {
		leptoskit_rpc_spec: SPEC_VERSION,
		title: options.title.clone(),
		version: options.version.clone(),
		description: options.description.clone(),
		servers: options.servers.clone(),
		functions,
		channels,
		live_path: options.live_path.clone(),
		schemas: schemas.into_iter().collect(),
	})
}

/// Maps a request method and content type to the encoding a client must use.
fn classify_input(method: &http::Method, content_type: &str) -> HttpInput {
	match content_type {
		// `GetUrl` and `DeleteUrl` read their arguments from the query string;
		// the other URL encodings read them from the body.
		"application/x-www-form-urlencoded"
			if *method == http::Method::GET || *method == http::Method::DELETE =>
		{
			HttpInput::Query
		}
		"application/x-www-form-urlencoded" => HttpInput::Form,
		"application/json" => HttpInput::Json,
		other => {
			HttpInput::Other {
				content_type: other.to_owned(),
			}
		}
	}
}

/// Maps a response content type to the decoding a client must use.
fn classify_output(content_type: &str) -> HttpOutput {
	match content_type {
		"application/json" => HttpOutput::Json,
		other => {
			HttpOutput::Other {
				content_type: other.to_owned(),
			}
		}
	}
}

/// Writes the spec as JSON to `path`, creating parent directories.
///
/// # Errors
///
/// Returns an error when collection fails or the file cannot be written.
pub fn write_to(options: &SpecOptions, path: &Path) -> Result<ApiSpec, SpecError> {
	let spec = collect(options)?;
	let json = spec.to_json().map_err(SpecError::Codegen)?;
	if let Some(parent) = path.parent()
		&& !parent.as_os_str().is_empty()
	{
		std::fs::create_dir_all(parent).map_err(|source| {
			SpecError::Write {
				path: parent.to_path_buf(),
				source,
			}
		})?;
	}
	std::fs::write(path, json).map_err(|source| {
		SpecError::Write {
			path: path.to_path_buf(),
			source,
		}
	})?;
	Ok(spec)
}

/// Writes the spec when the CLI asks for it, then exits the process.
///
/// Call this first in `main`, before anything that binds ports or opens
/// databases. When `LEPTOSKIT_RPC_SPEC_OUT` is unset it [checks](check) that
/// no two `#[api]` functions share a name or a route and returns, and the
/// server starts as usual; a clash exits with status `1` and the pair on
/// stderr, because leptos would silently answer both with one function. When
/// the variable is set — `leptoskit rpc spec` and `leptoskit rpc generate`
/// set it — the spec is written there and the process exits with status `0`,
/// or `1` with the error on stderr.
///
/// Title, version, description, and servers come from the
/// `LEPTOSKIT_RPC_SPEC_*` variables the CLI sets from `leptoskit.toml`; use
/// [`export_if_requested_with`] to supply them from code instead.
pub fn export_if_requested() {
	export_if_requested_with(&SpecOptions::from_env());
}

/// [`export_if_requested`] with explicit metadata.
pub fn export_if_requested_with(options: &SpecOptions) {
	let Some(outcome) = maybe_export_from(|name| std::env::var(name).ok(), options) else {
		if let Err(error) = check() {
			eprintln!("error: {}", with_causes(&error));
			std::process::exit(1);
		}
		return;
	};
	match outcome {
		Ok(path) => {
			eprintln!("wrote the RPC specification to {}", path.display());
			std::process::exit(0);
		}
		Err(error) => {
			eprintln!(
				"error: could not export the RPC specification: {}",
				with_causes(&error)
			);
			std::process::exit(1);
		}
	}
}

/// An error's message followed by every cause's, `: `-separated.
fn with_causes(error: &dyn std::error::Error) -> String {
	let mut message = error.to_string();
	let mut cause = error.source();
	while let Some(source) = cause {
		message.push_str(": ");
		message.push_str(&source.to_string());
		cause = source.source();
	}
	message
}

/// Writes the spec when `LEPTOSKIT_RPC_SPEC_OUT` is set, without exiting.
///
/// Returns `None` when no export was requested, so callers can decide what
/// to do next.
pub fn maybe_export(options: &SpecOptions) -> Option<Result<PathBuf, SpecError>> {
	maybe_export_from(|name| std::env::var(name).ok(), options)
}

/// [`maybe_export`] over any variable source.
pub fn maybe_export_from(
	lookup: impl Fn(&str) -> Option<String>,
	options: &SpecOptions,
) -> Option<Result<PathBuf, SpecError>> {
	let path = PathBuf::from(lookup(SPEC_OUT_ENV).filter(|path| !path.is_empty())?);
	Some(write_to(options, &path).map(|_| path))
}

/// Serves the spec as OpenAPI: `GET /openapi.json`, `GET /openapi.yaml`, and
/// the live operations as `AsyncAPI` at `GET /asyncapi.json`, relative to
/// wherever the router is nested.
///
/// The spec is collected once, when the router is built, with internal
/// functions left out: this is the publicized document.
///
/// # Errors
///
/// Returns an error when collection fails; see [`collect`].
#[cfg(feature = "axum")]
pub fn openapi_router(options: &SpecOptions) -> Result<axum::Router, SpecError> {
	use axum::http::HeaderValue;
	use axum::http::header;
	use axum::response::IntoResponse;
	use axum::routing::get;

	let spec = collect(options)?.public();
	let json = serde_json::to_string_pretty(&spec.to_openapi()).map_err(|source| {
		SpecError::Codegen(leptoskit_rpc_codegen::CodegenError::Serialize(source))
	})?;
	let yaml = spec.to_openapi_yaml();
	let asyncapi = serde_json::to_string_pretty(&spec.to_asyncapi()).map_err(|source| {
		SpecError::Codegen(leptoskit_rpc_codegen::CodegenError::Serialize(source))
	})?;
	let asyncapi_response = move || {
		let asyncapi = asyncapi.clone();
		async move {
			(
				[(
					header::CONTENT_TYPE,
					HeaderValue::from_static("application/json"),
				)],
				asyncapi,
			)
				.into_response()
		}
	};
	let json_response = move || {
		let json = json.clone();
		async move {
			(
				[(
					header::CONTENT_TYPE,
					HeaderValue::from_static("application/json"),
				)],
				json,
			)
				.into_response()
		}
	};
	let yaml_response = move || {
		let yaml = yaml.clone();
		async move {
			(
				[(
					header::CONTENT_TYPE,
					HeaderValue::from_static("application/yaml"),
				)],
				yaml,
			)
				.into_response()
		}
	};
	Ok(axum::Router::new()
		.route("/openapi.json", get(json_response))
		.route("/openapi.yaml", get(yaml_response))
		.route("/asyncapi.json", get(asyncapi_response)))
}

/// Failures while building or exporting the spec.
#[derive(Debug, thiserror::Error)]
pub enum SpecError {
	/// Two `#[api]` functions share a name.
	#[error(
		"two #[api] functions are named `{name}` (in `{first}` and `{second}`); rename one, or \
		 give one its own `#[api(name = \"...\")]`, which also becomes its route"
	)]
	DuplicateName {
		/// The shared name.
		name: String,
		/// Where the first lives.
		first: String,
		/// Where the second lives.
		second: String,
	},
	/// Two `#[api]` functions share a route.
	#[error(
		"`{first}` and `{second}` both answer `{method} {path}`, so leptos only ever runs one of \
		 them; give one a different `endpoint` or `prefix` in its #[server] attribute"
	)]
	DuplicateRoute {
		/// The HTTP method.
		method: String,
		/// The shared route.
		path: String,
		/// The first function.
		first: String,
		/// The second function.
		second: String,
	},
	/// The spec could not be serialized.
	#[error(transparent)]
	Codegen(leptoskit_rpc_codegen::CodegenError),
	/// The spec file could not be written.
	#[error("could not write {path}")]
	Write {
		/// The path that failed.
		path: PathBuf,
		/// The underlying error, reported as the
		/// [`source`](std::error::Error::source).
		#[source]
		source: std::io::Error,
	},
}