1use axum::{
73 http::StatusCode,
74 response::{IntoResponse, Response},
75 Json,
76};
77use serde::{Deserialize, Serialize};
78use serde_json::json;
79use std::collections::BTreeMap;
80use std::fmt;
81use std::path::PathBuf;
82use thiserror::Error;
83
84pub mod id {
88 use ulid::Ulid;
89
90 #[must_use]
94 pub fn new(prefix: &str) -> String {
95 format!("{prefix}_{}", Ulid::new().to_string().to_lowercase())
96 }
97}
98
99#[derive(Debug, Error)]
103#[non_exhaustive]
104pub enum SlabError {
105 #[error("validation failed on `{field}`: {message}")]
107 Validation {
108 field: String,
110 message: String,
112 },
113
114 #[error("validation failed on {} field(s)", .0.len())]
116 ValidationErrors(BTreeMap<String, Vec<String>>),
117
118 #[error("bad request: {0}")]
120 BadRequest(String),
121
122 #[error("unauthorized: {0}")]
124 Unauthorized(String),
125
126 #[error("forbidden: {0}")]
128 Forbidden(String),
129
130 #[error("not found: {0}")]
132 NotFound(String),
133
134 #[error("conflict: {0}")]
136 Conflict(String),
137
138 #[error("too many requests: {message} (retry after {retry_after_secs}s)")]
142 TooManyRequests {
143 retry_after_secs: u64,
145 message: String,
147 },
148
149 #[error("database error: {0}")]
154 Database(#[from] sqlx::Error),
155
156 #[error("internal error: {0}")]
160 Internal(String),
161}
162
163impl SlabError {
164 #[must_use]
166 pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
167 Self::Validation {
168 field: field.into(),
169 message: message.into(),
170 }
171 }
172
173 #[must_use]
175 pub fn bad_request(msg: impl Into<String>) -> Self {
176 Self::BadRequest(msg.into())
177 }
178
179 #[must_use]
181 pub fn unauthorized(msg: impl Into<String>) -> Self {
182 Self::Unauthorized(msg.into())
183 }
184
185 #[must_use]
187 pub fn forbidden(msg: impl Into<String>) -> Self {
188 Self::Forbidden(msg.into())
189 }
190
191 #[must_use]
193 pub fn not_found(msg: impl Into<String>) -> Self {
194 Self::NotFound(msg.into())
195 }
196
197 #[must_use]
199 pub fn conflict(msg: impl Into<String>) -> Self {
200 Self::Conflict(msg.into())
201 }
202
203 #[must_use]
205 pub fn too_many_requests(retry_after_secs: u64, msg: impl Into<String>) -> Self {
206 Self::TooManyRequests {
207 retry_after_secs,
208 message: msg.into(),
209 }
210 }
211
212 #[must_use]
214 pub fn internal(msg: impl Into<String>) -> Self {
215 Self::Internal(msg.into())
216 }
217
218 #[must_use]
220 pub fn status_code(&self) -> StatusCode {
221 match self {
222 Self::Validation { .. } | Self::ValidationErrors(_) => StatusCode::UNPROCESSABLE_ENTITY,
223 Self::BadRequest(_) => StatusCode::BAD_REQUEST,
224 Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
225 Self::Forbidden(_) => StatusCode::FORBIDDEN,
226 Self::NotFound(_) | Self::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND,
227 Self::Conflict(_) => StatusCode::CONFLICT,
228 Self::TooManyRequests { .. } => StatusCode::TOO_MANY_REQUESTS,
229 Self::Database(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
230 }
231 }
232}
233
234impl IntoResponse for SlabError {
235 fn into_response(self) -> Response {
236 let status = self.status_code();
237 if let Self::TooManyRequests {
238 retry_after_secs,
239 message,
240 } = self
241 {
242 let mut resp = (
243 status,
244 Json(json!({
245 "error": "too_many_requests",
246 "retry_after_secs": retry_after_secs,
247 "message": message,
248 })),
249 )
250 .into_response();
251 if let Ok(val) = http::HeaderValue::from_str(&retry_after_secs.to_string()) {
252 resp.headers_mut().insert(http::header::RETRY_AFTER, val);
253 }
254 return resp;
255 }
256 let body = match &self {
257 Self::Validation { field, message } => json!({
258 "error": "validation_error",
259 "field": field,
260 "message": message,
261 }),
262 Self::ValidationErrors(fields) => json!({
263 "error": "validation_error",
264 "fields": fields,
265 }),
266 Self::Database(sqlx::Error::RowNotFound) => json!({
267 "error": "not_found",
268 "message": "record not found",
269 }),
270 Self::Database(err) => {
271 tracing::error!(error = %err, "database error in slab");
272 json!({
273 "error": "database_error",
274 "message": "internal database error",
275 })
276 }
277 Self::Internal(msg) => {
278 tracing::error!(error = %msg, "internal error in slab");
279 json!({
280 "error": "internal_error",
281 "message": "internal server error",
282 })
283 }
284 other => json!({
285 "error": status.canonical_reason().unwrap_or("error").to_lowercase().replace(' ', "_"),
286 "message": other.to_string(),
287 }),
288 };
289
290 (status, Json(body)).into_response()
291 }
292}
293
294pub type SlabResult<T> = Result<T, SlabError>;
296
297#[derive(Debug, Clone, Default)]
302pub struct Validate {
303 errors: BTreeMap<String, Vec<String>>,
304}
305
306impl Validate {
307 #[must_use]
309 pub fn new() -> Self {
310 Self::default()
311 }
312
313 pub fn required(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
317 if value.trim().is_empty() {
318 self.push(field, "is required");
319 }
320 self
321 }
322
323 pub fn min_len(&mut self, field: impl Into<String>, value: &str, min: usize) -> &mut Self {
325 if value.trim().chars().count() < min {
326 self.push(field, format!("must be at least {min} characters"));
327 }
328 self
329 }
330
331 pub fn max_len(&mut self, field: impl Into<String>, value: &str, max: usize) -> &mut Self {
333 if value.trim().chars().count() > max {
334 self.push(field, format!("must be at most {max} characters"));
335 }
336 self
337 }
338
339 pub fn email(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
344 let trimmed = value.trim();
345 let valid = !trimmed.is_empty()
346 && !trimmed.chars().any(char::is_whitespace)
347 && trimmed.split_once('@').is_some_and(|(local, domain)| {
348 !local.is_empty()
349 && !domain.is_empty()
350 && !domain.contains('@')
351 && domain.contains('.')
352 && !domain.starts_with('.')
353 && !domain.ends_with('.')
354 });
355 if !valid {
356 self.push(field, "must be a valid email address");
357 }
358 self
359 }
360
361 pub fn url(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
363 let trimmed = value.trim();
364 let valid = !trimmed.chars().any(char::is_whitespace)
365 && ((trimmed.starts_with("http://") && trimmed.len() > "http://".len())
366 || (trimmed.starts_with("https://") && trimmed.len() > "https://".len()));
367 if !valid {
368 self.push(field, "must start with http:// or https://");
369 }
370 self
371 }
372
373 pub fn one_of(&mut self, field: impl Into<String>, value: &str, allowed: &[&str]) -> &mut Self {
375 if !allowed.contains(&value) {
376 self.push(field, format!("must be one of: {}", allowed.join(", ")));
377 }
378 self
379 }
380
381 pub fn check(
383 &mut self,
384 field: impl Into<String>,
385 condition: bool,
386 message: impl Into<String>,
387 ) -> &mut Self {
388 if !condition {
389 self.push(field, message);
390 }
391 self
392 }
393
394 pub fn push(&mut self, field: impl Into<String>, message: impl Into<String>) -> &mut Self {
396 self.errors
397 .entry(field.into())
398 .or_default()
399 .push(message.into());
400 self
401 }
402
403 #[must_use]
405 pub fn is_empty(&self) -> bool {
406 self.errors.is_empty()
407 }
408
409 #[must_use]
411 pub fn errors(&self) -> &BTreeMap<String, Vec<String>> {
412 &self.errors
413 }
414
415 pub fn finish(self) -> SlabResult<()> {
417 if self.errors.is_empty() {
418 Ok(())
419 } else {
420 Err(SlabError::ValidationErrors(self.errors))
421 }
422 }
423}
424
425#[derive(Clone, Serialize, Deserialize)]
427pub struct AppConfig {
428 pub app_name: String,
430 pub bind_addr: String,
432 pub database_url: String,
434 pub secret_key: String,
436 pub storage_dir: PathBuf,
438 pub assets_dir: PathBuf,
440 pub job_poll_interval_ms: u64,
442 pub job_concurrency: usize,
444 pub cookie_secure: bool,
446 pub webhooks_live: bool,
448 pub webhooks_allow_local: bool,
450}
451
452impl fmt::Debug for AppConfig {
453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454 f.debug_struct("AppConfig")
455 .field("app_name", &self.app_name)
456 .field("bind_addr", &self.bind_addr)
457 .field("database_url", &self.database_url)
458 .field("secret_key", &"<redacted>")
459 .field("storage_dir", &self.storage_dir)
460 .field("assets_dir", &self.assets_dir)
461 .field("job_poll_interval_ms", &self.job_poll_interval_ms)
462 .field("job_concurrency", &self.job_concurrency)
463 .field("cookie_secure", &self.cookie_secure)
464 .field("webhooks_live", &self.webhooks_live)
465 .field("webhooks_allow_local", &self.webhooks_allow_local)
466 .finish()
467 }
468}
469
470impl AppConfig {
471 #[must_use]
476 pub fn from_env(app_name: impl Into<String>) -> Self {
477 let app_name = app_name.into();
478 Self {
479 app_name: app_name.clone(),
480 bind_addr: std::env::var("SLABS_BIND").unwrap_or_else(|_| "127.0.0.1:3000".into()),
481 database_url: std::env::var("DATABASE_URL")
482 .unwrap_or_else(|_| format!("sqlite://{app_name}.db?mode=rwc")),
483 secret_key: std::env::var("SLABS_SECRET_KEY")
484 .unwrap_or_else(|_| "dev-only-change-me-in-production-slabs-secret-key".into()),
485 storage_dir: std::env::var("SLABS_STORAGE_DIR").map_or_else(
486 |_| PathBuf::from(format!("./storage/{app_name}")),
487 PathBuf::from,
488 ),
489 assets_dir: std::env::var("SLABS_ASSETS_DIR").map_or_else(
490 |_| {
491 let local = PathBuf::from("./assets");
492 if local.is_dir() {
493 local
494 } else {
495 PathBuf::from(format!("./examples/{app_name}/assets"))
496 }
497 },
498 PathBuf::from,
499 ),
500 job_poll_interval_ms: std::env::var("SLABS_JOB_POLL_MS")
501 .ok()
502 .and_then(|v| v.parse().ok())
503 .unwrap_or(500),
504 job_concurrency: std::env::var("SLABS_JOB_CONCURRENCY")
505 .ok()
506 .and_then(|v| v.parse().ok())
507 .unwrap_or(4),
508 cookie_secure: std::env::var("SLABS_COOKIE_SECURE")
509 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
510 webhooks_live: std::env::var("SLABS_WEBHOOKS_LIVE")
511 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
512 webhooks_allow_local: std::env::var("SLABS_WEBHOOKS_ALLOW_LOCAL")
513 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
514 }
515 }
516
517 #[must_use]
522 pub fn for_test(app_name: impl Into<String>, storage_dir: PathBuf) -> Self {
523 let app_name = app_name.into();
524 let assets_dir = if PathBuf::from("./assets").is_dir() {
525 PathBuf::from("./assets")
526 } else {
527 PathBuf::from(format!("./examples/{app_name}/assets"))
528 };
529 Self {
530 app_name,
531 bind_addr: "127.0.0.1:0".into(),
532 database_url: "sqlite::memory:".into(),
533 secret_key: "test-secret-key-for-isolated-slabs-tests".into(),
534 storage_dir,
535 assets_dir,
536 job_poll_interval_ms: 50,
537 job_concurrency: 2,
538 cookie_secure: false,
539 webhooks_live: false,
540 webhooks_allow_local: false,
541 }
542 }
543}
544
545#[derive(Debug, Clone, Serialize, Deserialize)]
549pub struct RouteMeta {
550 pub name: String,
552 pub method: String,
554 pub path: String,
556 pub summary: String,
558 pub feature: String,
560 #[serde(default, skip_serializing_if = "Option::is_none")]
562 pub input_schema: Option<serde_json::Value>,
563 #[serde(default, skip_serializing_if = "Option::is_none")]
565 pub output_schema: Option<serde_json::Value>,
566}
567
568#[derive(Debug, Clone, Serialize, Deserialize)]
570pub struct JobMeta {
571 pub name: String,
573 pub queue: String,
575 pub max_attempts: i64,
577 pub summary: String,
579}
580
581#[derive(Debug, Clone, Serialize, Deserialize)]
583pub struct AppManifest {
584 pub app_name: String,
586 pub routes: Vec<RouteMeta>,
588 pub jobs: Vec<JobMeta>,
590}
591
592impl AppManifest {
593 #[must_use]
599 pub fn to_openapi_3_1(&self) -> serde_json::Value {
600 let mut paths = serde_json::Map::new();
601
602 for route in &self.routes {
603 let mut parameters = Vec::new();
604 let mut normalized_segments = Vec::new();
605
606 for segment in route.path.split('/') {
607 if let Some(inner) = segment.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
608 let param_name = inner.strip_prefix('*').unwrap_or(inner);
609 if !param_name.is_empty() {
610 parameters.push(json!({
611 "name": param_name,
612 "in": "path",
613 "required": true,
614 "schema": { "type": "string" },
615 }));
616 normalized_segments.push(format!("{{{param_name}}}"));
617 continue;
618 }
619 }
620 normalized_segments.push(segment.to_string());
621 }
622
623 let openapi_path = normalized_segments.join("/");
624 let method_key = route.method.to_ascii_lowercase();
625
626 let mut operation = serde_json::Map::new();
627 operation.insert("operationId".into(), json!(route.name));
628 operation.insert("summary".into(), json!(route.summary));
629 if !route.feature.is_empty() {
630 operation.insert("tags".into(), json!([route.feature]));
631 }
632 if !parameters.is_empty() {
633 operation.insert("parameters".into(), serde_json::Value::Array(parameters));
634 }
635 if let Some(input_schema) = &route.input_schema {
636 operation.insert(
637 "requestBody".into(),
638 json!({
639 "required": true,
640 "content": {
641 "application/json": {
642 "schema": input_schema,
643 }
644 }
645 }),
646 );
647 }
648
649 let ok_response = if let Some(output_schema) = &route.output_schema {
650 json!({
651 "description": "Success",
652 "content": {
653 "application/json": {
654 "schema": output_schema,
655 }
656 }
657 })
658 } else {
659 json!({
660 "description": "Success",
661 })
662 };
663 operation.insert("responses".into(), json!({ "200": ok_response }));
664
665 let path_item = paths
666 .entry(openapi_path)
667 .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
668 if let Some(path_obj) = path_item.as_object_mut() {
669 path_obj.insert(method_key, serde_json::Value::Object(operation));
670 }
671 }
672
673 json!({
674 "openapi": "3.1.0",
675 "info": {
676 "title": self.app_name,
677 "version": "0.1.0",
678 },
679 "paths": serde_json::Value::Object(paths),
680 })
681 }
682}
683
684pub mod slug {
686 #[must_use]
691 pub fn slugify(input: &str) -> String {
692 let mut out = String::with_capacity(input.len());
693 let mut prev_hyphen = true;
694 for ch in input.chars() {
695 if ch.is_ascii_alphanumeric() {
696 out.push(ch.to_ascii_lowercase());
697 prev_hyphen = false;
698 } else if !prev_hyphen {
699 out.push('-');
700 prev_hyphen = true;
701 }
702 }
703 while out.ends_with('-') {
704 out.pop();
705 }
706 if out.is_empty() {
707 "-".to_string()
708 } else {
709 out
710 }
711 }
712}
713
714pub mod position {
716 #[must_use]
723 pub fn between(prev: Option<f64>, next: Option<f64>) -> f64 {
724 match (prev, next) {
725 (None, None) => 1.0,
726 (Some(p), None) => p + 1.0,
727 (None, Some(n)) => {
728 if n > 0.0 {
729 n / 2.0
730 } else {
731 n - 1.0
732 }
733 }
734 (Some(p), Some(n)) => f64::midpoint(p, n),
735 }
736 }
737}
738
739#[must_use]
743pub fn fingerprint(parts: &[&str]) -> String {
744 use sha2::{Digest, Sha256};
745
746 let mut hasher = Sha256::new();
747 for (idx, part) in parts.iter().enumerate() {
748 if idx > 0 {
749 hasher.update([0u8]);
750 }
751 hasher.update(part.as_bytes());
752 }
753 hex::encode(hasher.finalize())
754}
755
756#[cfg(test)]
757mod tests {
758 use super::*;
759
760 #[test]
761 fn slugify_normalizes_titles_and_fallbacks() {
762 assert_eq!(slug::slugify("Hello, World! 2026"), "hello-world-2026");
763 assert_eq!(
764 slug::slugify(" Rust & SQLite --- WAL "),
765 "rust-sqlite-wal"
766 );
767 assert_eq!(slug::slugify("!!!"), "-");
768 }
769
770 #[test]
771 fn position_between_orders_items() {
772 assert!((position::between(None, None) - 1.0).abs() < f64::EPSILON);
773 assert!((position::between(Some(2.0), None) - 3.0).abs() < f64::EPSILON);
774 assert!((position::between(None, Some(1.0)) - 0.5).abs() < f64::EPSILON);
775 assert!((position::between(Some(1.0), Some(2.0)) - 1.5).abs() < f64::EPSILON);
776 }
777
778 #[test]
779 fn fingerprint_distinguishes_part_boundaries() {
780 assert_ne!(fingerprint(&["ab", "c"]), fingerprint(&["a", "bc"]));
781 assert_eq!(fingerprint(&["a", "b"]).len(), 64);
782 }
783
784 #[test]
785 fn app_config_debug_redacts_secret_key() {
786 let mut config = AppConfig::for_test("demo", PathBuf::from("./tmp"));
787 config.secret_key = "super-secret-signing-key".into();
788 let rendered = format!("{config:?}");
789 assert!(!rendered.contains("super-secret-signing-key"));
790 assert!(rendered.contains("<redacted>"));
791 }
792
793 #[test]
794 fn validate_builder_succeeds_for_valid_inputs() {
795 let mut v = Validate::new();
796 v.required("name", " Alice ")
797 .min_len("name", " Alice ", 3)
798 .max_len("name", " Alice ", 10)
799 .email("email", " alice@example.com ")
800 .url("website", "https://example.com/docs")
801 .one_of("role", "admin", &["member", "admin"])
802 .check("age", true, "must be adult");
803
804 assert!(v.is_empty());
805 assert!(v.errors().is_empty());
806 assert!(v.finish().is_ok());
807 }
808
809 #[test]
810 fn validate_builder_collects_all_field_errors_and_maps_to_422() {
811 let mut v = Validate::new();
812 v.required("title", " ")
813 .min_len("title", "hi", 3)
814 .max_len("bio", "123456", 5)
815 .email("email", "not-an-email")
816 .url("website", "ftp://example.com")
817 .one_of("role", "owner", &["member", "admin"])
818 .check("terms", false, "must accept terms")
819 .push("custom", "extra problem");
820
821 assert!(!v.is_empty());
822 assert_eq!(v.errors()["title"].len(), 2);
823 assert_eq!(v.errors()["title"][0], "is required");
824 assert!(v.errors().contains_key("bio"));
825 assert!(v.errors().contains_key("email"));
826 assert!(v.errors().contains_key("website"));
827 assert!(v.errors().contains_key("role"));
828 assert_eq!(v.errors()["terms"], vec!["must accept terms"]);
829 assert_eq!(v.errors()["custom"], vec!["extra problem"]);
830
831 let err = v.finish().unwrap_err();
832 assert_eq!(err.status_code(), StatusCode::UNPROCESSABLE_ENTITY);
833
834 let response = err.into_response();
835 assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
836 }
837
838 #[test]
839 fn validate_checks_unicode_char_lengths_and_email_url_edge_cases() {
840 let mut v = Validate::new();
841 v.min_len("label", "café!", 5)
843 .max_len("label", "café!", 5)
844 .email("bad_at", "@example.com")
845 .email("bad_dot", "alice@localhost")
846 .email("bad_trail", "alice@example.")
847 .url("bare_scheme", "https://")
848 .url("http_ok", "http://localhost:3000");
849
850 assert!(!v.errors().contains_key("label"));
851 assert!(v.errors().contains_key("bad_at"));
852 assert!(v.errors().contains_key("bad_dot"));
853 assert!(v.errors().contains_key("bad_trail"));
854 assert!(v.errors().contains_key("bare_scheme"));
855 assert!(!v.errors().contains_key("http_ok"));
856 }
857
858 #[test]
859 fn app_manifest_to_openapi_3_1_builds_paths_params_and_schemas() {
860 let manifest = AppManifest {
861 app_name: "campfire".into(),
862 routes: vec![
863 RouteMeta {
864 name: "rooms::list_rooms".into(),
865 method: "GET".into(),
866 path: "/api/rooms".into(),
867 summary: "List all rooms".into(),
868 feature: "rooms".into(),
869 input_schema: None,
870 output_schema: Some(json!({
871 "type": "array",
872 "items": { "type": "object" }
873 })),
874 },
875 RouteMeta {
876 name: "rooms::create_room".into(),
877 method: "POST".into(),
878 path: "/api/rooms".into(),
879 summary: "Create a room".into(),
880 feature: "rooms".into(),
881 input_schema: Some(json!({
882 "type": "object",
883 "required": ["name"],
884 "properties": { "name": { "type": "string" } }
885 })),
886 output_schema: Some(json!({
887 "type": "object",
888 "properties": { "id": { "type": "string" } }
889 })),
890 },
891 RouteMeta {
892 name: "messages::get_message".into(),
893 method: "GET".into(),
894 path: "/api/rooms/{room_id}/messages/{msg_id}".into(),
895 summary: "Get one message".into(),
896 feature: "messages".into(),
897 input_schema: None,
898 output_schema: None,
899 },
900 RouteMeta {
901 name: "files::serve_asset".into(),
902 method: "GET".into(),
903 path: "/assets/{*filepath}".into(),
904 summary: "Serve a static asset".into(),
905 feature: "files".into(),
906 input_schema: None,
907 output_schema: None,
908 },
909 ],
910 jobs: vec![],
911 };
912
913 let doc = manifest.to_openapi_3_1();
914 assert_eq!(doc["openapi"], "3.1.0");
915 assert_eq!(doc["info"]["title"], "campfire");
916 assert_eq!(doc["info"]["version"], "0.1.0");
917
918 assert_eq!(
920 doc["paths"]["/api/rooms"]["get"]["operationId"],
921 "rooms::list_rooms"
922 );
923 assert!(doc["paths"]["/api/rooms"]["get"]["requestBody"].is_null());
924 assert_eq!(
925 doc["paths"]["/api/rooms"]["get"]["responses"]["200"]["content"]["application/json"]
926 ["schema"]["type"],
927 "array"
928 );
929
930 assert_eq!(
931 doc["paths"]["/api/rooms"]["post"]["operationId"],
932 "rooms::create_room"
933 );
934 assert_eq!(
935 doc["paths"]["/api/rooms"]["post"]["requestBody"]["content"]["application/json"]
936 ["schema"]["required"][0],
937 "name"
938 );
939 assert_eq!(
940 doc["paths"]["/api/rooms"]["post"]["responses"]["200"]["content"]["application/json"]
941 ["schema"]["properties"]["id"]["type"],
942 "string"
943 );
944
945 let params = doc["paths"]["/api/rooms/{room_id}/messages/{msg_id}"]["get"]["parameters"]
947 .as_array()
948 .unwrap();
949 assert_eq!(params.len(), 2);
950 assert_eq!(params[0]["name"], "room_id");
951 assert_eq!(params[0]["in"], "path");
952 assert_eq!(params[0]["required"], true);
953 assert_eq!(params[0]["schema"]["type"], "string");
954 assert_eq!(params[1]["name"], "msg_id");
955
956 let wildcard_params = doc["paths"]["/assets/{filepath}"]["get"]["parameters"]
958 .as_array()
959 .unwrap();
960 assert_eq!(wildcard_params.len(), 1);
961 assert_eq!(wildcard_params[0]["name"], "filepath");
962 assert_eq!(wildcard_params[0]["in"], "path");
963 assert_eq!(wildcard_params[0]["required"], true);
964 }
965
966 #[test]
967 fn route_meta_omits_none_schemas_when_serialized() {
968 let meta = RouteMeta {
969 name: "health::check".into(),
970 method: "GET".into(),
971 path: "/health".into(),
972 summary: "Health check".into(),
973 feature: "health".into(),
974 input_schema: None,
975 output_schema: None,
976 };
977 let value = serde_json::to_value(&meta).unwrap();
978 assert!(value.get("input_schema").is_none());
979 assert!(value.get("output_schema").is_none());
980
981 let parsed: RouteMeta = serde_json::from_value(value).unwrap();
982 assert!(parsed.input_schema.is_none());
983 assert!(parsed.output_schema.is_none());
984 }
985}