superposition_provider 0.107.1

Open feature provider for Superposition.
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
use std::collections::HashMap;

use log::debug;
use serde_json::{Map, Value};
use superposition_core::experiment::{
    ExperimentConfig, ExperimentGroups, FfiExperimentGroup,
};
use superposition_core::{Experiments, FfiExperiment};
use superposition_sdk::types::{
    ExperimentStatusType as SDKExperimentStatusType, GroupType as SdkGroupType,
};
use superposition_types::database::models::cac::{DependencyGraph, DimensionType};
use superposition_types::database::models::experimentation::{
    Bucket, Buckets, ExperimentStatusType, GroupType, Variant, VariantType, Variants,
};
use superposition_types::{
    Cac, Condition, Config, Context, DimensionInfo, Exp, ExtendedMap, OverrideWithKeys,
    Overrides,
};

use crate::{conversions, types::*};

pub struct ConversionUtils;

impl ConversionUtils {
    pub fn convert_get_config_response(
        response: superposition_sdk::operation::get_config::GetConfigOutput,
    ) -> Result<Config> {
        debug!("Converting get_config response to superposition_types::Config");

        // Convert default configs - these are already Value types
        let default_configs = conversions::hashmap_to_map(response.default_configs);

        // Convert overrides - HashMap<String, HashMap<String, Document>>
        let overrides = response
            .overrides
            .into_iter()
            .map(|(k, v)| {
                let override_values = conversions::hashmap_to_map(v);
                let override_obj = Cac::<Overrides>::try_from(override_values)
                    .map_err(|e| SuperpositionError::SerializationError(e.to_string()))?;
                Ok((k, override_obj.into_inner()))
            })
            .collect::<Result<HashMap<String, Overrides>>>()?;

        // Convert contexts - Vec<ContextPartial>
        let contexts = response
            .contexts
            .into_iter()
            .map(|context_partial| {
                // Convert condition Document to Map<String, Value>
                let condition_map =
                    conversions::hashmap_to_map(context_partial.condition);

                // Create Condition directly from Map<String, Value>
                let condition =
                    Cac::<Condition>::try_from(condition_map).map_err(|e| {
                        SuperpositionError::SerializationError(format!(
                            "Invalid condition: {}",
                            e
                        ))
                    })?;

                let override_with_keys =
                    OverrideWithKeys::try_from(context_partial.override_with_keys)
                        .map_err(|e| {
                            SuperpositionError::SerializationError(format!(
                                "Invalid override_with_keys: {e}",
                            ))
                        })?;

                Ok(Context {
                    id: context_partial.id,
                    condition: condition.into_inner(),
                    priority: context_partial.priority,
                    weight: context_partial.weight,
                    override_with_keys,
                })
            })
            .collect::<Result<Vec<Context>>>()?;

        let dimensions = response
            .dimensions
            .into_iter()
            .map(|(key, dimension_info)| {
                let schema = conversions::hashmap_to_map(dimension_info.schema);
                let dim_info = DimensionInfo {
                    schema: ExtendedMap::from(schema),
                    position: dimension_info.position,
                    dimension_type: Self::try_dimension_type(
                        dimension_info.dimension_type,
                    )?,
                    dependency_graph: DependencyGraph(dimension_info.dependency_graph),
                    value_compute_function_name: dimension_info
                        .value_compute_function_name,
                };
                Ok((key, dim_info))
            })
            .collect::<Result<HashMap<String, DimensionInfo>>>()?;

        let config = Config {
            contexts,
            overrides,
            default_configs: default_configs.into(),
            dimensions,
        };

        debug!("Successfully converted config with {} contexts, {} overrides, {} default configs", 
               config.contexts.len(), config.overrides.len(), config.default_configs.len());

        Ok(config)
    }

    fn try_dimension_type(
        dim_type: superposition_sdk::types::DimensionType,
    ) -> Result<DimensionType> {
        match dim_type {
            superposition_sdk::types::DimensionType::RemoteCohort(cohort_based_on) => {
                Ok(DimensionType::RemoteCohort(cohort_based_on))
            }
            superposition_sdk::types::DimensionType::LocalCohort(cohort_based_on) => {
                Ok(DimensionType::LocalCohort(cohort_based_on))
            }
            superposition_sdk::types::DimensionType::Regular => {
                Ok(DimensionType::Regular {})
            }
            _ => Err(SuperpositionError::SerializationError(
                "Unknown dimension type".to_string(),
            )),
        }
    }

    pub fn convert_value_to_config(map: &Map<String, Value>) -> Result<Config> {
        // Extract contexts array
        let contexts =
            map.get("contexts")
                .and_then(|v| v.as_array())
                .ok_or_else(|| {
                    SuperpositionError::ConfigError(
                        "Missing or invalid 'contexts' field".to_string(),
                    )
                })?;

        let parsed_contexts: Result<Vec<Context>> = contexts
            .iter()
            .map(|context_val| {
                let context_obj = context_val.as_object().ok_or_else(|| {
                    SuperpositionError::ConfigError(
                        "Context must be an object".to_string(),
                    )
                })?;

                // Extract required fields
                let id = context_obj
                    .get("id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| {
                        SuperpositionError::ConfigError(
                            "Missing or invalid 'id' field in context".to_string(),
                        )
                    })?
                    .to_string();

                let priority = context_obj
                    .get("priority")
                    .and_then(|v| v.as_i64())
                    .ok_or_else(|| {
                        SuperpositionError::ConfigError(
                            "Missing or invalid 'priority' field in context".to_string(),
                        )
                    })? as i32;

                let weight = context_obj
                    .get("weight")
                    .and_then(|v| v.as_i64())
                    .ok_or_else(|| {
                        SuperpositionError::ConfigError(
                            "Missing or invalid 'weight' field in context".to_string(),
                        )
                    })? as i32;

                let override_with_keys: Vec<String> = context_obj
                    .get("override_with_keys")
                    .and_then(|v| v.as_array())
                    .ok_or_else(|| {
                        SuperpositionError::ConfigError(
                            "Missing or invalid 'override_with_keys' field in context"
                                .to_string(),
                        )
                    })?
                    .iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect();
                let override_with_keys = OverrideWithKeys::try_from(override_with_keys)
                    .map_err(|e| {
                    SuperpositionError::ConfigError(format!(
                        "Invalid override_with_keys: {e}",
                    ))
                })?;

                // Extract condition
                let condition_map = context_obj
                    .get("condition")
                    .and_then(|v| v.as_object())
                    .ok_or_else(|| {
                        SuperpositionError::ConfigError(
                            "Missing or invalid 'condition' field in context".to_string(),
                        )
                    })?
                    .clone();

                let condition = Cac::<Condition>::try_from(condition_map)
                    .map_err(|e| {
                        SuperpositionError::SerializationError(format!(
                            "Invalid condition: {}",
                            e
                        ))
                    })?
                    .into_inner();

                Ok(Context {
                    id,
                    condition,
                    priority,
                    weight,
                    override_with_keys,
                })
            })
            .collect();

        let contexts = parsed_contexts?;

        // Extract overrides object
        let overrides_obj = map
            .get("overrides")
            .and_then(|v| v.as_object())
            .ok_or_else(|| {
                SuperpositionError::ConfigError(
                    "Missing or invalid 'overrides' field".to_string(),
                )
            })?;

        let mut overrides: HashMap<String, Overrides> = HashMap::new();
        for (key, value) in overrides_obj {
            let override_map = value
                .as_object()
                .ok_or_else(|| {
                    SuperpositionError::ConfigError(format!(
                        "Override '{}' must be an object",
                        key
                    ))
                })?
                .clone();

            let override_obj = Cac::<Overrides>::try_from(override_map)
                .map_err(|e| {
                    SuperpositionError::SerializationError(format!(
                        "Invalid override '{}': {}",
                        key, e
                    ))
                })?
                .into_inner();

            overrides.insert(key.clone(), override_obj);
        }

        // Extract default_configs object
        let default_configs = map
            .get("default_configs")
            .and_then(|v| v.as_object())
            .ok_or_else(|| {
                SuperpositionError::ConfigError(
                    "Missing or invalid 'default_configs' field".to_string(),
                )
            })?
            .clone();

        let dimensions = map
            .get("dimensions")
            .and_then(|v| v.as_object())
            .map(|dim| {
                dim.iter()
                    .map(|(key, value)| {
                        let dim_info: DimensionInfo =
                            serde_json::from_value(value.clone()).map_err(|e| {
                                SuperpositionError::SerializationError(format!(
                                    "Invalid dimension info for '{}': {}",
                                    key, e
                                ))
                            })?;
                        Ok((key.clone(), dim_info))
                    })
                    .collect::<Result<HashMap<String, DimensionInfo>>>()
            })
            .unwrap_or_else(|| Ok(HashMap::new()))?;

        Ok(Config {
            contexts,
            overrides,
            default_configs: default_configs.into(),
            dimensions,
        })
    }

    /// Convert list_experiment SDK response to structured experiment data
    pub fn convert_experiments_response(
        response: Vec<superposition_sdk::types::ExperimentResponse>,
    ) -> Result<Experiments> {
        debug!("Converting experiments response");

        let mut trimmed_exp_list: Experiments = Vec::new();

        for exp in response {
            // Convert experiment context (condition)
            let condition_map = conversions::hashmap_to_map(exp.context);

            // Convert variants
            let mut variants: Variants = Variants::new(vec![]);
            for variant in exp.variants {
                let variant_type = match variant.variant_type {
                    superposition_sdk::types::VariantType::Control => {
                        VariantType::CONTROL
                    }
                    superposition_sdk::types::VariantType::Experimental => {
                        VariantType::EXPERIMENTAL
                    }
                    _ => {
                        return Err(SuperpositionError::SerializationError(
                            "Unknown variant type".to_string(),
                        ))
                    }
                };

                // Convert variant overrides - check if overrides exist
                let overrides_map = conversions::hashmap_to_map(variant.overrides);

                let override_ = Exp::<Overrides>::try_from(overrides_map)
                    .map_err(|e| SuperpositionError::SerializationError(e.to_string()))?;

                let variant_value = Variant {
                    id: variant.id,
                    variant_type,
                    context_id: variant.context_id,
                    override_id: variant.override_id,
                    overrides: override_,
                };
                variants.push(variant_value);
            }
            let context = Exp::<Condition>::try_from(condition_map)
                .map_err(|e| {
                    SuperpositionError::SerializationError(format!(
                        "Invalid condition: {}",
                        e
                    ))
                })?
                .into_inner();
            let status = match exp.status {
                SDKExperimentStatusType::Created => ExperimentStatusType::CREATED,
                SDKExperimentStatusType::Inprogress => ExperimentStatusType::INPROGRESS,
                SDKExperimentStatusType::Paused => ExperimentStatusType::PAUSED,
                SDKExperimentStatusType::Concluded => ExperimentStatusType::CONCLUDED,
                SDKExperimentStatusType::Discarded => ExperimentStatusType::DISCARDED,
                _ => {
                    return Err(SuperpositionError::SerializationError(
                        "Unknown experiment status".to_string(),
                    ))
                }
            };
            let experiment = FfiExperiment {
                id: exp.id,
                context,
                variants,
                traffic_percentage: exp.traffic_percentage as u8,
                status,
            };

            trimmed_exp_list.push(experiment);
        }

        Ok(trimmed_exp_list)
    }

    pub fn convert_experiment_groups_response(
        response: Vec<superposition_sdk::types::ExperimentGroupResponse>,
    ) -> Result<ExperimentGroups> {
        debug!("Converting experiment groups response");

        let mut trimmed_group_list: ExperimentGroups = Vec::new();

        for exp_group in response {
            // Convert experiment context (condition)
            let condition_map = conversions::hashmap_to_map(exp_group.context);

            let context = Exp::<Condition>::try_from(condition_map)
                .map_err(|e| {
                    SuperpositionError::SerializationError(format!(
                        "Invalid condition: {}",
                        e
                    ))
                })?
                .into_inner();
            let group_type = match exp_group.group_type {
                SdkGroupType::SystemGenerated => GroupType::SystemGenerated,
                SdkGroupType::UserCreated => GroupType::UserCreated,
                _ => {
                    return Err(SuperpositionError::SerializationError(
                        "Unknown group type".to_string(),
                    ))
                }
            };

            let experiment_group = FfiExperimentGroup {
                id: exp_group.id,
                context,
                traffic_percentage: exp_group.traffic_percentage as u8,
                member_experiment_ids: exp_group.member_experiment_ids,
                group_type,
                buckets: Buckets::try_from(
                    exp_group
                        .buckets
                        .into_iter()
                        .map(|b| {
                            b.map(|bucket| Bucket {
                                variant_id: bucket.variant_id,
                                experiment_id: bucket.experiment_id,
                            })
                        })
                        .collect::<Vec<_>>(),
                )
                .map_err(SuperpositionError::SerializationError)?,
            };

            trimmed_group_list.push(experiment_group);
        }

        Ok(trimmed_group_list)
    }

    pub fn convert_experiment_config_response(
        response: superposition_sdk::operation::get_experiment_config::GetExperimentConfigOutput,
    ) -> Result<ExperimentConfig> {
        debug!("Converting experiment config response");

        let experiments = Self::convert_experiments_response(response.experiments)?;
        let experiment_groups =
            Self::convert_experiment_groups_response(response.experiment_groups)?;

        Ok(ExperimentConfig {
            experiments,
            experiment_groups,
        })
    }

    /// Convert Config back to the legacy format for compatibility with existing provider logic
    pub fn config_to_legacy_format(config: &Config) -> HashMap<String, Value> {
        let mut result = HashMap::new();

        // Convert default_configs
        result.insert(
            "default_configs".to_string(),
            Value::Object((*config.default_configs).clone()),
        );

        // Convert overrides to the expected format
        let mut overrides_map = Map::new();
        for (key, overrides) in &config.overrides {
            let override_value: Map<String, Value> = overrides.clone().into();
            overrides_map.insert(key.clone(), Value::Object(override_value));
        }
        result.insert("overrides".to_string(), Value::Object(overrides_map));

        // Convert contexts
        let contexts_array: Vec<Value> = config
            .contexts
            .iter()
            .map(|context| {
                let condition_map: Map<String, Value> = context.condition.clone().into();
                serde_json::json!({
                    "id": context.id,
                    "priority": context.priority,
                    "weight": context.weight,
                    "override_with_keys": context.override_with_keys,
                    "condition": condition_map
                })
            })
            .collect();
        result.insert("contexts".to_string(), Value::Array(contexts_array));

        debug!(
            "Converted Config to legacy format with {} sections",
            result.len()
        );
        result
    }

    /// Evaluate config using superposition_types logic and return resolved values
    pub fn evaluate_config(
        config: Config,
        dimension_data: &Map<String, Value>,
        prefix_filter: Option<&[String]>,
    ) -> Result<HashMap<String, Value>> {
        debug!(
            "Evaluating config with dimension data: {:?}",
            dimension_data.keys().collect::<Vec<_>>()
        );

        // Filter by dimensions first
        let filtered_config = config.filter_by_dimensions(dimension_data);
        debug!(
            "Filtered config has {} contexts after dimension filtering",
            filtered_config.contexts.len()
        );

        // Apply prefix filtering if specified
        let final_config = if let Some(prefixes) = prefix_filter {
            let prefix_set: std::collections::HashSet<String> =
                prefixes.iter().cloned().collect();
            filtered_config.filter_by_prefix(&prefix_set)
        } else {
            filtered_config
        };

        debug!(
            "Final config has {} contexts after prefix filtering",
            final_config.contexts.len()
        );

        // Start with default configs
        let mut result = final_config.default_configs.into_inner();

        // Apply overrides based on context priority (higher priority wins)
        let mut sorted_contexts = final_config.contexts.clone();
        sorted_contexts.sort_by_key(|c| std::cmp::Reverse(c.priority)); // Sort by priority descending

        for context in sorted_contexts {
            if let Some(override_key) = context.override_with_keys.first() {
                if let Some(overrides) = final_config.overrides.get(override_key) {
                    let override_map: Map<String, Value> = overrides.clone().into();
                    for (override_key, value) in override_map {
                        result.insert(override_key, value);
                        debug!("Applied override for key");
                    }
                }
            }
        }

        debug!(
            "Config evaluation completed with {} final keys",
            result.len()
        );

        // Convert Map<String, Value> to HashMap<String, Value>
        let final_result: HashMap<String, Value> = result.into_iter().collect();
        Ok(final_result)
    }
}