ekodb_client 0.17.0

Official Rust client library for ekoDB - A high-performance database
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
//! Functions API for ekoDB client
//!
//! This module provides types and methods for working with functions,
//! allowing you to create, manage, and execute server-side sequences of Functions.

use crate::types::FieldType;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Build the structural placeholder `{"type": "Parameter", "name": <name>}`
/// that ekoDB's `resolve_json_parameters` recognizes inside
/// `Function::Insert.record`, `Function::Update.updates`,
/// `Function::UpdateById.updates`, `Function::FindOneAndUpdate.updates`,
/// `Function::BatchInsert.records`, and any `QueryExpression` filter value.
///
/// This is the structural alternative to the text-level `"{{name}}"`
/// placeholder form — use it when the parameter is a whole-object record or
/// a value whose type would be lost on a raw-JSON round-trip (Binary,
/// DateTime, UUID, Decimal, Duration, Number, Set, Vector). Requires
/// ekoDB >= 0.41.0 for the mutation-stage parameter-resolution
/// consistency fix.
///
/// # Example
///
/// ```
/// use ekodb_client::{parameter_ref, Function, UserFunction};
///
/// let create = UserFunction::new("items_create", "Create item")
///     .with_function(Function::Insert {
///         collection: "items".to_string(),
///         record: parameter_ref("record"),
///         bypass_ripple: None,
///         ttl: None,
///     });
/// ```
pub fn parameter_ref(name: impl Into<String>) -> serde_json::Value {
    serde_json::json!({
        "type": "Parameter",
        "name": name.into(),
    })
}

/// A reusable sequence of Functions stored in ekoDB.
/// Called by label via the `call_function` chat tool or REST API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserFunction {
    /// Unique identifier (ekoDB-generated)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    /// User-defined label (unique identifier)
    pub label: String,

    /// Human-readable name
    pub name: String,

    /// Optional description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Version string (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Parameter definitions (keyed by parameter name)
    #[serde(default)]
    pub parameters: HashMap<String, ParameterDefinition>,

    /// Functions to execute in sequence
    pub functions: Vec<Function>,

    /// Tags for categorization
    #[serde(default)]
    pub tags: Vec<String>,

    /// Creation timestamp (server-managed, read-only)
    #[serde(skip_serializing)]
    pub created_at: Option<DateTime<Utc>>,

    /// Last update timestamp (server-managed, read-only)
    #[serde(skip_serializing)]
    pub updated_at: Option<DateTime<Utc>>,
}

impl UserFunction {
    /// Create a new UserFunction
    pub fn new(label: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: None,
            label: label.into(),
            name: name.into(),
            description: None,
            version: None,
            parameters: HashMap::new(),
            functions: Vec::new(),
            tags: Vec::new(),
            created_at: None,
            updated_at: None,
        }
    }

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

    /// Set the version
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }

    /// Add a parameter definition
    pub fn with_parameter(mut self, param: ParameterDefinition) -> Self {
        self.parameters.insert(param.name.clone(), param);
        self
    }

    /// Add a Function
    pub fn with_function(mut self, function: Function) -> Self {
        self.functions.push(function);
        self
    }

    /// Add a tag
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }
}

/// Parameter definition for a function
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParameterDefinition {
    /// Parameter name (used as key in HashMap, not serialized)
    #[serde(skip_serializing, default)]
    pub name: String,

    /// Whether this parameter is required
    #[serde(default)]
    pub required: bool,

    /// Default value if not provided
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<FieldType>,

    /// Parameter description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl ParameterDefinition {
    /// Create a new parameter definition
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            required: false,
            default: None,
            description: None,
        }
    }

    /// Mark as required
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// Set default value
    pub fn with_default(mut self, default: FieldType) -> Self {
        self.default = Some(default);
        self
    }

    /// Set description
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Condition evaluation for function control flow (If statements)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
pub enum FunctionCondition {
    /// Check if field equals value in current records
    FieldEquals {
        field: String,
        value: serde_json::Value,
    },
    /// Check if field exists in current records
    FieldExists { field: String },
    /// Check if we have any records
    HasRecords,
    /// Check if record count equals N
    CountEquals { count: usize },
    /// Check if record count > N
    CountGreaterThan { count: usize },
    /// Check if record count < N
    CountLessThan { count: usize },
    /// Logical AND
    And { conditions: Vec<FunctionCondition> },
    /// Logical OR
    Or { conditions: Vec<FunctionCondition> },
    /// Logical NOT
    Not { condition: Box<FunctionCondition> },
}

/// Function step in a pipeline
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "PascalCase")]
#[allow(
    clippy::enum_variant_names,
    clippy::vec_box,
    clippy::upper_case_acronyms
)]
pub enum Function {
    /// Find all records in collection
    FindAll { collection: String },

    /// Query records with advanced options
    Query {
        collection: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        filter: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        sort: Option<Vec<SortFieldConfig>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        limit: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        skip: Option<serde_json::Value>,
    },

    /// Project specific fields
    Project { fields: Vec<String>, exclude: bool },

    /// Group records with functions
    Group {
        by_fields: Vec<String>,
        functions: Vec<GroupFunctionConfig>,
    },

    /// Count records
    Count { output_field: String },

    /// Find record by ID
    FindById {
        collection: String,
        record_id: String,
    },

    /// Find one record by key/value
    FindOne {
        collection: String,
        key: String,
        value: serde_json::Value,
    },

    /// Insert a record
    Insert {
        collection: String,
        record: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        bypass_ripple: Option<bool>,
        #[serde(skip_serializing_if = "Option::is_none")]
        ttl: Option<serde_json::Value>,
    },

    /// Update records matching filter
    Update {
        collection: String,
        filter: serde_json::Value,
        updates: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        bypass_ripple: Option<bool>,
        #[serde(skip_serializing_if = "Option::is_none")]
        ttl: Option<serde_json::Value>,
    },

    /// Update record by ID
    UpdateById {
        collection: String,
        record_id: String,
        updates: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        bypass_ripple: Option<bool>,
        #[serde(skip_serializing_if = "Option::is_none")]
        ttl: Option<serde_json::Value>,
    },

    /// Find one record and update atomically
    FindOneAndUpdate {
        collection: String,
        filter: serde_json::Value,
        updates: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        bypass_ripple: Option<bool>,
        #[serde(skip_serializing_if = "Option::is_none")]
        ttl: Option<serde_json::Value>,
    },

    /// Update with actions (increment/decrement)
    UpdateWithAction {
        collection: String,
        filter: serde_json::Value,
        actions: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        bypass_ripple: Option<bool>,
    },

    /// Delete records matching filter
    Delete {
        collection: String,
        filter: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        bypass_ripple: Option<bool>,
    },

    /// Delete record by ID
    DeleteById {
        collection: String,
        record_id: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        bypass_ripple: Option<bool>,
    },

    /// Batch insert records
    BatchInsert {
        collection: String,
        records: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        bypass_ripple: Option<bool>,
    },

    /// Batch delete records
    BatchDelete {
        ids: serde_json::Value,
        #[serde(default)]
        bypass_ripple: bool,
    },

    /// HTTP request
    HttpRequest {
        url: String,
        #[serde(default = "default_method")]
        method: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        headers: Option<HashMap<String, String>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        body: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        timeout_seconds: Option<u64>,
        #[serde(skip_serializing_if = "Option::is_none")]
        output_field: Option<String>,
    },

    /// Vector search
    VectorSearch {
        query_vector: Vec<f32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        options: Option<serde_json::Value>,
    },

    /// Text search
    TextSearch {
        collection: String,
        query_text: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        fields: Option<Vec<String>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        limit: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        fuzzy: Option<bool>,
    },

    /// Hybrid search (text + vector)
    HybridSearch {
        text_query: String,
        vector_query: Vec<f32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        options: Option<serde_json::Value>,
    },

    /// AI Chat completion
    Chat {
        messages: Vec<ChatMessage>,
        #[serde(skip_serializing_if = "Option::is_none")]
        model: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        temperature: Option<f32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        max_tokens: Option<i32>,
    },

    /// Generate embeddings for field in records
    Embed {
        input_field: String,
        output_field: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        model: Option<String>,
    },

    /// Conditional execution
    If {
        condition: FunctionCondition,
        then_functions: Vec<Box<Function>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        else_functions: Option<Vec<Box<Function>>>,
    },

    /// For each record, execute Functions
    ForEach { functions: Vec<Box<Function>> },

    /// Call a saved UserFunction by label
    CallFunction {
        function_label: String,
        params: Option<HashMap<String, serde_json::Value>>,
    },

    /// Create a savepoint for partial rollback
    CreateSavepoint { name: String },

    /// Rollback to a specific savepoint
    RollbackToSavepoint { name: String },

    /// Release a savepoint (no longer needed)
    ReleaseSavepoint { name: String },

    // =========================================================================
    // KV Store Operations
    // =========================================================================
    /// Get a value from the KV store
    /// Returns {value: <data>} on hit, {value: null} on miss
    KvGet { key: serde_json::Value },

    /// Set a value in the KV store
    KvSet {
        key: serde_json::Value,
        value: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        ttl: Option<serde_json::Value>,
    },

    /// Delete a key from the KV store
    KvDelete { key: serde_json::Value },

    /// Check if a key exists in the KV store
    KvExists {
        key: serde_json::Value,
        #[serde(skip_serializing_if = "Option::is_none")]
        output_field: Option<String>,
    },

    /// Query the KV store with a pattern
    KvQuery {
        #[serde(skip_serializing_if = "Option::is_none")]
        pattern: Option<serde_json::Value>,
        #[serde(default)]
        include_expired: bool,
    },

    /// SWR (Stale-While-Revalidate) pattern for external API caching
    /// Automatically handles: KV cache check → HTTP request → KV cache set → optional audit storage
    SWR {
        cache_key: String,
        ttl: serde_json::Value,
        url: String,
        method: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        headers: Option<HashMap<String, String>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        body: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        timeout_seconds: Option<u64>,
        #[serde(skip_serializing_if = "Option::is_none")]
        output_field: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        collection: Option<String>,
    },

    /// Bcrypt-hash a plaintext value and write the result onto every
    /// record in the working data (creates a single result record if the
    /// working set is empty). Use in a compound `users_register` function.
    /// Requires ekoDB >= 0.41.0.
    BcryptHash {
        /// Plaintext to hash, typically `"{{password}}"`.
        plain: String,
        /// bcrypt cost factor (4..=31). Defaults to 12 when None.
        #[serde(skip_serializing_if = "Option::is_none")]
        cost: Option<u32>,
        /// Field name to write the bcrypt hash string into.
        output_field: String,
    },

    /// Verify a plaintext against a bcrypt hash stored on the first
    /// record in the working data; writes a boolean result into
    /// `output_field`. Pair with an `If` stage for login flows.
    /// Requires ekoDB >= 0.41.0.
    BcryptVerify {
        /// Plaintext to verify, typically `"{{password}}"`.
        plain: String,
        /// Name of the field on the current record holding the stored
        /// bcrypt hash (e.g. `"password_hash"`).
        hash_field: String,
        /// Field name to write the boolean result into.
        output_field: String,
    },

    /// Generate a cryptographically-random token and add it to every
    /// record in the working data. Requires ekoDB >= 0.41.0.
    RandomToken {
        /// Number of random bytes (1..=1024).
        bytes: usize,
        /// "hex" | "base64" | "base64url" (default "hex").
        #[serde(skip_serializing_if = "Option::is_none")]
        encoding: Option<String>,
        /// Field name to write the encoded token into.
        output_field: String,
    },

    // =========================================================================
    // Error Handling & Control Flow
    // =========================================================================
    /// Try/Catch error handling for graceful failure recovery.
    /// Executes try_functions, and if any fail, executes catch_functions.
    TryCatch {
        try_functions: Vec<Box<Function>>,
        catch_functions: Vec<Box<Function>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        output_error_field: Option<String>,
    },

    /// Execute multiple functions in parallel (concurrently).
    /// All functions run simultaneously, results are merged.
    Parallel {
        functions: Vec<Box<Function>>,
        wait_for_all: bool,
    },

    /// Sleep/delay execution for rate limiting or timing control.
    Sleep { duration_ms: serde_json::Value },

    // =========================================================================
    // Response Formatting
    // =========================================================================
    /// Return a shaped response (final output formatting).
    /// Constructs the final response object from current execution context.
    Return {
        fields: HashMap<String, serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        status_code: Option<u16>,
    },

    // =========================================================================
    // Data Validation
    // =========================================================================
    /// Validate data against a JSON schema before processing.
    Validate {
        schema: serde_json::Value,
        data_field: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        on_error: Option<Vec<Box<Function>>>,
    },
}

fn default_method() -> String {
    "GET".to_string()
}

/// Chat message for AI operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
    pub role: String,
    pub content: String,
}

impl ChatMessage {
    /// Create a system message
    pub fn system(content: impl Into<String>) -> Self {
        Self {
            role: "system".to_string(),
            content: content.into(),
        }
    }

    /// Create a user message
    pub fn user(content: impl Into<String>) -> Self {
        Self {
            role: "user".to_string(),
            content: content.into(),
        }
    }

    /// Create an assistant message
    pub fn assistant(content: impl Into<String>) -> Self {
        Self {
            role: "assistant".to_string(),
            content: content.into(),
        }
    }
}

/// Group function configuration for Group stage
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupFunctionConfig {
    pub output_field: String,
    pub operation: GroupFunctionOp,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_field: Option<String>,
}

impl GroupFunctionConfig {
    /// Create a new group function
    pub fn new(output_field: impl Into<String>, operation: GroupFunctionOp) -> Self {
        Self {
            output_field: output_field.into(),
            operation,
            input_field: None,
        }
    }

    /// Set the input field
    pub fn with_input_field(mut self, field: impl Into<String>) -> Self {
        self.input_field = Some(field.into());
        self
    }
}

/// Group function operation type
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum GroupFunctionOp {
    Sum,
    Average,
    Count,
    Min,
    Max,
    First,
    Last,
    Push,
}

/// Sort field configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SortFieldConfig {
    pub field: String,
    #[serde(default = "default_ascending")]
    pub ascending: bool,
}

impl SortFieldConfig {
    /// Create a new sort field (ascending by default)
    pub fn new(field: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            ascending: true,
        }
    }

    /// Set descending order
    pub fn descending(mut self) -> Self {
        self.ascending = false;
        self
    }

    /// Set ascending order
    pub fn ascending(mut self) -> Self {
        self.ascending = true;
        self
    }
}

fn default_ascending() -> bool {
    true
}

/// Function execution result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionResult {
    /// Resulting records from the pipeline
    pub records: Vec<crate::Record>,

    /// Statistics about the function execution
    pub stats: FunctionStats,
}

/// Statistics about function execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionStats {
    /// Number of input records
    pub input_count: usize,

    /// Number of output records
    pub output_count: usize,

    /// Execution time in milliseconds
    pub execution_time_ms: u128,

    /// Number of stages executed
    pub stages_executed: usize,

    /// Per-stage statistics
    pub stage_stats: Vec<StageStats>,
}

/// Statistics for a single stage
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StageStats {
    /// Stage name
    pub stage: String,

    /// Input count to stage
    pub input_count: usize,

    /// Output count from stage
    pub output_count: usize,

    /// Execution time for this stage in milliseconds
    pub execution_time_ms: u128,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn try_catch_round_trip() {
        let stage = Function::TryCatch {
            try_functions: vec![Box::new(Function::FindAll {
                collection: "users".to_string(),
            })],
            catch_functions: vec![Box::new(Function::Insert {
                collection: "errors".to_string(),
                record: json!({"msg": "failed"}),
                bypass_ripple: None,
                ttl: None,
            })],
            output_error_field: Some("api_error".to_string()),
        };
        let json = serde_json::to_string(&stage).unwrap();
        let parsed: Function = serde_json::from_str(&json).unwrap();
        match parsed {
            Function::TryCatch {
                try_functions,
                catch_functions,
                output_error_field,
            } => {
                assert_eq!(try_functions.len(), 1);
                assert_eq!(catch_functions.len(), 1);
                assert_eq!(output_error_field, Some("api_error".to_string()));
            }
            other => panic!("Expected TryCatch, got {:?}", other),
        }
    }

    #[test]
    fn parallel_round_trip() {
        let stage = Function::Parallel {
            functions: vec![
                Box::new(Function::FindAll {
                    collection: "a".to_string(),
                }),
                Box::new(Function::FindAll {
                    collection: "b".to_string(),
                }),
            ],
            wait_for_all: false,
        };
        let json = serde_json::to_string(&stage).unwrap();
        let parsed: Function = serde_json::from_str(&json).unwrap();
        match parsed {
            Function::Parallel {
                functions,
                wait_for_all,
            } => {
                assert_eq!(functions.len(), 2);
                assert!(!wait_for_all);
            }
            other => panic!("Expected Parallel, got {:?}", other),
        }
    }

    #[test]
    fn sleep_round_trip() {
        let stage = Function::Sleep {
            duration_ms: json!(1000),
        };
        let json = serde_json::to_string(&stage).unwrap();
        let parsed: Function = serde_json::from_str(&json).unwrap();
        match parsed {
            Function::Sleep { duration_ms } => {
                assert_eq!(duration_ms, json!(1000));
            }
            other => panic!("Expected Sleep, got {:?}", other),
        }
    }

    #[test]
    fn sleep_with_placeholder() {
        let stage = Function::Sleep {
            duration_ms: json!("{{delay}}"),
        };
        let json = serde_json::to_string(&stage).unwrap();
        assert!(json.contains("{{delay}}"));
        let parsed: Function = serde_json::from_str(&json).unwrap();
        match parsed {
            Function::Sleep { duration_ms } => {
                assert_eq!(duration_ms, json!("{{delay}}"));
            }
            other => panic!("Expected Sleep, got {:?}", other),
        }
    }

    #[test]
    fn return_round_trip() {
        let mut fields = HashMap::new();
        fields.insert("message".to_string(), json!("ok"));
        fields.insert("user_id".to_string(), json!("{{id}}"));
        let stage = Function::Return {
            fields,
            status_code: Some(201),
        };
        let json = serde_json::to_string(&stage).unwrap();
        let parsed: Function = serde_json::from_str(&json).unwrap();
        match parsed {
            Function::Return {
                fields,
                status_code,
            } => {
                assert_eq!(fields.get("message"), Some(&json!("ok")));
                assert_eq!(status_code, Some(201));
            }
            other => panic!("Expected Return, got {:?}", other),
        }
    }

    #[test]
    fn return_omits_status_code_when_none() {
        let mut fields = HashMap::new();
        fields.insert("success".to_string(), json!(true));
        let stage = Function::Return {
            fields,
            status_code: None,
        };
        let json = serde_json::to_string(&stage).unwrap();
        assert!(!json.contains("status_code"));
    }

    #[test]
    fn validate_round_trip() {
        let stage = Function::Validate {
            schema: json!({"type": "object", "required": ["name"]}),
            data_field: "{{input}}".to_string(),
            on_error: Some(vec![Box::new(Function::FindAll {
                collection: "errors".to_string(),
            })]),
        };
        let json = serde_json::to_string(&stage).unwrap();
        let parsed: Function = serde_json::from_str(&json).unwrap();
        match parsed {
            Function::Validate {
                schema,
                data_field,
                on_error,
            } => {
                assert_eq!(schema, json!({"type": "object", "required": ["name"]}));
                assert_eq!(data_field, "{{input}}");
                assert_eq!(on_error.unwrap().len(), 1);
            }
            other => panic!("Expected Validate, got {:?}", other),
        }
    }

    #[test]
    fn validate_omits_on_error_when_none() {
        let stage = Function::Validate {
            schema: json!({"type": "object"}),
            data_field: "record".to_string(),
            on_error: None,
        };
        let json = serde_json::to_string(&stage).unwrap();
        assert!(!json.contains("on_error"));
    }

    /// Regression test: the server may store functions with newer stage types
    /// (Return, TryCatch, etc.). When the client deserializes a list of
    /// UserFunctions, it must not choke on these variants.
    #[test]
    fn deserialize_user_function_with_return_stage() {
        let json = r#"{
            "id": "abc123",
            "label": "api_handler",
            "name": "API Handler",
            "functions": [
                {"type": "FindAll", "collection": "users"},
                {"type": "Return", "fields": {"data": "{{result}}"}, "status_code": 200}
            ]
        }"#;
        let uf: UserFunction = serde_json::from_str(json).unwrap();
        assert_eq!(uf.functions.len(), 2);
        match &uf.functions[1] {
            Function::Return {
                fields,
                status_code,
            } => {
                assert!(fields.contains_key("data"));
                assert_eq!(*status_code, Some(200));
            }
            other => panic!("Expected Return, got {:?}", other),
        }
    }
}