sofie-flags 0.3.0

Feature flags: declared as constants, stored in the database, cached in process and evaluated per request.
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
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;

use sofie_core::{Error, Result, SqlValue, Uuid};
use sofie_db::{BoxFuture, Call, Db, Dialect, Driver, RowSink, Step, Wakeups};
use sofie_flags::{DeclaredSetting, Feature, Flags, Rule, SettingValue, Subject, Variants, gated};
use sofie_postgres::Postgres;
use sofie_testing::TestDatabase;

const SPLIT_PAYMENTS: Feature = Feature::new("order.split_payments");

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Layout {
    Classic,
    Compact,
}

impl sofie_core::Variants for Layout {
    const TYPE: &'static str = "Layout";
    const VARIANTS: &'static [(&'static str, Self)] =
        &[("CLASSIC", Self::Classic), ("COMPACT", Self::Compact)];
}

const LAYOUT: Variants<Layout> = Variants::new("order.checkout_layout");

async fn migrated(database: &TestDatabase) -> Db {
    let db = Db::new(Postgres::connect(database.url()).unwrap());
    db.schema().migrate(&[]).await.unwrap();
    db
}

fn member(principal: Uuid) -> Subject {
    Subject {
        area: Some("member"),
        principal: Some(principal),
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_flag_nobody_switched_is_off_and_a_stored_rule_is_read_back() {
    let database = TestDatabase::create().await;
    let db = migrated(&database).await;
    let flags = Flags::start(&db, "production").await.unwrap();
    let anyone = member(Uuid::from_u128(1));
    assert!(!flags.evaluate(anyone).enabled(SPLIT_PAYMENTS));

    flags
        .set("order.split_payments", Rule::everyone())
        .await
        .unwrap();

    let features = flags.evaluate(anyone);
    assert!(features.enabled(SPLIT_PAYMENTS));
    assert_eq!(features.evaluated(), "order.split_payments=on");
    let restarted = Flags::start(&db, "production").await.unwrap();
    assert_eq!(
        restarted.rules(),
        vec![("order.split_payments".to_owned(), Rule::everyone())]
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_malformed_stored_flag_is_left_out_and_the_others_still_load() {
    let database = TestDatabase::create().await;
    let db = migrated(&database).await;
    Flags::start(&db, "production")
        .await
        .unwrap()
        .set("order.split_payments", Rule::everyone())
        .await
        .unwrap();
    let raw = Postgres::connect(database.url()).unwrap();
    sofie_db::query_values(
        &raw,
        "INSERT INTO sofie.flags (id, version, name, rule, changed_at) \
         VALUES (gen_random_uuid(), 1, 'order.broken', '{\"on\": \"yes\"}', now())",
        &[],
    )
    .await
    .unwrap();

    let restarted = Flags::start(&db, "production").await.unwrap();

    assert_eq!(
        restarted.rules(),
        vec![("order.split_payments".to_owned(), Rule::everyone())]
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_change_made_right_after_another_process_started_reaches_it_without_waiting_for_expiry() {
    let database = TestDatabase::create().await;
    let db = migrated(&database).await;
    let here = Flags::start(&db, "production").await.unwrap();
    let elsewhere = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    here.set("order.split_payments", Rule::everyone())
        .await
        .unwrap();

    let anyone = member(Uuid::from_u128(1));
    for _ in 0..50 {
        if elsewhere.evaluate(anyone).enabled(SPLIT_PAYMENTS) {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    panic!("the change did not reach the other process within five seconds");
}

fn free_shipping() -> Vec<DeclaredSetting> {
    vec![DeclaredSetting {
        name: "order.free_shipping_above".to_owned(),
        default: SettingValue::Number(5000),
    }]
}

#[tokio::test(flavor = "multi_thread")]
async fn a_setting_changed_here_is_held_by_another_instance() {
    let database = TestDatabase::create().await;
    let here = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    let elsewhere = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    here.declare_settings(free_shipping()).unwrap();
    let anyone = Subject::default();
    let before = here.evaluate(anyone).version();
    assert_eq!(
        here.evaluate(anyone).settings()[0].value,
        SettingValue::Number(5000)
    );

    here.change_setting("order.free_shipping_above", " 7500")
        .await
        .unwrap();

    assert_ne!(here.evaluate(anyone).version(), before);
    let default = || SettingValue::Number(5000);
    for _ in 0..50 {
        let held = elsewhere
            .evaluate(anyone)
            .setting("order.free_shipping_above", default());
        if held == SettingValue::Number(7500) {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    panic!("the change did not reach the other instance within five seconds");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_setting_is_changed_only_when_declared_and_only_to_its_kind() {
    let database = TestDatabase::create().await;
    let flags = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    flags.declare_settings(free_shipping()).unwrap();
    for (name, value) in [
        ("order.free_shipping_above", "lots"),
        ("order.unknown", "1"),
    ] {
        assert!(matches!(
            flags.change_setting(name, value).await,
            Err(Error::Invalid(_))
        ));
    }
    let twice = [free_shipping(), free_shipping()].concat();
    assert!(flags.declare_settings(twice).is_err());
    assert_eq!(
        flags.evaluate(Subject::default()).setting(
            "order.free_shipping_above",
            SettingValue::Text(String::new())
        ),
        SettingValue::Text(String::new()),
        "nothing stored keeps the default"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn targeting_and_variants_follow_the_stored_rule() {
    let database = TestDatabase::create().await;
    let flags = Flags::start(&migrated(&database).await, "staging")
        .await
        .unwrap();
    let chosen = Uuid::from_u128(42);
    let rule = Rule {
        environments: vec!["staging".to_owned()],
        principals: vec![chosen],
        percentage: 0,
        variants: vec![("COMPACT".to_owned(), 1)],
        ..Rule::everyone()
    };
    flags.set("order.checkout_layout", rule).await.unwrap();

    assert_eq!(
        flags.evaluate(member(chosen)).variant(LAYOUT),
        Some(Layout::Compact)
    );
    assert_eq!(
        flags.evaluate(member(Uuid::from_u128(7))).variant(LAYOUT),
        None
    );
    let production = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    assert_eq!(production.evaluate(member(chosen)).variant(LAYOUT), None);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_variant_flag_nobody_switched_is_recorded_as_off() {
    let database = TestDatabase::create().await;
    let flags = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    let features = flags.evaluate(member(Uuid::from_u128(1)));

    assert_eq!(features.variant(LAYOUT), None);
    assert_eq!(features.evaluated(), "order.checkout_layout=off");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_malformed_name_or_percentage_is_refused() {
    let database = TestDatabase::create().await;
    let flags = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    assert!(flags.set("split_payments", Rule::everyone()).await.is_err());
    let too_many = Rule {
        percentage: 101,
        ..Rule::everyone()
    };
    assert!(flags.set("order.split_payments", too_many).await.is_err());
}

#[tokio::test(flavor = "multi_thread")]
async fn a_settled_flag_is_listed_with_the_time_it_settled() {
    let database = TestDatabase::create().await;
    let flags = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    flags
        .set("order.split_payments", Rule::everyone())
        .await
        .unwrap();
    let half = Rule {
        percentage: 50,
        ..Rule::everyone()
    };
    flags.set("order.checkout_layout", half).await.unwrap();

    let settled = flags.settled();
    assert_eq!(settled.len(), 1);
    assert_eq!(settled[0].name, "order.split_payments");
    assert!(settled[0].on);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_gated_job_runs_only_while_its_feature_is_on() {
    let database = TestDatabase::create().await;
    let flags = Flags::start(&migrated(&database).await, "production")
        .await
        .unwrap();
    let ran = Arc::new(AtomicBool::new(false));
    let job = {
        let ran = Arc::clone(&ran);
        move || {
            let ran = Arc::clone(&ran);
            async move {
                ran.store(true, Ordering::SeqCst);
                Result::Ok(())
            }
        }
    };
    let gated_job = gated(&flags, SPLIT_PAYMENTS, job);

    Call::<(), ()>::call(&gated_job, &mut ()).await.unwrap();
    assert!(!ran.load(Ordering::SeqCst));

    flags
        .set("order.split_payments", Rule::everyone())
        .await
        .unwrap();
    Call::<(), ()>::call(&gated_job, &mut ()).await.unwrap();
    assert!(ran.load(Ordering::SeqCst));
}

/// A change lands while the next listener subscribes, so no wake-up tells of it.
struct Interrupted {
    postgres: Postgres,
    elsewhere: Db,
    subscriptions: AtomicUsize,
}

struct Failing;

impl Wakeups for Failing {
    fn next(&mut self) -> BoxFuture<'_, Result<()>> {
        Box::pin(async { Err(Error::internal_message("the listening connection dropped")) })
    }
}

struct Silent;

impl Wakeups for Silent {
    fn next(&mut self) -> BoxFuture<'_, Result<()>> {
        Box::pin(std::future::pending())
    }
}

impl Driver for Interrupted {
    fn dialect(&self) -> &dyn Dialect {
        self.postgres.dialect()
    }

    fn query<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [SqlValue],
        rows: &'a mut dyn RowSink,
    ) -> BoxFuture<'a, Result<()>> {
        self.postgres.query(sql, params, rows)
    }

    fn transaction(&self, steps: Vec<Step>) -> BoxFuture<'_, Result<()>> {
        self.postgres.transaction(steps)
    }

    fn wakeups(&self) -> Option<BoxFuture<'_, Result<Box<dyn Wakeups>>>> {
        let subscription = self.subscriptions.fetch_add(1, Ordering::SeqCst);
        Some(Box::pin(async move {
            if subscription == 0 {
                return Ok(Box::new(Failing) as Box<dyn Wakeups>);
            }
            if subscription == 1 {
                let elsewhere = Flags::start(&self.elsewhere, "production").await?;
                elsewhere
                    .set("order.split_payments", Rule::everyone())
                    .await?;
            }
            Ok(Box::new(Silent) as Box<dyn Wakeups>)
        }))
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_change_made_while_listening_resumed_is_read_without_waiting_for_expiry() {
    let database = TestDatabase::create().await;
    let interrupted = Interrupted {
        postgres: Postgres::connect(database.url()).unwrap(),
        elsewhere: migrated(&database).await,
        subscriptions: AtomicUsize::new(0),
    };
    let flags = Flags::start(&Db::new(interrupted), "production")
        .await
        .unwrap();

    let anyone = member(Uuid::from_u128(1));
    for _ in 0..50 {
        if flags.evaluate(anyone).enabled(SPLIT_PAYMENTS) {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    panic!("the change did not reach the process within five seconds");
}

/// Every subscription drops at once, as behind a proxy that closes listening connections.
struct Dropping {
    postgres: Postgres,
    subscriptions: Arc<AtomicUsize>,
}

impl Driver for Dropping {
    fn dialect(&self) -> &dyn Dialect {
        self.postgres.dialect()
    }

    fn query<'a>(
        &'a self,
        sql: &'a str,
        params: &'a [SqlValue],
        rows: &'a mut dyn RowSink,
    ) -> BoxFuture<'a, Result<()>> {
        self.postgres.query(sql, params, rows)
    }

    fn transaction(&self, steps: Vec<Step>) -> BoxFuture<'_, Result<()>> {
        self.postgres.transaction(steps)
    }

    fn wakeups(&self) -> Option<BoxFuture<'_, Result<Box<dyn Wakeups>>>> {
        self.subscriptions.fetch_add(1, Ordering::SeqCst);
        Some(Box::pin(async {
            Ok(Box::new(Failing) as Box<dyn Wakeups>)
        }))
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_listener_that_keeps_dropping_is_not_resubscribed_in_a_tight_loop() {
    let database = TestDatabase::create().await;
    let subscriptions = Arc::new(AtomicUsize::new(0));
    let dropping = Dropping {
        postgres: Postgres::connect(database.url()).unwrap(),
        subscriptions: Arc::clone(&subscriptions),
    };
    migrated(&database).await;
    let _flags = Flags::start(&Db::new(dropping), "production")
        .await
        .unwrap();

    tokio::time::sleep(Duration::from_secs(1)).await;

    let subscribed = subscriptions.load(Ordering::SeqCst);
    assert!(
        subscribed <= 10,
        "subscribed {subscribed} times in a second"
    );
}