superposition_provider 0.100.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
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
use open_feature::{provider::FeatureProvider, EvaluationContext, OpenFeature};
use serde_json::Value;
use superposition_provider::{
    ExperimentationOptions, OnDemandStrategy, RefreshStrategy, SuperpositionProvider,
    SuperpositionProviderOptions,
};
use superposition_sdk::{
    types::{ContextPut, DimensionType, Variant, WorkspaceStatus},
    Client, Config,
};

const WORKSPACE_ID: &str = "rustprovidertest";
const ENDPOINT: &str = "http://localhost:8080";
const TOKEN: &str = "12131";

/// Helper to create SDK client with bearer token auth
fn create_sdk_client() -> Client {
    use superposition_sdk::config::Token;

    let config = Config::builder()
        .endpoint_url(ENDPOINT)
        .bearer_token(Token::new(TOKEN, None))
        .behavior_version_latest()
        .build();

    Client::from_conf(config)
}

/// Setup functions - mirrors Kotlin/JS/Python implementations
async fn create_organisation(client: &Client) -> String {
    let output = client
        .create_organisation()
        .name("rusttestorg")
        .admin_email("admin@rusttestorg.com")
        .send()
        .await
        .expect("Failed to create organisation");

    println!(
        "Organisation created: {} with ID: {}",
        output.name, output.id
    );
    output.id
}

async fn create_workspace(client: &Client, org_id: &str, workspace_name: &str) {
    client
        .create_workspace()
        .org_id(org_id)
        .workspace_name(workspace_name)
        .workspace_admin_email("test@tests.com")
        .workspace_status(WorkspaceStatus::Enabled)
        .allow_experiment_self_approval(true)
        .auto_populate_control(false) // disable auto populate control for testing experiment
        .enable_context_validation(true)
        .enable_change_reason_validation(true)
        .send()
        .await
        .expect("Failed to create workspace");

    println!("Workspace created: {}", workspace_name);
}

async fn create_dimensions(client: &Client, org_id: &str, workspace_id: &str) {
    println!("Creating dimensions:");

    use aws_smithy_types::Document;

    // Dimension 1: name (string)
    client
        .create_dimension()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .dimension("name")
        .position(1)
        .schema("type", Document::from("string"))
        .description("customer name dimension")
        .change_reason("adding name dimension")
        .dimension_type(DimensionType::Regular)
        .send()
        .await
        .expect("Failed to create name dimension");
    println!("  - Created dimension: name");

    // Dimension 2: city (string)
    client
        .create_dimension()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .dimension("city")
        .position(2)
        .schema("type", Document::from("string"))
        .description("city dimension")
        .change_reason("adding city dimension")
        .dimension_type(DimensionType::Regular)
        .send()
        .await
        .expect("Failed to create city dimension");
    println!("  - Created dimension: city");

    // Dimension 3: customers (LOCAL_COHORT with platinum/gold/otherwise)
    // Build enum array
    let enum_array = Document::Array(vec![
        Document::from("platinum"),
        Document::from("gold"),
        Document::from("otherwise"),
    ]);

    // Build platinum definition
    let platinum_def = Document::Object(
        [(
            "in".to_string(),
            Document::Array(vec![
                Document::Object(
                    [("var".to_string(), Document::from("name"))]
                        .into_iter()
                        .collect(),
                ),
                Document::Array(vec![Document::from("Agush"), Document::from("Sauyav")]),
            ]),
        )]
        .into_iter()
        .collect(),
    );

    // Build gold definition
    let gold_def = Document::Object(
        [(
            "in".to_string(),
            Document::Array(vec![
                Document::Object(
                    [("var".to_string(), Document::from("name"))]
                        .into_iter()
                        .collect(),
                ),
                Document::Array(vec![Document::from("Angit"), Document::from("Bhrey")]),
            ]),
        )]
        .into_iter()
        .collect(),
    );

    // Build definitions object
    let definitions = Document::Object(
        [
            ("platinum".to_string(), platinum_def),
            ("gold".to_string(), gold_def),
        ]
        .into_iter()
        .collect(),
    );

    client
        .create_dimension()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .dimension("customers")
        .position(1)
        .schema("type", Document::from("string"))
        .schema("enum", enum_array)
        .schema("definitions", definitions)
        .description("customers dimension")
        .change_reason("adding customers dimension")
        .dimension_type(DimensionType::LocalCohort("name".to_string()))
        .send()
        .await
        .expect("Failed to create customers dimension");
    println!("  - Created dimension: customers");
}

async fn create_default_configs(client: &Client, org_id: &str, workspace_id: &str) {
    println!("Creating default configs:");

    use aws_smithy_types::Document;

    // Config 1: price (number, minimum 0)
    client
        .create_default_config()
        .key("price")
        .value(Document::from(10000))
        .schema("type", Document::from("number"))
        .schema("minimum", Document::from(0))
        .description("price as a positive number")
        .change_reason("adding price config")
        .workspace_id(workspace_id)
        .org_id(org_id)
        .send()
        .await
        .expect("Failed to create price config");
    println!("  - Created config: price");

    // Config 2: currency (enum: Rupee/Dollar/Euro)
    let currency_enum = Document::Array(vec![
        Document::from("Rupee"),
        Document::from("Dollar"),
        Document::from("Euro"),
    ]);

    client
        .create_default_config()
        .key("currency")
        .value(Document::from("Rupee"))
        .schema("type", Document::from("string"))
        .schema("enum", currency_enum)
        .description("currency as an enum")
        .change_reason("adding currency config")
        .workspace_id(workspace_id)
        .org_id(org_id)
        .send()
        .await
        .expect("Failed to create currency config");
    println!("  - Created config: currency");
}

async fn create_overrides(client: &Client, org_id: &str, workspace_id: &str) {
    println!("Creating overrides:");

    use aws_smithy_types::Document;

    // Override 1: Boston -> Dollar
    client
        .create_context()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .request(
            ContextPut::builder()
                .context("city", Document::from("Boston"))
                .r#override("currency", Document::from("Dollar"))
                .description("Bostonian")
                .change_reason("testing")
                .build()
                .expect("Failed to create ContextPut"),
        )
        .send()
        .await
        .expect("Failed to create Boston override");
    println!("  - Created override: Boston -> Dollar");

    // Override 2: Berlin -> Euro
    client
        .create_context()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .request(
            ContextPut::builder()
                .context("city", Document::from("Berlin"))
                .r#override("currency", Document::from("Euro"))
                .description("Berlin")
                .change_reason("testing")
                .build()
                .expect("Failed to create ContextPut"),
        )
        .send()
        .await
        .expect("Failed to create Berlin override");
    println!("  - Created override: Berlin -> Euro");

    // Override 3: platinum -> price 5000
    client
        .create_context()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .request(
            ContextPut::builder()
                .context("customers", Document::from("platinum"))
                .r#override("price", Document::from(5000))
                .description("platinum customer")
                .change_reason("testing")
                .build()
                .expect("Failed to create ContextPut"),
        )
        .send()
        .await
        .expect("Failed to create platinum override");
    println!("  - Created override: platinum -> price 5000");

    // Override 4: gold -> price 8000
    client
        .create_context()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .request(
            ContextPut::builder()
                .context("customers", Document::from("gold"))
                .r#override("price", Document::from(8000))
                .description("gold customers")
                .change_reason("testing")
                .build()
                .expect("Failed to create ContextPut"),
        )
        .send()
        .await
        .expect("Failed to create gold override");
    println!("  - Created override: gold -> price 8000");

    // Override 5: karbik (otherwise) -> price 1
    client
        .create_context()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .request(
            ContextPut::builder()
                .context("name", Document::from("karbik"))
                .r#override("price", Document::from(1))
                .description("edge case customer karbik")
                .change_reason("testing")
                .build()
                .expect("Failed to create ContextPut"),
        )
        .send()
        .await
        .expect("Failed to create karbik override");
    println!("  - Created override: karbik -> price 1");
}

async fn create_experiments(client: &Client, org_id: &str, workspace_id: &str) {
    println!("Creating experiment:");

    use aws_smithy_types::Document;

    let response = client
        .create_experiment()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .name("Kolkata Pricing Experiment")
        .context("city", Document::from("Kolkata"))
        .variants(
            Variant::builder()
                .id("control".to_string())
                .variant_type(superposition_sdk::types::VariantType::Control)
                .overrides("price", Document::from(8000)) // # Note: Using a different price to distinguish from default
                .build()
                .expect("Failed to build control variant"),
        )
        .variants(
            Variant::builder()
                .id("Experimental".to_string())
                .variant_type(superposition_sdk::types::VariantType::Experimental)
                .overrides("price", Document::from(7000))
                .build()
                .expect("Failed to build Experimental variant"),
        )
        .description("A test experiment")
        .change_reason("adding test experiment")
        .send()
        .await
        .expect("Failed to create experiment");

    println!("  - Created experiment: Kolkata Pricing Experiment");

    client
        .ramp_experiment()
        .workspace_id(workspace_id)
        .org_id(org_id)
        .id(response.id)
        .traffic_percentage(50)
        .change_reason("ramping up experiment")
        .send()
        .await
        .expect("Failed to ramp experiment");
}

async fn setup_with_sdk(org_id: &str, workspace_id: &str) {
    println!("\n=== Setting up test environment ===\n");

    let client = create_sdk_client();

    create_workspace(&client, org_id, workspace_id).await;
    create_dimensions(&client, org_id, workspace_id).await;
    create_default_configs(&client, org_id, workspace_id).await;
    create_overrides(&client, org_id, workspace_id).await;
    create_experiments(&client, org_id, workspace_id).await;

    println!("\n=== Setup complete ===\n");
}

async fn run_provider_tests(org_id: &str, workspace_id: &str) {
    println!("\n=== Starting OpenFeature provider tests ===\n");

    // Create provider with on-demand refresh strategy
    let provider_options = SuperpositionProviderOptions {
        endpoint: ENDPOINT.to_string(),
        token: TOKEN.to_string(),
        org_id: org_id.to_string(),
        workspace_id: workspace_id.to_string(),
        refresh_strategy: RefreshStrategy::OnDemand(OnDemandStrategy::default()),
        evaluation_cache: None,
        fallback_config: None,
        experimentation_options: Some(ExperimentationOptions {
            refresh_strategy: RefreshStrategy::OnDemand(OnDemandStrategy::default()),
            evaluation_cache: None,
            default_toss: None,
        }),
    };

    let provider = SuperpositionProvider::new(provider_options);
    // Test 0: Verify provider clone works (sanity check)
    println!("Test 0: Verify provider clone works (sanity check)");
    {
        let mut provider_clone = provider.clone();
        provider_clone
            .initialize(&EvaluationContext::default())
            .await;
        let ctx = EvaluationContext::default().with_custom_field("name", "karbik");
        let all_fields = provider_clone.resolve_full_config(&ctx).await.unwrap();

        assert_eq!(
            all_fields.get("price").unwrap(),
            &Value::from(1),
            "Price should be 1 for karbik"
        );
        assert_eq!(
            all_fields.get("currency").unwrap(),
            &Value::from("Rupee"),
            "Currency should be default Rupee"
        );
        println!("  ✓ Test passed\n");
    }

    // Set provider as the global provider
    let mut api = OpenFeature::singleton_mut().await;
    api.set_provider(provider).await;

    let client = api.create_client();

    // Test 1: Default values (no context)
    println!("Test 1: Default values (no context)");
    {
        let ctx = EvaluationContext::default();
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();

        assert_eq!(price, 10000.0, "Default price should be 10000");
        assert_eq!(currency, "Rupee", "Default currency should be Rupee");
        println!("  ✓ Test passed\n");
    }

    // Test 2: Platinum customer - Agush, no city
    println!("Test 2: Platinum customer - Agush (no city)");
    {
        let ctx = EvaluationContext::default().with_custom_field("name", "Agush");
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();

        assert_eq!(price, 5000.0, "Price should be 5000 for platinum customer");
        assert_eq!(currency, "Rupee", "Currency should be default Rupee");
        println!("  ✓ Test passed\n");
    }

    // Test 3: Platinum customer - Sauyav, with city Boston
    println!("Test 3: Platinum customer - Sauyav with city Boston");
    {
        let ctx = EvaluationContext::default()
            .with_custom_field("name", "Sauyav")
            .with_custom_field("city", "Boston");
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();

        assert_eq!(price, 5000.0, "Price should be 5000");
        assert_eq!(currency, "Dollar", "Currency should be Dollar");
        println!("  ✓ Test passed\n");
    }

    // Test 4: Regular customer - John (no city)
    println!("Test 4: Regular customer - John (no city)");
    {
        let ctx = EvaluationContext::default().with_custom_field("name", "John");
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();

        assert_eq!(price, 10000.0, "Price should be default 10000");
        assert_eq!(currency, "Rupee", "Currency should be default Rupee");
        println!("  ✓ Test passed\n");
    }

    // Test 5: Platinum customer - Sauyav with city Berlin
    println!("Test 5: Platinum customer - Sauyav with city Berlin");
    {
        let ctx = EvaluationContext::default()
            .with_custom_field("name", "Sauyav")
            .with_custom_field("city", "Berlin");
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();

        assert_eq!(price, 5000.0, "Price should be 5000");
        assert_eq!(currency, "Euro", "Currency should be Euro in Berlin");
        println!("  ✓ Test passed\n");
    }

    // Test 6: Regular customer - John with city Boston
    println!("Test 6: Regular customer - John with city Boston");
    {
        let ctx = EvaluationContext::default()
            .with_custom_field("name", "John")
            .with_custom_field("city", "Boston");
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();

        assert_eq!(price, 10000.0, "Price should be default 10000");
        assert_eq!(currency, "Dollar", "Currency should be Dollar in Boston");
        println!("  ✓ Test passed\n");
    }

    // Test 7: Edge case customer - karbik (specific override)
    println!("Test 7: Edge case customer - karbik (specific override)");
    {
        let ctx = EvaluationContext::default().with_custom_field("name", "karbik");
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();

        assert_eq!(price, 1.0, "Price should be 1 for karbik");
        assert_eq!(currency, "Rupee", "Currency should be default Rupee");
        println!("  ✓ Test passed\n");
    }

    // Test 8: Edge case customer - karbik with city Boston
    println!("Test 8: Edge case customer - karbik with city Boston");
    {
        let ctx = EvaluationContext::default()
            .with_custom_field("name", "karbik")
            .with_custom_field("city", "Boston");
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();

        assert_eq!(price, 1.0, "Price should be 1 for karbik");
        assert_eq!(currency, "Dollar", "Currency should be Dollar in Boston");
        println!("  ✓ Test passed\n");
    }

    // Test 9: Experiment case - Kolkata pricing
    println!("Test 9: Experiment case: Kolkata pricing");
    {
        let ctx = EvaluationContext::default()
            .with_custom_field("city", "Kolkata")
            .with_targeting_key("test");
        let price = client
            .get_float_value("price", Some(&ctx), None)
            .await
            .unwrap();
        let currency = client
            .get_string_value("currency", Some(&ctx), None)
            .await
            .unwrap();
        println!("  Retrieved price: {}, currency: {}", price, currency);

        assert!(
            price == 8000.0 || price == 7000.0,
            "Price should be either 8000 (control) or 7000 (experiment) "
        );
        assert_eq!(currency, "Rupee", "Currency should be default Rupee");
        println!("  ✓ Experiment test passed ");
    }

    println!("\n=== All tests passed! ===\n");
}

#[tokio::test]
#[ignore]
async fn test_rust_provider_integration() {
    // Create organisation
    let client = create_sdk_client();
    let org_id = create_organisation(&client).await;

    // Setup test environment using SDK
    setup_with_sdk(&org_id, WORKSPACE_ID).await;

    // Run provider tests
    run_provider_tests(&org_id, WORKSPACE_ID).await;
}