superposition_provider 0.106.0

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
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
use std::collections::HashMap;
use std::sync::Arc;

use log::{debug, error, info, warn};
pub use open_feature::{
    provider::{ProviderMetadata, ProviderStatus, ResolutionDetails},
    EvaluationContext,
};
use serde_json::Value;
use superposition_core::experiment::ExperimentGroups;
use superposition_core::{
    eval_config, get_applicable_variants, Experiments, MergeStrategy,
};
use superposition_types::{Config, DimensionInfo};
use tokio::join;
use tokio::sync::RwLock;
use tokio::time::{sleep, Duration};
use tokio_util::sync::CancellationToken;

use crate::types::*;
use crate::utils::ConversionUtils;

#[derive(Debug, Clone)]
pub struct CacConfig {
    superposition_options: SuperpositionOptions,
    options: ConfigurationOptions,
    fallback_config: Option<serde_json::Map<String, Value>>,
    cached_config: Arc<RwLock<Option<Config>>>,
    last_updated: Arc<RwLock<Option<chrono::DateTime<chrono::Utc>>>>,
    polling_task_cancellation_token: Arc<RwLock<Option<CancellationToken>>>,
}

impl CacConfig {
    pub fn new(
        superposition_options: SuperpositionOptions,
        options: ConfigurationOptions,
    ) -> Self {
        Self {
            superposition_options,
            fallback_config: options.fallback_config.clone(),
            options,
            cached_config: Arc::new(RwLock::new(None)),
            last_updated: Arc::new(RwLock::new(None)),
            polling_task_cancellation_token: Arc::new(RwLock::new(None)),
        }
    }

    pub async fn create_config(&self) -> Result<()> {
        info!("Creating CAC configuration...");

        // Fetch initial config
        let latest_config = self.get_config(&self.superposition_options).await;
        match latest_config {
            Ok(config) => {
                let mut cached_config = self.cached_config.write().await;
                *cached_config = Some(config);
                let mut last_updated = self.last_updated.write().await;
                *last_updated = Some(chrono::Utc::now());
                info!("CAC config fetched successfully");
            }
            Err(e) => {
                let mut cached_config = self.cached_config.write().await;
                if cached_config.is_none() {
                    // If no cached config, use fallback if available
                    if let Some(fallback) = &self.fallback_config {
                        *cached_config =
                            Some(ConversionUtils::convert_value_to_config(fallback)?);
                        info!("Using fallback config due to initial fetch failure");
                    }
                } else {
                    error!("Failed to fetch initial config: {}", e);
                    return Err(e);
                }
            }
        }

        // Start refresh strategy
        match &self.options.refresh_strategy {
            RefreshStrategy::Polling(polling_strategy) => {
                info!(
                    "Using PollingStrategy: interval={}s, timeout={}s",
                    polling_strategy.interval,
                    polling_strategy.timeout.unwrap_or(30)
                );
                let task_token = self.start_polling(polling_strategy.interval).await;
                let mut polling_task_cancellation_token =
                    self.polling_task_cancellation_token.write().await;
                *polling_task_cancellation_token = Some(task_token);
            }
            RefreshStrategy::OnDemand(on_demand_strategy) => {
                info!(
                    "Using OnDemandStrategy: ttl={}s, use_stale_on_error={}, timeout={}s",
                    on_demand_strategy.ttl,
                    on_demand_strategy.use_stale_on_error.unwrap_or(false),
                    on_demand_strategy.timeout.unwrap_or(30)
                );
            }
            RefreshStrategy::Watch(_) => {
                info!("Using Watch refresh strategy");
            }
            RefreshStrategy::Manual => {
                info!("Using Manual refresh strategy");
            }
        }

        Ok(())
    }

    async fn start_polling(&self, interval: u64) -> CancellationToken {
        let superposition_options = self.superposition_options.clone();
        let cached_config = self.cached_config.clone();
        let last_updated = self.last_updated.clone();
        let cancellation_token = CancellationToken::new();
        let cancellation_token_clone = cancellation_token.clone();

        tokio::spawn(async move {
            tokio::select! {
                _ = cancellation_token_clone.cancelled() => {
                    info!("shutting down polling task gracefully");
                },
                _ = async {
                    loop {
                        match Self::get_config_static(&superposition_options).await {
                            Ok(config) => {
                                let mut cached = cached_config.write().await;
                                *cached = Some(config);
                                let mut updated = last_updated.write().await;
                                *updated = Some(chrono::Utc::now());
                                debug!("CAC config updated via polling");
                            }
                            Err(e) => {
                                error!("Polling error: {}", e);
                            }
                        }
                        sleep(Duration::from_secs(interval)).await;
                    }
                } => {}
            }
        });

        cancellation_token
    }

    pub async fn on_demand_config(&self, ttl: u64, use_stale: bool) -> Result<Config> {
        let now = chrono::Utc::now();
        let last_updated;
        {
            last_updated = self.last_updated.read().await;
        }
        let should_refresh = match *last_updated {
            Some(last) => (now - last).num_seconds() > ttl as i64,
            None => true,
        };

        if should_refresh {
            debug!("TTL expired. Fetching config on-demand");
            match self.get_config(&self.superposition_options).await {
                Ok(config) => {
                    let mut cached_config = self.cached_config.write().await;
                    *cached_config = Some(config.clone());
                    let mut last_updated_mut = self.last_updated.write().await;
                    *last_updated_mut = Some(chrono::Utc::now());
                    info!("Config fetched successfully on-demand");
                    return Ok(config);
                }
                Err(e) => {
                    warn!("On-demand fetch failed: {}", e);
                    if !use_stale {
                        return Err(e);
                    }
                    info!("Using stale config due to error");
                }
            }
        }

        // Return cached config
        let cached_config = self.cached_config.read().await;
        match cached_config.as_ref() {
            Some(config) => Ok(config.clone()),
            None => Err(SuperpositionError::ConfigError(
                "No cached config available".into(),
            )),
        }
    }

    async fn get_config(&self, options: &SuperpositionOptions) -> Result<Config> {
        Self::get_config_static(options).await
    }

    async fn get_config_static(options: &SuperpositionOptions) -> Result<Config> {
        use superposition_sdk::{Client, Config as SdkConfig};

        info!("Fetching config from Superposition service using SDK");

        // Create SDK config
        let sdk_config = SdkConfig::builder()
            .endpoint_url(&options.endpoint)
            .bearer_token(options.token.clone().into())
            .behavior_version_latest()
            .build();

        // Create Superposition client
        let client = Client::from_conf(sdk_config);

        // Call the get_config API
        let response = client
            .get_config()
            .workspace_id(&options.workspace_id)
            .org_id(&options.org_id)
            .send()
            .await
            .map_err(|e| {
                let error = format!("Failed to get config: {}", e);
                SuperpositionError::NetworkError(error)
            })?;

        // Use ConversionUtils to convert to proper Config type
        let config = ConversionUtils::convert_get_config_response(response)?;

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

        Ok(config)
    }

    pub async fn get_cached_config(&self) -> Option<Config> {
        let cached_config = self.cached_config.read().await;
        cached_config.clone()
    }

    /// Evaluate configuration for given context and return resolved values
    pub async fn evaluate_config(
        &self,
        query_data: &serde_json::Map<String, Value>,
        prefix_filter: Option<&[String]>,
    ) -> Result<serde_json::Map<String, Value>> {
        let cached_config = self.cached_config.read().await;
        match cached_config.as_ref() {
            Some(cached_config) => {
                // Use ConversionUtils to evaluate config
                eval_config(
                    (*cached_config.default_configs).clone(),
                    &cached_config.contexts,
                    &cached_config.overrides,
                    &cached_config.dimensions,
                    query_data,
                    MergeStrategy::MERGE,
                    prefix_filter.map(|p| p.to_vec()),
                )
                .map_err(|e| {
                    SuperpositionError::ConfigError(format!(
                        "Failed to evaluate config: {}",
                        e
                    ))
                })
            }
            None => Err(SuperpositionError::ConfigError(
                "No cached config available".into(),
            )),
        }
    }

    pub async fn close(&self) -> Result<()> {
        // Stop polling task
        let mut polling_task_cancellation_token =
            self.polling_task_cancellation_token.write().await;
        if let Some(task) = polling_task_cancellation_token.take() {
            task.cancel();
        }

        // Clear caches
        let mut cached_config = self.cached_config.write().await;
        *cached_config = None;

        Ok(())
    }
}

/// Experimentation Configuration client
#[derive(Debug, Clone)]
pub struct ExperimentationConfig {
    superposition_options: SuperpositionOptions,
    options: ExperimentationOptions,
    cached_experiments: Arc<RwLock<Option<Experiments>>>,
    cached_experiment_groups: Arc<RwLock<Option<ExperimentGroups>>>,
    last_updated: Arc<RwLock<Option<chrono::DateTime<chrono::Utc>>>>,
    polling_task_cancellation_token: Arc<RwLock<Option<CancellationToken>>>,
}

impl ExperimentationConfig {
    pub fn new(
        superposition_options: SuperpositionOptions,
        options: ExperimentationOptions,
    ) -> Self {
        Self {
            superposition_options,
            options,
            cached_experiments: Arc::new(RwLock::new(None)),
            cached_experiment_groups: Arc::new(RwLock::new(None)),
            last_updated: Arc::new(RwLock::new(None)),
            polling_task_cancellation_token: Arc::new(RwLock::new(None)),
        }
    }

    pub async fn create_config(&self) -> Result<()> {
        info!("Creating Experimentation configuration...");

        // Fetch initial experiments and experiment groups
        let (latest_experiments, latest_experiment_groups) = join!(
            self.get_experiments(&self.superposition_options),
            self.get_experiment_groups(&self.superposition_options)
        );
        match (latest_experiments, latest_experiment_groups) {
            (Ok(Some(experiments)), Ok(Some(experiment_groups))) => {
                let mut cached_experiments = self.cached_experiments.write().await;
                *cached_experiments = Some(experiments);
                let mut cached_experiment_groups =
                    self.cached_experiment_groups.write().await;
                *cached_experiment_groups = Some(experiment_groups);
                let mut last_updated = self.last_updated.write().await;
                *last_updated = Some(chrono::Utc::now());
                info!("Experiments fetched successfully");
            }
            (Ok(None), Ok(None)) => {
                warn!("No experiments or experiment groups returned from initial fetch");
            }
            (Err(e), _) | (_, Err(e)) => {
                error!(
                    "Failed to fetch initial experiments or experiment groups: {}",
                    e
                );
                return Err(e);
            }
            (_, _) => {
                error!("Failed to fetch either experiments or experiment groups");
                return Err(SuperpositionError::ConfigError(
                    "Failed to fetch either experiments or experiment groups".into(),
                ));
            }
        }

        // Start refresh strategy
        match &self.options.refresh_strategy {
            RefreshStrategy::Polling(polling_strategy) => {
                info!(
                    "Using PollingStrategy for experiments: interval={}s",
                    polling_strategy.interval
                );
                let task_token = self.start_polling(polling_strategy.interval).await;
                let mut polling_task_cancellation_token =
                    self.polling_task_cancellation_token.write().await;
                *polling_task_cancellation_token = Some(task_token);
            }
            RefreshStrategy::OnDemand(on_demand_strategy) => {
                info!(
                    "Using OnDemandStrategy for experiments: ttl={}s",
                    on_demand_strategy.ttl
                );
            }
            RefreshStrategy::Watch(_) => {
                info!("Using Watch refresh strategy for experiments");
            }
            RefreshStrategy::Manual => {
                info!("Using Manual refresh strategy for experiments");
            }
        }

        Ok(())
    }

    async fn start_polling(&self, interval: u64) -> CancellationToken {
        let superposition_options = self.superposition_options.clone();
        let cached_experiments = self.cached_experiments.clone();
        let cached_experiment_groups = self.cached_experiment_groups.clone();
        let last_updated = self.last_updated.clone();
        let cancellation_token = CancellationToken::new();
        let cancellation_token_clone = cancellation_token.clone();

        tokio::spawn(async move {
            tokio::select! {
                _ = cancellation_token_clone.cancelled() => {
                    info!("shutting down polling task gracefully");
                },
                _ = async {
                    loop {
                        let (experiments_result, groups_result) = join!(
                            Self::get_experiments_static(&superposition_options),
                            Self::get_experiment_groups_static(&superposition_options)
                        );
                        match (experiments_result, groups_result) {
                            (Ok(Some(experiments)), Ok(Some(experiment_groups))) => {
                                let mut cached = cached_experiments.write().await;
                                *cached = Some(experiments);
                                let mut cached_groups = cached_experiment_groups.write().await;
                                *cached_groups = Some(experiment_groups);
                                let mut updated = last_updated.write().await;
                                *updated = Some(chrono::Utc::now());
                                debug!("Experiments and Experiment Groups updated via polling");
                            }
                            (Ok(None), Ok(None)) => {
                                warn!(
                                    "No experiments or experiment groups returned from polling"
                                );
                            }
                            (Err(e), _) | (_, Err(e)) => {
                                error!("Polling error: {}", e);
                            }
                            _ => {}
                        }
                        sleep(Duration::from_secs(interval)).await;
                    }
                } => {}
            }
        });

        cancellation_token
    }

    pub async fn on_demand_config(
        &self,
        ttl: u64,
        use_stale: bool,
    ) -> Result<Experiments> {
        let now = chrono::Utc::now();
        let last_updated = self.last_updated.read().await;

        let should_refresh = match *last_updated {
            Some(last) => (now - last).num_seconds() > ttl as i64,
            None => true,
        };

        if should_refresh {
            debug!("TTL expired. Fetching experiments and experiment groups on-demand");
            let (experiments_result, groups_result) = join!(
                self.get_experiments(&self.superposition_options),
                self.get_experiment_groups(&self.superposition_options)
            );
            match (experiments_result, groups_result) {
                (Ok(Some(experiments)), Ok(Some(experiment_groups))) => {
                    let mut cached_experiments = self.cached_experiments.write().await;
                    *cached_experiments = Some(experiments.clone());
                    let mut cached_experiment_groups =
                        self.cached_experiment_groups.write().await;
                    *cached_experiment_groups = Some(experiment_groups);
                    let mut last_updated_mut = self.last_updated.write().await;
                    *last_updated_mut = Some(chrono::Utc::now());
                    info!("Experiments and Experiment Groups fetched successfully on-demand");
                    return Ok(experiments);
                }
                (Err(e), _) | (_, Err(e)) => {
                    warn!(
                        "On-demand experiments and experiment groups fetch failed: {}",
                        e
                    );
                    if !use_stale {
                        return Err(e);
                    }
                    info!("Using stale experiments and experiment groups due to error");
                }
                _ => {}
            }
        }

        // Return cached experiments
        let cached_experiments = self.cached_experiments.read().await;
        match cached_experiments.as_ref() {
            Some(experiments) => Ok(experiments.clone()),
            None => Ok(vec![]), // Return empty if no experiments cached
        }
    }

    async fn get_experiments(
        &self,
        options: &SuperpositionOptions,
    ) -> Result<Option<Experiments>> {
        Self::get_experiments_static(options).await
    }

    async fn get_experiment_groups(
        &self,
        options: &SuperpositionOptions,
    ) -> Result<Option<ExperimentGroups>> {
        Self::get_experiment_groups_static(options).await
    }

    async fn get_experiments_static(
        options: &SuperpositionOptions,
    ) -> Result<Option<Experiments>> {
        use superposition_sdk::{
            types::ExperimentStatusType, Client, Config as SdkConfig,
        };

        info!("Fetching experiments from Superposition service using SDK");

        // Create SDK config
        let sdk_config = SdkConfig::builder()
            .endpoint_url(&options.endpoint)
            .bearer_token(options.token.clone().into())
            .behavior_version_latest()
            .build();

        // Create Superposition client
        let client = Client::from_conf(sdk_config);

        let response = client
            .list_experiment()
            .workspace_id(&options.workspace_id)
            .org_id(&options.org_id)
            .all(true)
            .status(ExperimentStatusType::Created)
            .status(ExperimentStatusType::Inprogress)
            .send()
            .await
            .map_err(|e| {
                SuperpositionError::NetworkError(format!(
                    "Failed to list experiments: {}",
                    e
                ))
            })?;

        let experiments = ConversionUtils::convert_experiments_response(response.data)?;

        info!(
            "Successfully fetched and converted {} experiments",
            experiments.len()
        );
        Ok(Some(experiments))
    }

    async fn get_experiment_groups_static(
        options: &SuperpositionOptions,
    ) -> Result<Option<ExperimentGroups>> {
        use superposition_sdk::{Client, Config as SdkConfig};

        info!("Fetching experiment groups from Superposition service using SDK");

        // Create SDK config
        let sdk_config = SdkConfig::builder()
            .endpoint_url(&options.endpoint)
            .bearer_token(options.token.clone().into())
            .behavior_version_latest()
            .build();

        // Create Superposition client
        let client = Client::from_conf(sdk_config);

        let response = client
            .list_experiment_groups()
            .workspace_id(&options.workspace_id)
            .org_id(&options.org_id)
            .all(true)
            .send()
            .await
            .map_err(|e| {
                SuperpositionError::NetworkError(format!(
                    "Failed to list experiment groups: {}",
                    e
                ))
            })?;

        let experiment_groups =
            ConversionUtils::convert_experiment_groups_response(response.data)?;

        info!(
            "Successfully fetched and converted {} experiment groups",
            experiment_groups.len()
        );
        Ok(Some(experiment_groups))
    }

    pub async fn get_cached_experiments(&self) -> Option<Experiments> {
        let cached_experiments = self.cached_experiments.read().await;
        cached_experiments.clone()
    }

    pub async fn get_cached_experiment_groups(&self) -> Option<ExperimentGroups> {
        let cached_experiment_groups = self.cached_experiment_groups.read().await;
        cached_experiment_groups.clone()
    }

    pub async fn close(&self) -> Result<()> {
        // Stop polling task
        let mut polling_task_cancellation_token =
            self.polling_task_cancellation_token.write().await;
        if let Some(token) = polling_task_cancellation_token.take() {
            token.cancel();
        }

        // Clear caches
        let mut cached_experiments = self.cached_experiments.write().await;
        *cached_experiments = None;

        Ok(())
    }

    pub async fn get_applicable_variants(
        &self,
        dimensions_info: &HashMap<String, DimensionInfo>,
        contexts: &serde_json::Map<String, Value>,
        identifier: Option<String>,
    ) -> Result<Vec<String>> {
        let cached_experiments = self.cached_experiments.read().await;
        let cached_experiment_groups = self.cached_experiment_groups.read().await;

        match (
            cached_experiments.as_ref(),
            cached_experiment_groups.as_ref(),
        ) {
            (Some(experiments), Some(experiment_groups)) => {
                // Use get_applicable_variants from superposition_core
                Ok(get_applicable_variants(
                    dimensions_info,
                    experiments.clone(),
                    experiment_groups,
                    contexts,
                    &identifier.unwrap_or_default(),
                    None,
                ))
            }
            _ => Err(SuperpositionError::ConfigError(
                "No cached experiments or experiment groups available".into(),
            )),
        }
    }
}