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
#![expect(unused_crate_dependencies)]
//! Integration tests for stately proc macros and generated code

use serde::{Deserialize, Serialize};
use stately::HasName;
use stately::prelude::*;

// Test entities
#[stately::entity]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Pipeline {
    name:        String,
    description: Option<String>,
}

#[stately::entity]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
struct Source {
    name: String,
    url:  String,
}

#[stately::entity]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
struct Sink {
    name:        String,
    destination: String,
}

#[stately::entity(singleton, description = "Global configuration")]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
struct Config {
    max_connections: usize,
    timeout_seconds: u64,
}

// Additional entities for demonstrating collection syntax variations
#[stately::entity]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
struct Task {
    name:   String,
    status: String,
}

#[stately::entity]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
struct Job {
    name:     String,
    priority: u32,
}

// Type alias for custom StateCollection demonstration
type TaskCache = Collection<Task>;

// Test state demonstrating all collection syntax permutations
#[stately::state]
struct TestState {
    // Singleton
    #[singleton]
    config:     Config,
    // Case 1: Implicit collection (no attribute)
    pipelines:  Pipeline,
    // Case 2: Explicit collection (same as case 1, with variant to avoid collision)
    #[collection(variant = "ExplicitSource")]
    sources:    Source,
    // Case 3: Custom StateCollection type (using type alias)
    #[collection(TaskCache, variant = "CachedTask")]
    tasks:      Task,
    // Case 4: Variant override only (reusing Pipeline entity)
    #[collection(variant = "ArchivedPipeline")]
    archived:   Pipeline,
    // Case 5: Custom type + variant override (reusing Task entity and TaskCache type)
    #[collection(TaskCache, variant = "BackgroundTask")]
    background: Task,

    // Standard case
    sinks: Sink,
    jobs:  Job,
}

#[test]
fn test_state_new() {
    let state = TestState::new();
    assert!(state.pipelines.is_empty());
    assert!(state.sources.is_empty());
    assert!(state.sinks.is_empty());
    // Singleton is initialized with Default value
    assert_eq!(state.config.get(), &Config::default());
}

#[test]
fn test_create_entities() {
    let mut state = TestState::new();

    let source_id = state
        .sources
        .create(Source { name: "test-source".to_string(), url: "http://example.com".to_string() });

    let sink_id = state.sinks.create(Sink {
        name:        "test-sink".to_string(),
        destination: "s3://bucket".to_string(),
    });

    let pipeline_id = state.pipelines.create(Pipeline {
        name:        "test-pipeline".to_string(),
        description: Some("A test pipeline".to_string()),
    });

    assert_eq!(state.sources.len(), 1);
    assert_eq!(state.sinks.len(), 1);
    assert_eq!(state.pipelines.len(), 1);

    // Verify we can retrieve them
    assert!(state.sources.get_by_id(&source_id).is_some());
    assert!(state.sinks.get_by_id(&sink_id).is_some());
    assert!(state.pipelines.get_by_id(&pipeline_id).is_some());
}

#[test]
fn test_get_entity_by_id() {
    let mut state = TestState::new();

    let source = Source { name: "my-source".to_string(), url: "http://example.com".to_string() };
    let source_id = state.sources.create(source.clone());

    assert!(!state.is_empty());

    let result = state.get_entity(&source_id, StateEntry::ExplicitSource);
    assert!(result.is_some());

    let (id, entity) = result.unwrap();
    assert_eq!(id, source_id);

    match entity {
        Entity::ExplicitSource(s) => assert_eq!(s, source),
        _ => panic!("Wrong entity type"),
    }
}

#[test]
fn test_get_entity_by_name() {
    let mut state = TestState::new();

    let source = Source { name: "my-source".to_string(), url: "http://example.com".to_string() };
    drop(state.sources.create(source.clone()));

    let result = state.get_entity("my-source", StateEntry::ExplicitSource);
    assert!(result.is_some());

    let (_id, entity) = result.unwrap();
    match entity {
        Entity::ExplicitSource(s) => assert_eq!(s, source),
        _ => panic!("Wrong entity type"),
    }
}

#[test]
fn test_list_all_entities() {
    let mut state = TestState::new();

    let source1_id = state
        .sources
        .create(Source { name: "source1".to_string(), url: "http://example.com".to_string() });
    drop(
        state
            .sources
            .create(Source { name: "source2".to_string(), url: "http://example.org".to_string() }),
    );
    drop(
        state.sinks.create(Sink {
            name:        "sink1".to_string(),
            destination: "s3://bucket".to_string(),
        }),
    );

    let all_entities = state.list_entities(None);

    assert_eq!(all_entities.len(), 8); // 8 entity types (config singleton + pipelines + sources + tasks + archived + background + sinks + jobs)
    assert_eq!(all_entities.get(&StateEntry::ExplicitSource).map(Vec::len), Some(2));
    assert_eq!(all_entities.get(&StateEntry::Sink).map(Vec::len), Some(1));

    let collected = state.sources.get_entities();
    assert_eq!(collected.len(), 2);

    let err_res = state.sources.update("non_existent", Source {
        name: "source3".to_string(),
        url:  "http://example.net".to_string(),
    });
    assert!(err_res.is_err());
    let removed = state.sources.remove(&source1_id).expect("source1 exists");
    assert!(removed.name() == "source1");
    assert!(!state.sources.is_empty());
}

#[test]
fn test_list_entities_by_type() {
    let mut state = TestState::new();

    drop(
        state
            .sources
            .create(Source { name: "source1".to_string(), url: "http://example.com".to_string() }),
    );
    drop(
        state
            .sources
            .create(Source { name: "source2".to_string(), url: "http://example.org".to_string() }),
    );
    drop(
        state.sinks.create(Sink {
            name:        "sink1".to_string(),
            destination: "s3://bucket".to_string(),
        }),
    );

    let sources = state.list_entities(Some(StateEntry::ExplicitSource));
    assert_eq!(sources.len(), 1);
    assert_eq!(sources.get(&StateEntry::ExplicitSource).map(Vec::len), Some(2));

    let sinks = state.list_entities(Some(StateEntry::Sink));
    assert_eq!(sinks.len(), 1);
    assert_eq!(sinks.get(&StateEntry::Sink).map(Vec::len), Some(1));

    let all_sinks = state.sinks.iter().map(|(k, v)| (k.clone(), v.clone())).collect::<Vec<_>>();
    assert!(all_sinks.len() == 1);
}

#[test]
fn test_search_entities() {
    let mut state = TestState::new();

    drop(state.sources.create(Source {
        name: "api-source".to_string(),
        url:  "http://api.example.com".to_string(),
    }));
    drop(state.sources.create(Source {
        name: "database-source".to_string(),
        url:  "postgresql://localhost".to_string(),
    }));
    drop(state.pipelines.create(Pipeline {
        name:        "api-pipeline".to_string(),
        description: Some("Processes API data".to_string()),
    }));

    // Search for "api" - should match source name and pipeline name/description
    let results = state.search_entities("api");
    assert!(results.contains_key(&StateEntry::ExplicitSource));
    assert!(results.contains_key(&StateEntry::Pipeline));

    let source_results = results.get(&StateEntry::ExplicitSource).unwrap();
    assert_eq!(source_results.len(), 1);

    let pipeline_results = results.get(&StateEntry::Pipeline).unwrap();
    assert_eq!(pipeline_results.len(), 1);

    // Search for "database" - should only match one source
    let results = state.search_entities("database");
    assert_eq!(results.len(), 1);
    assert!(results.contains_key(&StateEntry::ExplicitSource));
}

#[test]
fn test_update_entity() {
    let mut state = TestState::new();

    let source = Source { name: "my-source".to_string(), url: "http://example.com".to_string() };
    let source_id = state.sources.create(source);

    // Update by ID
    let updated_source =
        Source { name: "my-source".to_string(), url: "http://updated.com".to_string() };
    let result = state.sources.update(&source_id, updated_source.clone());
    assert!(result.is_ok());

    let retrieved = state.sources.get_by_id(&source_id).unwrap();
    assert_eq!(retrieved.url, "http://updated.com");
}

#[test]
fn test_update_entity_by_id() {
    let mut state = TestState::new();

    let source = Source { name: "my-source".to_string(), url: "http://example.com".to_string() };
    let source_id = state.sources.create(source);

    // Update by ID
    let updated_source =
        Source { name: "my-source".to_string(), url: "http://updated.com".to_string() };
    let result = state.sources.update(&source_id, updated_source);
    assert!(result.is_ok());

    let retrieved = state.sources.get_by_id(&source_id).unwrap();
    assert_eq!(retrieved.url, "http://updated.com");
}

#[test]
fn test_remove_entity() {
    let mut state = TestState::new();

    let source = Source { name: "my-source".to_string(), url: "http://example.com".to_string() };
    let source_id = state.sources.create(source.clone());

    assert_eq!(state.sources.len(), 1);
    assert_eq!(state.sources.inner().len(), 1);

    let removed = state.sources.remove(&source_id);
    assert!(removed.is_ok());
    assert_eq!(removed.unwrap(), source);

    assert_eq!(state.sources.len(), 0);
    assert!(state.sources.get_by_id(&source_id).is_none());
}

#[test]
fn test_singleton_operations() {
    let mut state = TestState::new();

    // Set singleton
    let config = Config { max_connections: 100, timeout_seconds: 30 };
    state.config.set(config.clone());
    assert_eq!(state.config.get(), &config);
    assert!(!state.config.is_empty());

    let new_collection = Singleton::<Config>::load(vec![(EntityId::singleton(), config.clone())]);
    assert_eq!(new_collection.get(), &config);

    // Update singleton
    let updated_config = Config { max_connections: 200, timeout_seconds: 60 };
    state.config.set(updated_config.clone());
    assert_eq!(state.config.get(), &updated_config);

    state.config.get_mut().max_connections = 250;
    match state.get_entity(&EntityId::singleton(), StateEntry::Config) {
        Some((_, Entity::Config(config))) => assert_eq!(config.max_connections, 250),
        _ => panic!("Entity not found"),
    }

    let returned = state.config.get_entity("");
    assert!(returned.is_some());

    let collected = state.config.get_entities();
    assert!(collected.len() == 1);

    let err_res = state.config.remove("");
    assert!(err_res.is_err());

    let result = state.config.update("", Config { max_connections: 300, timeout_seconds: 90 });
    assert!(result.is_ok());

    let create_id = state.config.create(Config { max_connections: 400, timeout_seconds: 120 });
    assert_eq!(create_id, EntityId::singleton());
}

/// Test all 5 permutations of collection syntax using the main `TestState`
#[test]
fn test_custom_collection_syntax() {
    let mut state = TestState::new();

    // Test Case 1: Implicit collection (pipelines field)
    let pipeline1 = Pipeline {
        name:        "implicit-pipeline".to_string(),
        description: Some("Created in implicit collection".to_string()),
    };
    let id1 = state.pipelines.create(pipeline1.clone());
    assert_eq!(state.pipelines.len(), 1);

    // Test Case 2: Explicit collection with variant override (sources field -> ExplicitSource)
    let source =
        Source { name: "explicit-source".to_string(), url: "http://example.com".to_string() };
    let id2 = state.sources.create(source.clone());
    assert_eq!(state.sources.len(), 1);

    // Test Case 3: Custom StateCollection type (tasks field -> CachedTask)
    let task = Task { name: "cached-task".to_string(), status: "pending".to_string() };
    let id3 = state.tasks.create(task.clone());
    assert_eq!(state.tasks.len(), 1);

    // Test Case 4: Variant override only (archived field -> ArchivedPipeline)
    let pipeline2 = Pipeline {
        name:        "archived-pipeline".to_string(),
        description: Some("Created in archived collection".to_string()),
    };
    let id4 = state.archived.create(ArchivedPipeline(pipeline2.clone()));
    assert_eq!(state.archived.len(), 1);

    // Test Case 5: Custom type + variant override (background field -> BackgroundTask)
    let task2 = Task { name: "background-task".to_string(), status: "running".to_string() };
    let id5 = state.background.create(BackgroundTask(task2.clone()));
    assert_eq!(state.background.len(), 1);

    // Test that each variant is distinct in StateEntry enum
    let list_all = state.list_entities(None);
    assert_eq!(list_all.len(), 8); // All 8 entity types

    // Test retrieval by variant
    let result1 = state.get_entity(&id1, StateEntry::Pipeline);
    assert!(result1.is_some());
    if let Entity::Pipeline(p) = result1.unwrap().1 {
        assert_eq!(p, pipeline1);
    } else {
        panic!("Wrong entity type");
    }

    let result2 = state.get_entity(&id2, StateEntry::ExplicitSource);
    assert!(result2.is_some());
    if let Entity::ExplicitSource(s) = result2.unwrap().1 {
        assert_eq!(s, source);
    } else {
        panic!("Wrong entity type");
    }

    let result3 = state.get_entity(&id3, StateEntry::CachedTask);
    assert!(result3.is_some());
    if let Entity::CachedTask(t) = result3.unwrap().1 {
        assert_eq!(t, task);
    } else {
        panic!("Wrong entity type");
    }

    let result4 = state.get_entity(&id4, StateEntry::ArchivedPipeline);
    assert!(result4.is_some());
    if let Entity::ArchivedPipeline(p) = result4.unwrap().1 {
        assert_eq!(p.0, pipeline2); // Access inner value of wrapper
    } else {
        panic!("Wrong entity type");
    }

    let result5 = state.get_entity(&id5, StateEntry::BackgroundTask);
    assert!(result5.is_some());
    if let Entity::BackgroundTask(t) = result5.unwrap().1 {
        assert_eq!(t.0, task2); // Access inner value of wrapper
    } else {
        panic!("Wrong entity type");
    }

    // Test update operations
    let updated_task =
        Task { name: "background-task".to_string(), status: "completed".to_string() };
    assert!(state.background.update(&id5, BackgroundTask(updated_task.clone())).is_ok());
    let retrieved = state.background.get_by_id(&id5).unwrap();
    assert_eq!(retrieved.status, "completed");

    // Test remove operations
    assert!(state.archived.remove(&id4).is_ok());
    assert_eq!(state.archived.len(), 0);
}

#[test]
fn test_state_entry_constants() {
    // Verify that STATE_ENTRY constants are based on the VARIANT names (unique per field)
    // This ensures each collection is uniquely identified, even when the same type is reused
    use stately::StateEntity;

    // Types without variant override have STATE_ENTRY matching their type name
    assert_eq!(Pipeline::STATE_ENTRY.as_ref(), "pipeline");
    assert_eq!(Sink::STATE_ENTRY.as_ref(), "sink");
    assert_eq!(Config::STATE_ENTRY.as_ref(), "config");
    assert_eq!(Job::STATE_ENTRY.as_ref(), "job");

    // Types with variant override (even first occurrence) use the variant name
    assert_eq!(Source::STATE_ENTRY.as_ref(), "explicit_source"); // Only occurrence, but has variant override
    assert_eq!(Task::STATE_ENTRY.as_ref(), "cached_task"); // First occurrence has variant override

    // Wrapper types have STATE_ENTRY matching their WRAPPER/VARIANT name
    assert_eq!(ArchivedPipeline::STATE_ENTRY.as_ref(), "archived_pipeline");
    assert_eq!(BackgroundTask::STATE_ENTRY.as_ref(), "background_task");

    // Verify StateEntry enum variants serialize to their variant name in snake_case
    assert_eq!(StateEntry::Pipeline.as_ref(), "pipeline");
    assert_eq!(StateEntry::ExplicitSource.as_ref(), "explicit_source"); // Variant name, not type
    assert_eq!(StateEntry::Sink.as_ref(), "sink");
    assert_eq!(StateEntry::Config.as_ref(), "config");
    assert_eq!(StateEntry::CachedTask.as_ref(), "cached_task"); // Variant name, not type
    assert_eq!(StateEntry::ArchivedPipeline.as_ref(), "archived_pipeline"); // Wrapper variant
    assert_eq!(StateEntry::BackgroundTask.as_ref(), "background_task"); // Wrapper variant
    assert_eq!(StateEntry::Job.as_ref(), "job");
}

#[test]
fn test_state_serialization_roundtrip() {
    let mut state = TestState::new();

    // Create various entities across all collection types
    let pipeline_id = state.pipelines.create(Pipeline {
        name:        "main-pipeline".to_string(),
        description: Some("Main data pipeline".to_string()),
    });

    let source_id = state.sources.create(Source {
        name: "api-source".to_string(),
        url:  "https://api.example.com".to_string(),
    });

    let task_id = state
        .tasks
        .create(Task { name: "process-task".to_string(), status: "pending".to_string() });

    let archived_id = state.archived.create(ArchivedPipeline::from(Pipeline {
        name:        "archived-pipeline".to_string(),
        description: Some("Old pipeline".to_string()),
    }));

    let background_id = state.background.create(BackgroundTask::from(Task {
        name:   "background-job".to_string(),
        status: "running".to_string(),
    }));

    let _sink_id = state.sinks.create(Sink {
        name:        "output-sink".to_string(),
        destination: "s3://bucket/path".to_string(),
    });

    // Update singleton config
    state
        .config
        .update("default", Config { max_connections: 100, timeout_seconds: 30 })
        .unwrap();

    // Serialize to JSON
    let json = serde_json::to_string_pretty(&state).expect("Failed to serialize state");

    // Verify the JSON structure doesn't have "inner" fields for wrappers/singletons
    assert!(!json.contains("\"inner\""), "Serialized JSON should not contain 'inner' fields");

    // Deserialize back
    let deserialized: TestState = serde_json::from_str(&json).expect("Failed to deserialize state");

    // Verify all entities are preserved
    assert_eq!(deserialized.pipelines.get_by_id(&pipeline_id).unwrap().name, "main-pipeline");
    assert_eq!(deserialized.sources.get_by_id(&source_id).unwrap().url, "https://api.example.com");
    assert_eq!(deserialized.tasks.get_by_id(&task_id).unwrap().status, "pending");
    assert_eq!(deserialized.archived.get_by_id(&archived_id).unwrap().name, "archived-pipeline");
    assert_eq!(deserialized.background.get_by_id(&background_id).unwrap().status, "running");

    // Verify singleton config
    let config = deserialized.config.get_entity("default").unwrap().1;
    assert_eq!(config.max_connections, 100);
    assert_eq!(config.timeout_seconds, 30);

    // Verify collection counts
    assert_eq!(deserialized.pipelines.len(), 1);
    assert_eq!(deserialized.sources.len(), 1);
    assert_eq!(deserialized.tasks.len(), 1);
    assert_eq!(deserialized.archived.len(), 1);
    assert_eq!(deserialized.background.len(), 1);
    assert_eq!(deserialized.sinks.len(), 1);
}

#[test]
fn test_wrapper_transparency() {
    // Test that wrapper types serialize transparently (no "inner" field)
    use stately::StateCollection;

    let mut state = TestState::new();

    // Create an entity in a wrapped collection (ArchivedPipeline wraps Pipeline)
    let id = state.archived.create(ArchivedPipeline::from(Pipeline {
        name:        "test".to_string(),
        description: Some("test desc".to_string()),
    }));

    // Serialize just the collection
    let json = serde_json::to_string(&state.archived).expect("Failed to serialize collection");

    // Should be a map of IDs to Pipeline objects, NOT {inner: {...}}
    assert!(!json.contains("\"inner\""), "Wrapper should be transparent in serialization");

    // Deserialize and verify
    let deserialized: Collection<ArchivedPipeline> =
        serde_json::from_str(&json).expect("Failed to deserialize");
    assert_eq!(deserialized.get_by_id(&id).unwrap().name, "test");
}

#[test]
fn test_singleton_serialization() {
    // Test that singletons serialize transparently
    let mut state = TestState::new();

    state
        .config
        .update("default", Config { max_connections: 50, timeout_seconds: 15 })
        .unwrap();

    // Serialize just the singleton
    let json = serde_json::to_string(&state.config).expect("Failed to serialize singleton");

    // Should serialize as just the Config object, not {inner: {...}}
    assert!(!json.contains("\"inner\""), "Singleton should be transparent in serialization");

    // Should be able to deserialize directly from the entity JSON
    let deserialized: Singleton<Config> =
        serde_json::from_str(&json).expect("Failed to deserialize");
    assert_eq!(deserialized.get().max_connections, 50);
    assert_eq!(deserialized.get().timeout_seconds, 15);
}