stately 0.5.0

Type-safe state management with entity relationships and CRUD operations
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
// ============================================================================
// DO NOT EDIT THIS FILE MANUALLY
// This file is auto-generated by scripts/generate-demo.sh
// Run `just docs` or `./scripts/generate-demo.sh` to regenerate
// ============================================================================

#![allow(clippy::all)]
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unreachable_code)]
#![allow(unused_mut)]
#![expect(unused_crate_dependencies)]

//! Auto-generated code examples showing what the stately macros generate.
//!
//! This module demonstrates the actual code generated by the `#[stately::state]`
//! and `#[stately::axum_api]` macros. Refer to [`examples/doc_expand.rs`](https://github.com/georgeleepatterson/stately/blob/main/crates/stately/examples/doc_expand.rs)
//! for the source code that generates this output.

//! # Generated Code Examples - Demo
//!
//! > **All code here is automatically generated from the example in
//! > `stately/examples/doc_expand.rs`. It is
//! > for illustration only to show what gets generated in your actual crate.**
//!
//! This module demonstrates the code generated by stately's procedural macros.
//! All code shown here is automatically generated when you use the `#[stately::state]` and
//! `#[stately::axum_api]` macros in your crate.
//!
//! **Note:** This module is only included when building documentation (`#[cfg(doc)]`).
//! These types are for illustration and show what gets generated in your actual crate.
//!
//! ## What Gets Generated
//!
//! When you use `#[stately::state]` on a struct, the macro generates:
//!
//! - **[`StateEntry`] enum** - Discriminator for entity types with string conversion
//! - **[`Entity`] enum** - Type-erased wrapper for all entity types
//! - **[`ForeignEntity`] trait** - Impl on external types (when using `#[collection(foreign)]`)
//! - **Wrapper types** - When using `variant = "..."` (e.g., [`ArchivedPipeline`], [`JsonConfig`])
//! - **[`State`] implementation** - With CRUD methods like `create_entity`, `update_entity`, etc.
//! - **[`link_aliases`] module** - Type aliases like `PipelineLink = Link<Pipeline>`
//!
//! When you additionally use `#[stately::axum_api(State)]`, the macro also generates:
//!
//! - **[`ApiState`] implementation** - With handler methods and `router()`
//! - **[`ResponseEvent`] enum** - Events emitted after CRUD operations
//! - **Request/Response types** - For all API endpoints
//! - **`OpenAPI` documentation** - When using the `openapi` parameter
//!
//! ## Source Example
//!
//! The code below is generated from the example at `crates/stately/examples/doc_expand.rs`:
//!
//! ```rust,ignore
//! #[stately::entity]
//! #[derive(Clone, serde::Serialize, serde::Deserialize)]
//! pub struct Pipeline {
//!     pub name: String,
//!     pub source: Link<Source>,
//! }
//!
//! #[stately::state(openapi)]
//! pub struct State {
//!     pipelines: Pipeline,
//!     sources: Source,
//!
//!     // Variant for multiple uses of same type
//!     #[collection(variant = "ArchivedPipeline")]
//!     archived: Pipeline,
//!
//!     // Custom collection type
//!     #[collection(SinkCollection)]
//!     sinks: Sink,
//!
//!     // Foreign type support
//!     #[collection(foreign, variant = "JsonConfig")]
//!     configs: serde_json::Value,
//! }
//!
//! #[stately::axum_api(State, openapi)]
//! pub struct ApiState {}
//! ```
use crate::prelude::*;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct Pipeline {
    pub name:   String,
    pub source: Link<Source>,
}
impl crate::HasName for Pipeline {
    fn name(&self) -> &str { &self.name }
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct Source {
    pub name: String,
    pub url:  String,
}
impl crate::HasName for Source {
    fn name(&self) -> &str { &self.name }
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct Sink {
    pub name:        String,
    pub destination: String,
}
impl crate::HasName for Sink {
    fn name(&self) -> &str { &self.name }
}
type SinkCollection = Collection<Sink>;
/// Wrapper type for disambiguating multiple uses of the same entity type
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[serde(transparent)]
pub struct ArchivedPipeline(pub Pipeline);
impl ArchivedPipeline {
    /// Creates a new wrapper instance
    pub fn new(inner: Pipeline) -> Self { Self(inner) }

    /// Consumes the wrapper and returns the inner value
    pub fn into_inner(self) -> Pipeline { self.0 }

    /// Returns a reference to the inner value
    pub fn inner(&self) -> &Pipeline { &self.0 }

    /// Returns a mutable reference to the inner value
    pub fn inner_mut(&mut self) -> &mut Pipeline { &mut self.0 }
}
impl ::core::ops::Deref for ArchivedPipeline {
    type Target = Pipeline;

    fn deref(&self) -> &Self::Target { &self.0 }
}
impl ::core::ops::DerefMut for ArchivedPipeline {
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}
impl ::core::convert::AsRef<Pipeline> for ArchivedPipeline {
    fn as_ref(&self) -> &Pipeline { &self.0 }
}
impl ::core::convert::AsMut<Pipeline> for ArchivedPipeline {
    fn as_mut(&mut self) -> &mut Pipeline { &mut self.0 }
}
impl ::core::convert::From<Pipeline> for ArchivedPipeline {
    fn from(inner: Pipeline) -> Self { Self(inner) }
}
impl ::core::convert::From<ArchivedPipeline> for Pipeline {
    fn from(wrapper: ArchivedPipeline) -> Self { wrapper.0 }
}
impl crate::HasName for ArchivedPipeline {
    fn name(&self) -> &str { self.0.name() }
}
impl crate::StateEntity for ArchivedPipeline {
    type Entry = StateEntry;

    const STATE_ENTRY: StateEntry = StateEntry::ArchivedPipeline;

    fn description(&self) -> Option<&str> { self.0.description() }

    fn summary(&self, id: crate::EntityId) -> crate::Summary { self.0.summary(id) }
}
/// Wrapper type for disambiguating multiple uses of the same entity type
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[serde(transparent)]
pub struct JsonConfig(pub serde_json::Value);
impl JsonConfig {
    /// Creates a new wrapper instance
    pub fn new(inner: serde_json::Value) -> Self { Self(inner) }

    /// Consumes the wrapper and returns the inner value
    pub fn into_inner(self) -> serde_json::Value { self.0 }

    /// Returns a reference to the inner value
    pub fn inner(&self) -> &serde_json::Value { &self.0 }

    /// Returns a mutable reference to the inner value
    pub fn inner_mut(&mut self) -> &mut serde_json::Value { &mut self.0 }
}
impl ::core::ops::Deref for JsonConfig {
    type Target = serde_json::Value;

    fn deref(&self) -> &Self::Target { &self.0 }
}
impl ::core::ops::DerefMut for JsonConfig {
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}
impl ::core::convert::AsRef<serde_json::Value> for JsonConfig {
    fn as_ref(&self) -> &serde_json::Value { &self.0 }
}
impl ::core::convert::AsMut<serde_json::Value> for JsonConfig {
    fn as_mut(&mut self) -> &mut serde_json::Value { &mut self.0 }
}
impl ::core::convert::From<serde_json::Value> for JsonConfig {
    fn from(inner: serde_json::Value) -> Self { Self(inner) }
}
impl ::core::convert::From<JsonConfig> for serde_json::Value {
    fn from(wrapper: JsonConfig) -> Self { wrapper.0 }
}
impl crate::HasName for JsonConfig {
    fn name(&self) -> &str { ForeignEntity::name(&self.0) }
}
impl crate::StateEntity for JsonConfig {
    type Entry = StateEntry;

    const STATE_ENTRY: StateEntry = StateEntry::JsonConfig;

    fn description(&self) -> Option<&str> { ForeignEntity::description(&self.0) }

    fn summary(&self, id: crate::EntityId) -> crate::Summary { ForeignEntity::summary(&self.0, id) }
}
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, utoipa::ToSchema,
)]
#[serde(rename_all = "snake_case")]
/// Discriminator enum for entity types in the state.
///
/// Used to specify which entity type you're querying when using type-erased operations.
pub enum StateEntry {
    Pipeline,
    Source,
    ArchivedPipeline,
    Sink,
    JsonConfig,
}
impl StateEntry {
    pub fn as_ref(&self) -> &str {
        match self {
            Self::Pipeline => "pipeline",
            Self::Source => "source",
            Self::ArchivedPipeline => "archived_pipeline",
            Self::Sink => "sink",
            Self::JsonConfig => "json_config",
        }
    }
}
impl ::core::convert::AsRef<str> for StateEntry {
    fn as_ref(&self) -> &str { self.as_ref() }
}
impl ::std::str::FromStr for StateEntry {
    type Err = String;

    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
        match s {
            "pipeline" => Ok(Self::Pipeline),
            "source" => Ok(Self::Source),
            "archived_pipeline" => Ok(Self::ArchivedPipeline),
            "sink" => Ok(Self::Sink),
            "json_config" => Ok(Self::JsonConfig),
            _ => Err(format!("Unknown entity type: {0}", s)),
        }
    }
}
/// Trait for implementing entities from external crates.
///
/// This trait is generated in your crate to allow implementing it on foreign types
/// without violating Rust's orphan rules. Use with `#[collection(foreign)]`.
pub trait ForeignEntity: Clone + ::serde::Serialize + for<'de> ::serde::Deserialize<'de> {
    /// Returns the human-readable name of this entity instance
    fn name(&self) -> &str;
    /// Returns an optional description of this entity instance
    fn description(&self) -> Option<&str> { None }
    /// Returns a summary of this entity for listings
    fn summary(&self, id: crate::EntityId) -> crate::Summary {
        crate::Summary {
            id,
            name: self.name().to_string(),
            description: self.description().map(ToString::to_string),
        }
    }
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
/// Type-erased wrapper for all entity types.
///
/// Allows storing and passing different entity types through a common interface.
pub enum Entity {
    Pipeline(Pipeline),
    Source(Source),
    ArchivedPipeline(ArchivedPipeline),
    Sink(Sink),
    JsonConfig(JsonConfig),
}
impl From<&Entity> for StateEntry {
    fn from(entity: &Entity) -> Self {
        match entity {
            Entity::Pipeline(_) => StateEntry::Pipeline,
            Entity::Source(_) => StateEntry::Source,
            Entity::ArchivedPipeline(_) => StateEntry::ArchivedPipeline,
            Entity::Sink(_) => StateEntry::Sink,
            Entity::JsonConfig(_) => StateEntry::JsonConfig,
        }
    }
}
impl crate::StateEntity for Pipeline {
    type Entry = StateEntry;

    const STATE_ENTRY: StateEntry = StateEntry::Pipeline;
}
impl crate::StateEntity for Source {
    type Entry = StateEntry;

    const STATE_ENTRY: StateEntry = StateEntry::Source;
}
impl crate::StateEntity for Sink {
    type Entry = StateEntry;

    const STATE_ENTRY: StateEntry = StateEntry::Sink;
}
/// The main state struct with generated CRUD methods.
///
/// Contains all entity collections and provides type-safe operations.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct State {
    pub pipelines: crate::Collection<Pipeline>,
    pub sources:   crate::Collection<Source>,
    pub archived:  crate::Collection<ArchivedPipeline>,
    pub sinks:     SinkCollection,
    pub configs:   crate::Collection<JsonConfig>,
}
impl Default for State {
    fn default() -> Self { Self::new() }
}
impl State {
    /// Creates a new empty state
    pub fn new() -> Self {
        Self {
            pipelines: crate::Collection::new(),
            sources:   crate::Collection::new(),
            archived:  crate::Collection::new(),
            configs:   crate::Collection::new(),
            sinks:     Default::default(),
        }
    }

    /// Creates a new entity
    pub fn create_entity(&mut self, entity: Entity) -> crate::EntityId {
        use crate::StateCollection;
        match entity {
            Entity::Pipeline(inner) => self.pipelines.create(inner),
            Entity::Source(inner) => self.sources.create(inner),
            Entity::ArchivedPipeline(inner) => self.archived.create(inner),
            Entity::JsonConfig(inner) => self.configs.create(inner),
            Entity::Sink(inner) => self.sinks.create(inner),
        }
    }

    /// Updates an existing entity by ID
    pub fn update_entity(&mut self, id: &str, entity: Entity) -> crate::Result<()> {
        use crate::StateCollection;
        match entity {
            Entity::Pipeline(inner) => {
                self.pipelines.update(id, inner)?;
            }
            Entity::Source(inner) => {
                self.sources.update(id, inner)?;
            }
            Entity::ArchivedPipeline(inner) => {
                self.archived.update(id, inner)?;
            }
            Entity::JsonConfig(inner) => {
                self.configs.update(id, inner)?;
            }
            Entity::Sink(inner) => {
                self.sinks.update(id, inner)?;
            }
        }
        Ok(())
    }

    /// Removes an entity by ID and type
    pub fn remove_entity(&mut self, id: &str, entry: StateEntry) -> crate::Result<()> {
        use crate::StateCollection;
        match entry {
            StateEntry::Pipeline => self.pipelines.remove(id).map(|_| ()),
            StateEntry::Source => self.sources.remove(id).map(|_| ()),
            StateEntry::ArchivedPipeline => self.archived.remove(id).map(|_| ()),
            StateEntry::JsonConfig => self.configs.remove(id).map(|_| ()),
            StateEntry::Sink => self.sinks.remove(id).map(|_| ()),
        }
    }

    /// Gets an entity by ID and type
    pub fn get_entity(&self, id: &str, entry: StateEntry) -> Option<(crate::EntityId, Entity)> {
        use crate::StateCollection;
        match entry {
            StateEntry::Pipeline => self
                .pipelines
                .get_entity(id)
                .map(|(id, e)| (id.clone(), Entity::Pipeline(e.clone()))),
            StateEntry::Source => {
                self.sources.get_entity(id).map(|(id, e)| (id.clone(), Entity::Source(e.clone())))
            }
            StateEntry::ArchivedPipeline => self
                .archived
                .get_entity(id)
                .map(|(id, e)| (id.clone(), Entity::ArchivedPipeline(e.clone()))),
            StateEntry::JsonConfig => self
                .configs
                .get_entity(id)
                .map(|(id, e)| (id.clone(), Entity::JsonConfig(e.clone()))),
            StateEntry::Sink => {
                self.sinks.get_entity(id).map(|(id, e)| (id.clone(), Entity::Sink(e.clone())))
            }
        }
    }

    /// Lists all entities of a specific type
    pub fn list_entities(
        &self,
        entry: Option<StateEntry>,
    ) -> crate::hashbrown::HashMap<StateEntry, Vec<crate::Summary>> {
        use crate::StateCollection;
        let mut result = crate::hashbrown::HashMap::default();
        if entry.is_none() || entry == Some(StateEntry::Pipeline) {
            result.insert(StateEntry::Pipeline, self.pipelines.list());
        }
        if entry.is_none() || entry == Some(StateEntry::Source) {
            result.insert(StateEntry::Source, self.sources.list());
        }
        if entry.is_none() || entry == Some(StateEntry::ArchivedPipeline) {
            result.insert(StateEntry::ArchivedPipeline, self.archived.list());
        }
        if entry.is_none() || entry == Some(StateEntry::JsonConfig) {
            result.insert(StateEntry::JsonConfig, self.configs.list());
        }
        if entry.is_none() || entry == Some(StateEntry::Sink) {
            result.insert(StateEntry::Sink, self.sinks.list());
        }
        result
    }

    /// Searches entities across all collections
    pub fn search_entities(
        &self,
        needle: &str,
    ) -> crate::hashbrown::HashMap<StateEntry, crate::hashbrown::HashMap<crate::EntityId, Entity>>
    {
        use crate::StateCollection;
        let mut result = crate::hashbrown::HashMap::default();
        {
            let matches = self.pipelines.search_entities(needle);
            if !matches.is_empty() {
                let mut entities = crate::hashbrown::HashMap::default();
                for (id, entity) in matches {
                    entities.insert(id.clone(), Entity::Pipeline(entity.clone()));
                }
                result.insert(StateEntry::Pipeline, entities);
            }
        }
        {
            let matches = self.sources.search_entities(needle);
            if !matches.is_empty() {
                let mut entities = crate::hashbrown::HashMap::default();
                for (id, entity) in matches {
                    entities.insert(id.clone(), Entity::Source(entity.clone()));
                }
                result.insert(StateEntry::Source, entities);
            }
        }
        {
            let matches = self.archived.search_entities(needle);
            if !matches.is_empty() {
                let mut entities = crate::hashbrown::HashMap::default();
                for (id, entity) in matches {
                    entities.insert(id.clone(), Entity::ArchivedPipeline(entity.clone()));
                }
                result.insert(StateEntry::ArchivedPipeline, entities);
            }
        }
        {
            let matches = self.configs.search_entities(needle);
            if !matches.is_empty() {
                let mut entities = crate::hashbrown::HashMap::default();
                for (id, entity) in matches {
                    entities.insert(id.clone(), Entity::JsonConfig(entity.clone()));
                }
                result.insert(StateEntry::JsonConfig, entities);
            }
        }
        {
            let matches = self.sinks.search_entities(needle);
            if !matches.is_empty() {
                let mut entities = crate::hashbrown::HashMap::default();
                for (id, entity) in matches {
                    entities.insert(id.clone(), Entity::Sink(entity.clone()));
                }
                result.insert(StateEntry::Sink, entities);
            }
        }
        result
    }

    pub fn is_empty(&self) -> bool {
        self.pipelines.is_empty()
            && self.sources.is_empty()
            && self.archived.is_empty()
            && self.configs.is_empty()
            && self.sinks.is_empty()
            && true
    }
}
/// Type aliases for `Link<T>` for all entity types in this state
/// Type aliases for `Link<T>` for each entity type.
///
/// Provides convenient type names like `PipelineLink` instead of `Link<Pipeline>`.
pub mod link_aliases {
    use super::*;
    pub type PipelineLink = crate::Link<Pipeline>;
    pub type SourceLink = crate::Link<Source>;
    pub type ArchivedPipelineLink = crate::Link<ArchivedPipeline>;
    pub type JsonConfigLink = crate::Link<JsonConfig>;
    pub type SinkLink = crate::Link<Sink>;
}
impl ForeignEntity for serde_json::Value {
    fn name(&self) -> &str { self.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed") }

    fn description(&self) -> Option<&str> { self.get("description").and_then(|v| v.as_str()) }
}
/// OpenAPI documentation
#[derive(utoipa::OpenApi)]
#[openapi(
    paths(
        create_entity,
        list_entities,
        get_entity_by_id,
        update_entity,
        patch_entity_by_id,
        remove_entity,
    ),
    components(
        responses(
            OperationResponse,
            EntitiesResponse,
            ListResponse,
            GetEntityResponse,
            crate::ApiError,
        ),
        schemas(
            Entity,
            StateEntry,
            OperationResponse,
            EntitiesResponse,
            EntitiesMap,
            ListResponse,
            GetEntityResponse,
            crate::Summary,
            crate::EntityId,
            link_aliases::PipelineLink,
            link_aliases::SourceLink,
            link_aliases::ArchivedPipelineLink,
            link_aliases::SinkLink,
            link_aliases::JsonConfigLink
        )
    ),
    tags((name = "entity", description = "Entity management endpoints"))
)]
/// The Axum API wrapper struct with generated handler methods.
///
/// Provides REST API endpoints and event middleware for the state.
#[derive(Debug, Clone)]
pub struct ApiState {
    pub state: ::std::sync::Arc<::tokio::sync::RwLock<State>>,
}
impl ApiState {
    /// Creates a new API state wrapper
    pub fn new(state: State) -> Self {
        Self { state: ::std::sync::Arc::new(::tokio::sync::RwLock::new(state)) }
    }

    /// Creates a new wrapped state for use with Axum
    pub fn new_from_state(state: ::std::sync::Arc<::tokio::sync::RwLock<State>>) -> Self {
        Self { state }
    }
}
impl ApiState {
    /// Creates the Axum router with all entity CRUD endpoints
    /// Returns an Axum router with all API endpoints configured.
    pub fn router<S>(state: S) -> ::axum::Router<S>
    where
        S: Send + Sync + Clone + 'static,
        ApiState: ::axum::extract::FromRef<S>,
    {
        ::axum::Router::new()
            .route(
                "/",
                ::axum::routing::get(get_entities)
                    .put(create_entity)
                    .layer(::tower_http::compression::CompressionLayer::new()),
            )
            .route(
                "/list",
                ::axum::routing::get(list_all_entities)
                    .layer(::tower_http::compression::CompressionLayer::new()),
            )
            .route(
                "/list/{type}",
                ::axum::routing::get(list_entities)
                    .layer(::tower_http::compression::CompressionLayer::new()),
            )
            .route(
                "/{id}",
                ::axum::routing::get(get_entity_by_id)
                    .post(update_entity)
                    .patch(patch_entity_by_id),
            )
            .route("/{entry}/{id}", ::axum::routing::delete(remove_entity))
            .with_state(state)
    }

    /// Creates middleware that extracts ResponseEvent from response extensions and sends to channel
    ///
    /// The channel can send any type `T` that implements `From<ResponseEvent>`, allowing you to
    /// convert the event into your own enum variant (e.g., `events::Api::StateEvent(event)`).
    /// Middleware that emits events after CRUD operations for persistence integration.
    pub fn event_middleware<T>(
        event_tx: ::tokio::sync::mpsc::Sender<T>,
    ) -> impl Fn(
        ::axum::http::Request<::axum::body::Body>,
        ::axum::middleware::Next,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = ::axum::response::Response> + Send>,
    > + Clone
    where
        T: From<ResponseEvent> + Send + 'static,
    {
        move |req: ::axum::http::Request<::axum::body::Body>, next: ::axum::middleware::Next| {
            let tx = event_tx.clone();
            Box::pin(async move {
                let response = next.run(req).await;
                if let Some(event) = response.extensions().get::<ResponseEvent>() {
                    let converted: T = event.clone().into();
                    let _ = tx.send(converted).await;
                }
                response
            })
        }
    }
}
/// Query parameters for getting a single entity by ID and type
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub struct GetEntityQuery {
    #[serde(rename = "type")]
    entity_type: StateEntry,
}
/// Standard operation response with ID and optional message
/// Response type for API operations.
#[derive(
    Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema, utoipa::ToResponse,
)]
pub struct OperationResponse {
    #[schema(value_type = String, format = "uuid")]
    pub id:      crate::EntityId,
    pub message: String,
}
/// Response containing a single entity
/// Response type for API operations.
#[derive(
    Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema, utoipa::ToResponse,
)]
pub struct GetEntityResponse {
    id:     crate::EntityId,
    entity: Entity,
}
/// Response for full entity queries
/// Response type for API operations.
#[derive(
    Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema, utoipa::ToResponse,
)]
pub struct EntitiesResponse {
    pub entities: EntitiesMap,
}
/// Map of all entity collections grouped by type
/// Map of all entity collections grouped by type.
#[derive(Debug, Clone, serde::Deserialize, utoipa::ToSchema)]
pub struct EntitiesMap {
    pub entities:
        crate::hashbrown::HashMap<StateEntry, crate::hashbrown::HashMap<crate::EntityId, Entity>>,
}
/// Response for entity summary list queries
/// Response type for API operations.
#[derive(
    Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema, utoipa::ToResponse,
)]
pub struct ListResponse {
    #[schema(
        value_type = HashMap<StateEntry,
        Vec<crate::Summary>>,
        example = json!(
            {"pipeline":[{"id":"my-pipeline",
            "name":"My Pipeline",
            "description":"Example pipeline"}],
            "source":[{"id":"my-source",
            "name":"My Source",
            "description":"Example source"}]}
        )
    )]
    pub entities: crate::hashbrown::HashMap<StateEntry, Vec<crate::Summary>>,
}
/// Event emitted after CRUD operations
/// Events emitted after CRUD operations for event-driven persistence.
///
/// Use with `ApiState::event_middleware()` to handle state changes.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
pub enum ResponseEvent {
    Created { id: crate::EntityId, entity: Entity },
    Updated { id: crate::EntityId, entity: Entity },
    Deleted { id: crate::EntityId, entry: StateEntry },
}
impl ::serde::Serialize for EntitiesMap {
    fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
    where
        S: ::serde::Serializer,
    {
        use ::serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(Some(self.entities.len()))?;
        for (state_entry, entities) in &self.entities {
            let mut entity_map: crate::hashbrown::HashMap<
                crate::EntityId,
                crate::serde_json::Value,
            > = crate::hashbrown::HashMap::default();
            for (id, entity) in entities {
                let inner_value =
                    crate::serde_json::to_value(entity).map_err(::serde::ser::Error::custom)?;
                drop(entity_map.insert(id.clone(), inner_value));
            }
            map.serialize_entry(&state_entry.as_ref(), &entity_map)?;
        }
        map.end()
    }
}
/// Create a new entity
#[utoipa::path(
    put,
    path = "/",
    tag = "entity",
    request_body = Entity,
    responses(
        (status = 200, description = "Entity created successfully", body = OperationResponse),
        (status = 500, description = "Internal server error", body = crate::ApiError)
    )
)]
pub async fn create_entity(
    ::axum::extract::State(stately): ::axum::extract::State<ApiState>,
    ::axum::Json(entity): ::axum::Json<Entity>,
) -> ::axum::response::Response {
    use ::axum::response::IntoResponse;
    let mut state = stately.state.write().await;
    let id = state.create_entity(entity.clone());
    let mut response =
        ::axum::Json(OperationResponse { id: id.clone(), message: format!("Entity created") })
            .into_response();
    response.extensions_mut().insert(ResponseEvent::Created { id, entity });
    response
}
/// Update an existing entity (full replacement)
#[utoipa::path(
    post,
    path = "/{id}",
    tag = "entity",
    params(
        ("id" = String, Path, description = "Entity ID")
    ),
    request_body = Entity,
    responses(
        (status = 200, description = "Entity updated successfully", body = OperationResponse),
        (status = 500, description = "Internal server error", body = crate::ApiError)
    )
)]
pub async fn update_entity(
    ::axum::extract::State(stately): ::axum::extract::State<ApiState>,
    ::axum::extract::Path(id): ::axum::extract::Path<String>,
    ::axum::Json(entity): ::axum::Json<Entity>,
) -> ::axum::response::Response {
    use ::axum::response::IntoResponse;
    let mut state = stately.state.write().await;
    match state.update_entity(&id, entity.clone()) {
        Ok(_) => {
            let entity_id: crate::EntityId = id.into();
            let mut response = ::axum::Json(OperationResponse {
                id:      entity_id.clone(),
                message: format!("Entity updated"),
            })
            .into_response();
            response.extensions_mut().insert(ResponseEvent::Updated { id: entity_id, entity });
            response
        }
        Err(e) => e.into_response(),
    }
}
/// Patch an existing entity (same as update)
#[utoipa::path(
    patch,
    path = "/{id}",
    tag = "entity",
    params(
        ("id" = String, Path, description = "Entity ID")
    ),
    request_body = Entity,
    responses(
        (status = 200, description = "Entity patched successfully", body = OperationResponse),
        (status = 500, description = "Internal server error", body = crate::ApiError)
    )
)]
pub async fn patch_entity_by_id(
    ::axum::extract::State(stately): ::axum::extract::State<ApiState>,
    ::axum::extract::Path(id): ::axum::extract::Path<String>,
    ::axum::Json(entity): ::axum::Json<Entity>,
) -> ::axum::response::Response {
    use ::axum::response::IntoResponse;
    let mut state = stately.state.write().await;
    match state.update_entity(&id, entity.clone()) {
        Ok(_) => {
            let entity_id: crate::EntityId = id.into();
            let mut response = ::axum::Json(OperationResponse {
                id:      entity_id.clone(),
                message: format!("Entity patched"),
            })
            .into_response();
            response.extensions_mut().insert(ResponseEvent::Updated { id: entity_id, entity });
            response
        }
        Err(e) => e.into_response(),
    }
}
/// Remove an entity
#[utoipa::path(
    delete,
    path = "/{entry}/{id}",
    tag = "entity",
    params(
        ("entry" = StateEntry, Path, description = "Entity type"),
        ("id" = String, Path, description = "Entity ID")
    ),
    responses(
        (status = 200, description = "Entity removed successfully", body = OperationResponse),
        (status = 404, description = "Entity not found", body = crate::ApiError),
        (status = 500, description = "Internal server error", body = crate::ApiError)
    )
)]
pub async fn remove_entity(
    ::axum::extract::State(stately): ::axum::extract::State<ApiState>,
    ::axum::extract::Path((entry, id)): ::axum::extract::Path<(StateEntry, String)>,
) -> ::axum::response::Response {
    use ::axum::response::IntoResponse;
    let mut state = stately.state.write().await;
    if let Err(e) = state.remove_entity(&id, entry) {
        return e.into_response();
    }
    let entity_id: crate::EntityId = id.into();
    let mut response = ::axum::Json(OperationResponse {
        id:      entity_id.clone(),
        message: format!("Entity removed"),
    })
    .into_response();
    response.extensions_mut().insert(ResponseEvent::Deleted { id: entity_id, entry });
    response
}
/// List all entity summaries
#[utoipa::path(
    get,
    path = "/list",
    tag = "entity",
    responses(
        (status = 200, description = "List all entities", body = ListResponse)
    )
)]
pub async fn list_all_entities(
    ::axum::extract::State(stately): ::axum::extract::State<ApiState>,
) -> crate::Result<::axum::Json<ListResponse>> {
    let state = stately.state.read().await;
    let entities = state.list_entities(None);
    Ok(::axum::Json(ListResponse { entities }))
}
/// List entity summaries
#[utoipa::path(
    get,
    path = "/list/{type}",
    tag = "entity",
    params(
        ("type" = StateEntry, Path, description = "Entity type to list")
    ),
    responses(
        (status = 200, description = "List entities by type", body = ListResponse)
    )
)]
pub async fn list_entities(
    ::axum::extract::State(stately): ::axum::extract::State<ApiState>,
    ::axum::extract::Path(entity_type): ::axum::extract::Path<StateEntry>,
) -> crate::Result<::axum::Json<ListResponse>> {
    let state = stately.state.read().await;
    let entities = state.list_entities(Some(entity_type));
    Ok(::axum::Json(ListResponse { entities }))
}
/// Get all entities for all types
#[utoipa::path(
    get,
    path = "/",
    tag = "entity",
    params(
        ("name" = Option<String>, Query, description = "Identifier of entity, ie id or name"),
        ("type" = Option<StateEntry>, Query, description = "Type of entity")
    ),
    responses(
        (status = 200, description = "Get entities with filters", body = EntitiesResponse)
    )
)]
pub async fn get_entities(
    ::axum::extract::State(stately): ::axum::extract::State<ApiState>,
) -> crate::Result<::axum::Json<EntitiesResponse>> {
    let state = stately.state.read().await;
    let entities = state.search_entities("");
    Ok(::axum::Json(EntitiesResponse { entities: EntitiesMap { entities } }))
}
/// Get entity by ID and type
#[utoipa::path(
    get,
    path = "/{id}",
    tag = "entity",
    params(
        ("id" = String, Path, description = "Entity ID"),
        GetEntityQuery
    ),
    responses(
        (status = 200, description = "Successfully retrieved entity", body = GetEntityResponse),
        (status = 404, description = "Entity not found", body = crate::ApiError)
    )
)]
pub async fn get_entity_by_id(
    ::axum::extract::State(stately): ::axum::extract::State<ApiState>,
    ::axum::extract::Path(id): ::axum::extract::Path<String>,
    ::axum::extract::Query(query): ::axum::extract::Query<GetEntityQuery>,
) -> crate::Result<::axum::Json<GetEntityResponse>> {
    let state = stately.state.read().await;
    let Some((id, entity)) = state.get_entity(&id, query.entity_type) else {
        return Err(crate::Error::NotFound(format!("Entity with ID {0} not found", id)));
    };
    Ok(::axum::Json(GetEntityResponse { id, entity }))
}