-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvespera_impl.rs
More file actions
1853 lines (1626 loc) · 68.2 KB
/
vespera_impl.rs
File metadata and controls
1853 lines (1626 loc) · 68.2 KB
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Core implementation of vespera! and `export_app`! macros.
//!
//! This module orchestrates the entire macro execution flow:
//! - Route discovery via filesystem scanning
//! - `OpenAPI` spec generation
//! - File I/O for writing `OpenAPI` JSON
//! - Router code generation
//!
//! # Overview
//!
//! This is the main orchestrator for the two primary macros:
//! - `vespera!()` - Generates a complete Axum router with `OpenAPI` spec
//! - `export_app!()` - Exports a router for merging into parent apps
//!
//! The execution flow is:
//! 1. Parse macro arguments via [`router_codegen`]
//! 2. Discover routes via [`collector::collect_metadata`]
//! 3. Generate `OpenAPI` spec via [`openapi_generator`]
//! 4. Write `OpenAPI` JSON files (if configured)
//! 5. Generate router code via [`router_codegen::generate_router_code`]
//!
//! # Key Functions
//!
//! - [`process_vespera_macro`] - Main vespera! macro implementation
//! - [`process_export_app`] - Main `export_app`! macro implementation
//! - [`generate_and_write_openapi`] - `OpenAPI` generation and file I/O
use std::{
collections::HashMap,
hash::{Hash, Hasher},
path::Path,
};
use proc_macro2::Span;
use quote::quote;
use serde::{Deserialize, Serialize};
use crate::{
collector::{collect_file_fingerprints, collect_metadata},
error::{MacroResult, err_call_site},
metadata::{CollectedMetadata, StructMetadata},
openapi_generator::generate_openapi_doc_with_metadata,
route_impl::StoredRouteInfo,
router_codegen::{ProcessedVesperaInput, generate_router_code},
};
/// Docs info tuple type alias for cleaner signatures
pub type DocsInfo = (Option<String>, Option<String>, Option<String>);
/// Cache for avoiding redundant route scanning and OpenAPI generation.
/// Persisted to `target/vespera/routes.cache` across builds.
#[derive(Serialize, Deserialize)]
struct VesperaCache {
/// Macro crate version — invalidates cache when macro code changes
#[serde(default)]
macro_version: String,
/// File path → modification time (secs since UNIX_EPOCH)
file_fingerprints: HashMap<String, u64>,
/// Hash of SCHEMA_STORAGE contents
schema_hash: u64,
/// Hash of OpenAPI config (title, version, servers, docs_url, etc.)
config_hash: u64,
/// Cached route/struct metadata
metadata: CollectedMetadata,
/// Compact JSON for docs embedding (None if docs disabled)
spec_json: Option<String>,
/// Pretty JSON for file output (None if no openapi file configured)
spec_pretty: Option<String>,
}
/// Compute a deterministic hash of SCHEMA_STORAGE contents.
fn compute_schema_hash(schema_storage: &HashMap<String, StructMetadata>) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
let mut keys: Vec<&String> = schema_storage.keys().collect();
keys.sort();
for key in keys {
key.hash(&mut hasher);
let meta = &schema_storage[key];
meta.name.hash(&mut hasher);
meta.definition.hash(&mut hasher);
meta.include_in_openapi.hash(&mut hasher);
}
hasher.finish()
}
/// Compute a deterministic hash of OpenAPI config fields.
fn compute_config_hash(processed: &ProcessedVesperaInput) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
processed.title.hash(&mut hasher);
processed.version.hash(&mut hasher);
processed.docs_url.hash(&mut hasher);
processed.redoc_url.hash(&mut hasher);
processed.openapi_file_names.hash(&mut hasher);
if let Some(ref servers) = processed.servers {
for s in servers {
s.url.hash(&mut hasher);
}
}
for merge_path in &processed.merge {
quote!(#merge_path).to_string().hash(&mut hasher);
}
hasher.finish()
}
/// Get the path to the routes cache file.
fn get_cache_path() -> std::path::PathBuf {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default();
let manifest_path = Path::new(&manifest_dir);
find_target_dir(manifest_path)
.join("vespera")
.join("routes.cache")
}
/// Try to read and deserialize a cache file. Returns None on any failure.
fn read_cache(cache_path: &Path) -> Option<VesperaCache> {
let content = std::fs::read_to_string(cache_path).ok()?;
serde_json::from_str(&content).ok()
}
/// Write cache to disk. Failures are silently ignored (cache is best-effort).
fn write_cache(cache_path: &Path, cache: &VesperaCache) {
if let Some(parent) = cache_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(json) = serde_json::to_string(cache) {
let _ = std::fs::write(cache_path, json);
}
}
/// Generate `OpenAPI` JSON and write to files, returning docs info
pub fn generate_and_write_openapi(
input: &ProcessedVesperaInput,
metadata: &CollectedMetadata,
file_asts: HashMap<String, syn::File>,
route_storage: &[StoredRouteInfo],
) -> MacroResult<DocsInfo> {
if input.openapi_file_names.is_empty() && input.docs_url.is_none() && input.redoc_url.is_none()
{
return Ok((None, None, None));
}
let mut openapi_doc = generate_openapi_doc_with_metadata(
input.title.clone(),
input.version.clone(),
input.servers.clone(),
metadata,
Some(file_asts),
route_storage,
);
// Merge specs from child apps at compile time
if !input.merge.is_empty()
&& let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR")
{
let manifest_path = Path::new(&manifest_dir);
let target_dir = find_target_dir(manifest_path);
let vespera_dir = target_dir.join("vespera");
for merge_path in &input.merge {
// Extract the struct name (last segment, e.g., "ThirdApp" from "third::ThirdApp")
if let Some(last_segment) = merge_path.segments.last() {
let struct_name = last_segment.ident.to_string();
let spec_file = vespera_dir.join(format!("{struct_name}.openapi.json"));
if let Ok(spec_content) = std::fs::read_to_string(&spec_file)
&& let Ok(child_spec) =
serde_json::from_str::<vespera_core::openapi::OpenApi>(&spec_content)
{
openapi_doc.merge(child_spec);
}
}
}
}
// Pretty-print for user-visible files
if !input.openapi_file_names.is_empty() {
let json_pretty = serde_json::to_string_pretty(&openapi_doc).map_err(|e| err_call_site(format!("OpenAPI generation: failed to serialize document to JSON. Error: {e}. Check that all schema types are serializable.")))?;
for openapi_file_name in &input.openapi_file_names {
let file_path = Path::new(openapi_file_name);
if let Some(parent) = file_path.parent() {
std::fs::create_dir_all(parent).map_err(|e| err_call_site(format!("OpenAPI output: failed to create directory '{}'. Error: {}. Ensure the path is valid and writable.", parent.display(), e)))?;
}
let should_write =
std::fs::read_to_string(file_path).map_or(true, |existing| existing != json_pretty);
if should_write {
std::fs::write(file_path, &json_pretty).map_err(|e| err_call_site(format!("OpenAPI output: failed to write file '{openapi_file_name}'. Error: {e}. Ensure the file path is writable.")))?;
}
}
}
// Compact JSON for embedding (smaller binary, faster downstream compilation)
let spec_json = if input.docs_url.is_some() || input.redoc_url.is_some() {
Some(serde_json::to_string(&openapi_doc).map_err(|e| err_call_site(format!("OpenAPI generation: failed to serialize document to JSON. Error: {e}. Check that all schema types are serializable.")))?)
} else {
None
};
Ok((input.docs_url.clone(), input.redoc_url.clone(), spec_json))
}
/// Find the folder path for route scanning
pub fn find_folder_path(folder_name: &str) -> MacroResult<std::path::PathBuf> {
let root = std::env::var("CARGO_MANIFEST_DIR").map_err(|_| {
err_call_site(
"CARGO_MANIFEST_DIR is not set. vespera macros must be used within a cargo build.",
)
})?;
let path = format!("{root}/src/{folder_name}");
let path = Path::new(&path);
if path.exists() && path.is_dir() {
return Ok(path.to_path_buf());
}
Ok(Path::new(folder_name).to_path_buf())
}
/// Find the workspace root's target directory
pub fn find_target_dir(manifest_path: &Path) -> std::path::PathBuf {
// Look for workspace root by finding a Cargo.toml with [workspace] section
let mut current = Some(manifest_path);
let mut last_with_lock = None;
while let Some(dir) = current {
// Check if this directory has Cargo.lock
if dir.join("Cargo.lock").exists() {
last_with_lock = Some(dir.to_path_buf());
}
// Check if this is a workspace root (has Cargo.toml with [workspace])
let cargo_toml = dir.join("Cargo.toml");
if cargo_toml.exists()
&& let Ok(contents) = std::fs::read_to_string(&cargo_toml)
&& contents.contains("[workspace]")
{
return dir.join("target");
}
current = dir.parent();
}
// If we found a Cargo.lock but no [workspace], use the topmost one
if let Some(lock_dir) = last_with_lock {
return lock_dir.join("target");
}
// Fallback: use manifest dir's target
manifest_path.join("target")
}
/// Supplement collector's `RouteMetadata` with data from `ROUTE_STORAGE`.
///
/// `#[route]` stores metadata at attribute expansion time.
/// `collector.rs` re-parses the same data from file ASTs.
/// This function merges ROUTE_STORAGE data into collector's output,
/// preferring ROUTE_STORAGE values when they provide richer info.
///
/// Matching is by function name. If multiple routes share a function name,
/// the match is ambiguous and ROUTE_STORAGE data is skipped for safety.
fn merge_route_storage_data(metadata: &mut CollectedMetadata, route_storage: &[StoredRouteInfo]) {
if route_storage.is_empty() {
return;
}
for route in &mut metadata.routes {
// Find matching StoredRouteInfo by function name
let mut matches = route_storage
.iter()
.filter(|s| s.fn_name == route.function_name);
let Some(stored) = matches.next() else {
continue;
};
// Skip if ambiguous (multiple routes with same function name)
if matches.next().is_some() {
continue;
}
// Supplement with ROUTE_STORAGE data
// Only override when ROUTE_STORAGE has an explicit value
if let Some(ref tags) = stored.tags {
route.tags = Some(tags.clone());
}
if let Some(ref desc) = stored.description {
route.description = Some(desc.clone());
}
if let Some(ref status) = stored.error_status {
route.error_status = Some(status.clone());
}
}
}
/// Write cached OpenAPI spec to output files if they are stale or missing.
pub fn ensure_openapi_files_from_cache(
openapi_file_names: &[String],
spec_pretty: Option<&str>,
) -> syn::Result<()> {
let Some(pretty) = spec_pretty else {
return Ok(());
};
for openapi_file_name in openapi_file_names {
let file_path = Path::new(openapi_file_name);
let should_write =
std::fs::read_to_string(file_path).map_or(true, |existing| existing != *pretty);
if should_write {
if let Some(parent) = file_path.parent() {
std::fs::create_dir_all(parent).map_err(|e| {
syn::Error::new(
Span::call_site(),
format!(
"OpenAPI output: failed to create directory '{}': {}",
parent.display(),
e
),
)
})?;
}
std::fs::write(file_path, pretty).map_err(|e| {
syn::Error::new(
Span::call_site(),
format!("OpenAPI output: failed to write file '{openapi_file_name}': {e}"),
)
})?;
}
}
Ok(())
}
/// Write compact spec JSON to target dir for `include_str!` embedding.
fn write_spec_for_embedding(
spec_json: Option<String>,
) -> syn::Result<Option<proc_macro2::TokenStream>> {
let Some(json) = spec_json else {
return Ok(None);
};
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default();
let manifest_path = Path::new(&manifest_dir);
let target_dir = find_target_dir(manifest_path);
let vespera_dir = target_dir.join("vespera");
std::fs::create_dir_all(&vespera_dir).map_err(|e| {
syn::Error::new(
Span::call_site(),
format!(
"vespera! macro: failed to create directory '{}': {}",
vespera_dir.display(),
e
),
)
})?;
let spec_file = vespera_dir.join("vespera_spec.json");
let should_write =
std::fs::read_to_string(&spec_file).map_or(true, |existing| existing != json);
if should_write {
std::fs::write(&spec_file, &json).map_err(|e| {
syn::Error::new(
Span::call_site(),
format!(
"vespera! macro: failed to write spec file '{}': {}",
spec_file.display(),
e
),
)
})?;
}
let path_str = spec_file.display().to_string().replace('\\', "/");
Ok(Some(quote::quote! { include_str!(#path_str) }))
}
/// Process vespera macro - extracted for testability
#[allow(clippy::too_many_lines)]
pub fn process_vespera_macro(
processed: &ProcessedVesperaInput,
schema_storage: &HashMap<String, StructMetadata>,
route_storage: &[StoredRouteInfo],
) -> syn::Result<proc_macro2::TokenStream> {
let profile_start = if std::env::var("VESPERA_PROFILE").is_ok() {
Some(std::time::Instant::now())
} else {
None
};
let folder_path = find_folder_path(&processed.folder_name)?;
if !folder_path.exists() {
return Err(syn::Error::new(
Span::call_site(),
format!(
"vespera! macro: route folder '{}' not found. Create src/{} or specify a different folder with `dir = \"your_folder\"`.",
processed.folder_name, processed.folder_name
),
));
}
// --- Incremental cache check ---
let cache_path = get_cache_path();
let fingerprints = collect_file_fingerprints(&folder_path)
.map_err(|e| syn::Error::new(Span::call_site(), format!("vespera! macro: {e}")))?;
let schema_hash = compute_schema_hash(schema_storage);
let config_hash = compute_config_hash(processed);
let macro_version = env!("CARGO_PKG_VERSION").to_string();
let cached = read_cache(&cache_path);
let cache_hit = cached.as_ref().is_some_and(|c| {
c.macro_version == macro_version
&& c.file_fingerprints == fingerprints
&& c.schema_hash == schema_hash
&& c.config_hash == config_hash
});
let (metadata, spec_json) = if cache_hit {
let cache = cached.unwrap();
let mut metadata = cache.metadata;
metadata.structs.extend(schema_storage.values().cloned());
merge_route_storage_data(&mut metadata, route_storage);
metadata
.check_duplicate_schema_names()
.map_err(|msg| syn::Error::new(Span::call_site(), format!("vespera! macro: {msg}")))?;
// Ensure openapi.json files exist and are up-to-date from cache
ensure_openapi_files_from_cache(
&processed.openapi_file_names,
cache.spec_pretty.as_deref(),
)?;
(metadata, cache.spec_json)
} else {
let (mut metadata, file_asts) = collect_metadata(&folder_path, &processed.folder_name, route_storage).map_err(|e| syn::Error::new(Span::call_site(), format!("vespera! macro: failed to scan route folder '{}'. Error: {}. Check that all .rs files have valid Rust syntax.", processed.folder_name, e)))?;
// Clone metadata before extending (cache stores file-only structs)
let cache_metadata = metadata.clone();
metadata.structs.extend(schema_storage.values().cloned());
merge_route_storage_data(&mut metadata, route_storage);
metadata
.check_duplicate_schema_names()
.map_err(|msg| syn::Error::new(Span::call_site(), format!("vespera! macro: {msg}")))?;
let (_, _, spec_json) =
generate_and_write_openapi(processed, &metadata, file_asts, route_storage)?;
// Read back spec_pretty from first openapi file for caching
let spec_pretty = processed
.openapi_file_names
.first()
.and_then(|f| std::fs::read_to_string(f).ok());
// Persist cache (best-effort, failures are silent)
write_cache(
&cache_path,
&VesperaCache {
macro_version: macro_version.clone(),
file_fingerprints: fingerprints,
schema_hash,
config_hash,
metadata: cache_metadata,
spec_json: spec_json.clone(),
spec_pretty,
},
);
(metadata, spec_json)
};
// Write compact spec for include_str! embedding
let spec_tokens = write_spec_for_embedding(spec_json)?;
// --- Cron job discovery from CRON_STORAGE ---
// #[cron("...")] attribute already registers metadata at expansion time.
// No folder scanning needed — just read the storage.
let cron_jobs: Vec<crate::metadata::CronMetadata> = {
let storage = crate::CRON_STORAGE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let src_dir = std::env::var("CARGO_MANIFEST_DIR")
.map(|d| {
let p = std::path::PathBuf::from(d).join("src");
// Canonicalize for reliable prefix stripping
let canonical = p.canonicalize().unwrap_or(p);
canonical.display().to_string().replace('\\', "/")
})
.unwrap_or_default();
storage
.iter()
.map(|s| {
// Derive module path from file_path relative to src/
let module_path = s
.file_path
.as_ref()
.map(|fp| {
let canonical = std::path::Path::new(fp)
.canonicalize()
.map_or_else(|_| fp.clone(), |p| p.display().to_string());
let normalized = canonical.replace('\\', "/");
let relative = normalized
.strip_prefix(&src_dir)
.map_or(&*normalized, |rest| rest.trim_start_matches('/'));
// Convert path to module path: strip .rs, replace / with ::, strip mod
// Replace hyphens with underscores (Rust module convention)
relative
.trim_end_matches(".rs")
.replace('/', "::")
.replace('-', "_")
.trim_end_matches("::mod")
.to_string()
})
.unwrap_or_default();
crate::metadata::CronMetadata {
expression: s.expression.clone(),
function_name: s.fn_name.clone(),
module_path,
file_path: s.file_path.clone().unwrap_or_default(),
}
})
.collect()
};
let result = Ok(generate_router_code(
&metadata,
processed.docs_url.as_deref(),
processed.redoc_url.as_deref(),
spec_tokens,
&processed.merge,
&cron_jobs,
));
if let Some(start) = profile_start {
eprintln!(
"[vespera-profile] vespera! macro total: {:?}",
start.elapsed()
);
crate::schema_macro::print_profile_summary();
}
result
}
/// Process `export_app` macro - extracted for testability
pub fn process_export_app(
name: &syn::Ident,
folder_name: &str,
schema_storage: &HashMap<String, StructMetadata>,
manifest_dir: &str,
route_storage: &[StoredRouteInfo],
) -> syn::Result<proc_macro2::TokenStream> {
let profile_start = if std::env::var("VESPERA_PROFILE").is_ok() {
Some(std::time::Instant::now())
} else {
None
};
let folder_path = find_folder_path(folder_name)?;
if !folder_path.exists() {
return Err(syn::Error::new(
Span::call_site(),
format!(
"export_app! macro: route folder '{folder_name}' not found. Create src/{folder_name} or specify a different folder with `dir = \"your_folder\"`.",
),
));
}
let (mut metadata, file_asts) = collect_metadata(&folder_path, folder_name, route_storage).map_err(|e| syn::Error::new(Span::call_site(), format!("export_app! macro: failed to scan route folder '{folder_name}'. Error: {e}. Check that all .rs files have valid Rust syntax.")))?;
metadata.structs.extend(schema_storage.values().cloned());
merge_route_storage_data(&mut metadata, route_storage);
metadata
.check_duplicate_schema_names()
.map_err(|msg| syn::Error::new(Span::call_site(), format!("export_app! macro: {msg}")))?;
// Generate OpenAPI spec JSON string
let openapi_doc = generate_openapi_doc_with_metadata(
None,
None,
None,
&metadata,
Some(file_asts),
route_storage,
);
let spec_json = serde_json::to_string(&openapi_doc).map_err(|e| syn::Error::new(Span::call_site(), format!("export_app! macro: failed to serialize OpenAPI spec to JSON. Error: {e}. Check that all schema types are serializable.")))?;
// Write spec to temp file for compile-time merging by parent apps
let name_str = name.to_string();
let manifest_path = Path::new(manifest_dir);
let target_dir = find_target_dir(manifest_path);
let vespera_dir = target_dir.join("vespera");
std::fs::create_dir_all(&vespera_dir).map_err(|e| syn::Error::new(Span::call_site(), format!("export_app! macro: failed to create build cache directory '{}'. Error: {}. Ensure the target directory is writable.", vespera_dir.display(), e)))?;
let spec_file = vespera_dir.join(format!("{name_str}.openapi.json"));
std::fs::write(&spec_file, &spec_json).map_err(|e| syn::Error::new(Span::call_site(), format!("export_app! macro: failed to write OpenAPI spec file '{}'. Error: {}. Ensure the file path is writable.", spec_file.display(), e)))?;
let spec_path_str = spec_file.display().to_string().replace('\\', "/");
// Generate router code (without docs routes, no merge)
let router_code = generate_router_code(&metadata, None, None, None, &[], &[]);
let result = Ok(quote! {
/// Auto-generated vespera app struct
pub struct #name;
impl #name {
/// OpenAPI specification as JSON string
pub const OPENAPI_SPEC: &'static str = include_str!(#spec_path_str);
/// Create the router for this app.
/// Returns `Router<()>` which can be merged into any other router.
pub fn router() -> vespera::axum::Router<()> {
#router_code
}
}
});
if let Some(start) = profile_start {
eprintln!(
"[vespera-profile] export_app! macro total: {:?}",
start.elapsed()
);
crate::schema_macro::print_profile_summary();
}
result
}
#[cfg(test)]
mod tests {
use std::fs;
use tempfile::TempDir;
use super::*;
use crate::metadata::RouteMetadata;
fn create_temp_file(dir: &TempDir, filename: &str, content: &str) -> std::path::PathBuf {
let file_path = dir.path().join(filename);
if let Some(parent) = file_path.parent() {
fs::create_dir_all(parent).expect("Failed to create parent directory");
}
fs::write(&file_path, content).expect("Failed to write temp file");
file_path
}
// ========== Tests for generate_and_write_openapi ==========
#[test]
fn test_generate_and_write_openapi_no_output() {
let processed = ProcessedVesperaInput {
folder_name: "routes".to_string(),
openapi_file_names: vec![],
title: None,
version: None,
docs_url: None,
redoc_url: None,
servers: None,
merge: vec![],
};
let metadata = CollectedMetadata::new();
let result = generate_and_write_openapi(&processed, &metadata, HashMap::new(), &[]);
assert!(result.is_ok());
let (docs_url, redoc_url, spec_json) = result.unwrap();
assert!(docs_url.is_none());
assert!(redoc_url.is_none());
assert!(spec_json.is_none());
}
#[test]
fn test_generate_and_write_openapi_docs_only() {
let processed = ProcessedVesperaInput {
folder_name: "routes".to_string(),
openapi_file_names: vec![],
title: Some("Test API".to_string()),
version: Some("1.0.0".to_string()),
docs_url: Some("/docs".to_string()),
redoc_url: None,
servers: None,
merge: vec![],
};
let metadata = CollectedMetadata::new();
let result = generate_and_write_openapi(&processed, &metadata, HashMap::new(), &[]);
assert!(result.is_ok());
let (docs_url, redoc_url, spec_json) = result.unwrap();
assert!(docs_url.is_some());
assert_eq!(docs_url.unwrap(), "/docs");
assert!(spec_json.is_some());
let json = spec_json.unwrap();
assert!(json.contains("\"openapi\""));
assert!(json.contains("Test API"));
assert!(redoc_url.is_none());
}
#[test]
fn test_generate_and_write_openapi_redoc_only() {
let processed = ProcessedVesperaInput {
folder_name: "routes".to_string(),
openapi_file_names: vec![],
title: None,
version: None,
docs_url: None,
redoc_url: Some("/redoc".to_string()),
servers: None,
merge: vec![],
};
let metadata = CollectedMetadata::new();
let result = generate_and_write_openapi(&processed, &metadata, HashMap::new(), &[]);
assert!(result.is_ok());
let (docs_url, redoc_url, spec_json) = result.unwrap();
assert!(docs_url.is_none());
assert!(redoc_url.is_some());
assert_eq!(redoc_url.unwrap(), "/redoc");
assert!(spec_json.is_some());
}
#[test]
fn test_generate_and_write_openapi_both_docs() {
let processed = ProcessedVesperaInput {
folder_name: "routes".to_string(),
openapi_file_names: vec![],
title: None,
version: None,
docs_url: Some("/docs".to_string()),
redoc_url: Some("/redoc".to_string()),
servers: None,
merge: vec![],
};
let metadata = CollectedMetadata::new();
let result = generate_and_write_openapi(&processed, &metadata, HashMap::new(), &[]);
assert!(result.is_ok());
let (docs_url, redoc_url, spec_json) = result.unwrap();
assert!(docs_url.is_some());
assert!(redoc_url.is_some());
assert!(spec_json.is_some());
}
#[test]
fn test_generate_and_write_openapi_file_output() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let output_path = temp_dir.path().join("test-openapi.json");
let processed = ProcessedVesperaInput {
folder_name: "routes".to_string(),
openapi_file_names: vec![output_path.to_string_lossy().to_string()],
title: Some("File Test".to_string()),
version: Some("2.0.0".to_string()),
docs_url: None,
redoc_url: None,
servers: None,
merge: vec![],
};
let metadata = CollectedMetadata::new();
let result = generate_and_write_openapi(&processed, &metadata, HashMap::new(), &[]);
assert!(result.is_ok());
// Verify file was written
assert!(output_path.exists());
let content = fs::read_to_string(&output_path).unwrap();
assert!(content.contains("\"openapi\""));
assert!(content.contains("File Test"));
assert!(content.contains("2.0.0"));
}
#[test]
fn test_generate_and_write_openapi_creates_directories() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let output_path = temp_dir.path().join("nested/dir/openapi.json");
let processed = ProcessedVesperaInput {
folder_name: "routes".to_string(),
openapi_file_names: vec![output_path.to_string_lossy().to_string()],
title: None,
version: None,
docs_url: None,
redoc_url: None,
servers: None,
merge: vec![],
};
let metadata = CollectedMetadata::new();
let result = generate_and_write_openapi(&processed, &metadata, HashMap::new(), &[]);
assert!(result.is_ok());
// Verify nested directories and file were created
assert!(output_path.exists());
}
// ========== Tests for find_folder_path ==========
// Note: find_folder_path uses CARGO_MANIFEST_DIR which is set during cargo test
#[test]
fn test_find_folder_path_nonexistent_returns_path() {
// When the constructed path doesn't exist, it falls back to using folder_name directly
let result = find_folder_path("nonexistent_folder_xyz").unwrap();
// It should return a PathBuf (either from src/nonexistent... or just the folder name)
assert!(result.to_string_lossy().contains("nonexistent_folder_xyz"));
}
// ========== Tests for find_target_dir ==========
#[test]
fn test_find_target_dir_no_workspace() {
// Test fallback to manifest dir's target
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let manifest_path = temp_dir.path();
let result = find_target_dir(manifest_path);
assert_eq!(result, manifest_path.join("target"));
}
#[test]
fn test_find_target_dir_with_cargo_lock() {
// Test finding target dir with Cargo.lock present
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let manifest_path = temp_dir.path();
// Create Cargo.lock (but no [workspace] in Cargo.toml)
fs::write(manifest_path.join("Cargo.lock"), "").expect("Failed to write Cargo.lock");
let result = find_target_dir(manifest_path);
// Should use the directory with Cargo.lock
assert_eq!(result, manifest_path.join("target"));
}
#[test]
fn test_find_target_dir_with_workspace() {
// Test finding workspace root
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let workspace_root = temp_dir.path();
// Create a workspace Cargo.toml
fs::write(
workspace_root.join("Cargo.toml"),
"[workspace]\nmembers = [\"crate1\"]",
)
.expect("Failed to write Cargo.toml");
// Create nested crate directory
let crate_dir = workspace_root.join("crate1");
fs::create_dir(&crate_dir).expect("Failed to create crate dir");
fs::write(crate_dir.join("Cargo.toml"), "[package]\nname = \"crate1\"")
.expect("Failed to write Cargo.toml");
let result = find_target_dir(&crate_dir);
// Should return workspace root's target
assert_eq!(result, workspace_root.join("target"));
}
#[test]
fn test_find_target_dir_workspace_with_cargo_lock() {
// Test that [workspace] takes priority over Cargo.lock
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let workspace_root = temp_dir.path();
// Create workspace Cargo.toml and Cargo.lock
fs::write(
workspace_root.join("Cargo.toml"),
"[workspace]\nmembers = [\"crate1\"]",
)
.expect("Failed to write Cargo.toml");
fs::write(workspace_root.join("Cargo.lock"), "").expect("Failed to write Cargo.lock");
// Create nested crate
let crate_dir = workspace_root.join("crate1");
fs::create_dir(&crate_dir).expect("Failed to create crate dir");
fs::write(crate_dir.join("Cargo.toml"), "[package]\nname = \"crate1\"")
.expect("Failed to write Cargo.toml");
let result = find_target_dir(&crate_dir);
assert_eq!(result, workspace_root.join("target"));
}
#[test]
fn test_find_target_dir_deeply_nested() {
// Test deeply nested crate structure
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let workspace_root = temp_dir.path();
// Create workspace
fs::write(
workspace_root.join("Cargo.toml"),
"[workspace]\nmembers = [\"crates/*\"]",
)
.expect("Failed to write Cargo.toml");
// Create deeply nested crate
let deep_crate = workspace_root.join("crates/group/my-crate");
fs::create_dir_all(&deep_crate).expect("Failed to create nested dirs");
fs::write(deep_crate.join("Cargo.toml"), "[package]").expect("Failed to write Cargo.toml");
let result = find_target_dir(&deep_crate);
assert_eq!(result, workspace_root.join("target"));
}
// ========== Tests for process_vespera_macro ==========
#[test]
fn test_process_vespera_macro_folder_not_found() {
let processed = ProcessedVesperaInput {
folder_name: "nonexistent_folder_xyz_123".to_string(),
openapi_file_names: vec![],
title: None,
version: None,
docs_url: None,
redoc_url: None,
servers: None,
merge: vec![],
};
let result = process_vespera_macro(&processed, &HashMap::new(), &[]);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(err.contains("route folder") && err.contains("not found"));
}
#[test]
fn test_process_vespera_macro_collect_metadata_error() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
// Create an invalid route file (will cause parse error but collect_metadata handles it)
create_temp_file(&temp_dir, "invalid.rs", "not valid rust code {{{");
let processed = ProcessedVesperaInput {
folder_name: temp_dir.path().to_string_lossy().to_string(),
openapi_file_names: vec![],
title: Some("Test API".to_string()),
version: Some("1.0.0".to_string()),
docs_url: None,
redoc_url: None,
servers: None,
merge: vec![],
};
// This exercises the collect_metadata path (which handles parse errors gracefully)
let result = process_vespera_macro(&processed, &HashMap::new(), &[]);
// Result may succeed or fail depending on how collect_metadata handles invalid files
let _ = result;
}
#[test]
fn test_process_vespera_macro_with_schema_storage() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
// Create an empty file (valid but no routes)
create_temp_file(&temp_dir, "empty.rs", "// empty file\n");
let schema_storage = HashMap::from([(
"TestSchema".to_string(),
StructMetadata::new(
"TestSchema".to_string(),
"struct TestSchema { id: i32 }".to_string(),
),
)]);
let processed = ProcessedVesperaInput {
folder_name: temp_dir.path().to_string_lossy().to_string(),
openapi_file_names: vec![],
title: None,
version: None,
docs_url: Some("/docs".to_string()),
redoc_url: Some("/redoc".to_string()),
servers: None,
merge: vec![],
};
// This exercises the schema_storage extend path
let result = process_vespera_macro(&processed, &schema_storage, &[]);
// We only care about exercising the code path
let _ = result;
}
#[test]
#[serial_test::serial]
fn test_process_vespera_macro_with_cron_storage() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
// Create src/ subfolder structure to simulate a real project
let src_dir = temp_dir.path().join("src");
std::fs::create_dir_all(src_dir.join("routes")).expect("create routes dir");
std::fs::write(src_dir.join("routes").join("health.rs"), "// empty\n")
.expect("write health.rs");
// Set CARGO_MANIFEST_DIR so module path derivation works
let old_manifest = std::env::var("CARGO_MANIFEST_DIR").ok();
unsafe {
std::env::set_var(
"CARGO_MANIFEST_DIR",
temp_dir.path().to_string_lossy().as_ref(),
);
}
// Populate CRON_STORAGE with a fake cron entry
{
let mut storage = crate::CRON_STORAGE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
storage.push(crate::cron_impl::StoredCronInfo {
fn_name: "test_cron_job".to_string(),
expression: "0 */5 * * * *".to_string(),
file_path: Some(
src_dir
.join("routes")
.join("health.rs")
.display()
.to_string(),
),
});
}
let processed = ProcessedVesperaInput {
folder_name: src_dir.join("routes").to_string_lossy().to_string(),
openapi_file_names: vec![],
title: None,