open-feature 0.3.0

The official OpenFeature Rust SDK.
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
use std::{collections::HashMap, ops::Deref, sync::Arc};

use crate::{
    provider::ProviderMetadata, ClientMetadata, EvaluationContext, EvaluationDetails,
    EvaluationError, Type, Value,
};

mod logging;
pub use logging::LoggingHook;

// ============================================================
//  Hook
// ============================================================

/// Hook allows application developers to add arbitrary behavior to the flag evaluation lifecycle.
/// They operate similarly to middleware in many web frameworks.
///
/// https://github.com/open-feature/spec/blob/main/specification/sections/04-hooks.md
#[cfg_attr(
    feature = "test-util",
    mockall::automock,
    allow(clippy::ref_option_ref)
)] // Specified lifetimes manually to make it work with mockall
#[async_trait::async_trait]
pub trait Hook: Send + Sync + 'static {
    /// This method is called before the flag evaluation.
    async fn before<'a>(
        &self,
        context: &HookContext<'a>,
        hints: Option<&'a HookHints>,
    ) -> Result<Option<EvaluationContext>, EvaluationError>;

    /// This method is called after the successful flag evaluation.
    async fn after<'a>(
        &self,
        context: &HookContext<'a>,
        details: &EvaluationDetails<Value>,
        hints: Option<&'a HookHints>,
    ) -> Result<(), EvaluationError>;

    /// This method is called on error during flag evaluation or error in before hook or after hook.
    async fn error<'a>(
        &self,
        context: &HookContext<'a>,
        error: &EvaluationError,
        hints: Option<&'a HookHints>,
    );

    /// This method is called after the flag evaluation, regardless of the result.
    async fn finally<'a>(
        &self,
        context: &HookContext<'a>,
        evaluation_details: &EvaluationDetails<Value>,
        hints: Option<&'a HookHints>,
    );
}

// ============================================================
//  HookWrapper
// ============================================================

#[allow(missing_docs)]
#[derive(Clone)]
pub struct HookWrapper(Arc<dyn Hook>);

impl HookWrapper {
    #[allow(missing_docs)]
    pub fn new(hook: impl Hook) -> Self {
        Self(Arc::new(hook))
    }
}

impl Deref for HookWrapper {
    type Target = dyn Hook;

    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

// ============================================================
//  HookHints
// ============================================================

#[allow(missing_docs)]
#[derive(Clone, Default, PartialEq, Debug)]
pub struct HookHints {
    hints: HashMap<String, Value>,
}

// ============================================================
//  HookContext
// ============================================================

/// Context for hooks.
#[allow(missing_docs)]
#[derive(Clone, PartialEq, Debug)]
pub struct HookContext<'a> {
    pub flag_key: &'a str,
    pub flag_type: Type,
    pub evaluation_context: &'a EvaluationContext,
    pub provider_metadata: ProviderMetadata,
    pub default_value: Option<Value>,
    pub client_metadata: ClientMetadata,
}

#[cfg(test)]
mod tests {

    use spec::spec;

    use crate::{
        provider::{MockFeatureProvider, ResolutionDetails},
        EvaluationErrorCode, EvaluationOptions, EvaluationReason, OpenFeature, StructValue,
    };

    use super::*;

    #[spec(
        number = "4.1.1",
        text = "Hook context MUST provide: the flag key, flag value type, evaluation context, and the default value."
    )]
    #[spec(
        number = "4.1.2",
        text = "The hook context SHOULD provide: access to the client metadata and the provider metadata fields."
    )]
    #[spec(
        number = "4.1.3",
        text = "The flag key, flag type, and default value properties MUST be immutable. If the language does not support immutability, the hook MUST NOT modify these properties."
    )]
    #[test]
    fn hook_context() {
        let context = HookContext {
            flag_key: "flag_key",
            flag_type: Type::Bool,
            evaluation_context: &EvaluationContext::default(),
            provider_metadata: ProviderMetadata::default(),
            default_value: Some(Value::Bool(true)),
            client_metadata: ClientMetadata::default(),
        };

        assert_eq!(context.flag_key, "flag_key");
        assert_eq!(context.flag_type, Type::Bool);
        assert_eq!(context.evaluation_context, &EvaluationContext::default());
        assert_eq!(context.provider_metadata, ProviderMetadata::default());
        assert_eq!(context.default_value, Some(Value::Bool(true)));
        assert_eq!(context.client_metadata, ClientMetadata::default());
    }

    #[spec(
        number = "4.2.1",
        text = "hook hints MUST be a structure supports definition of arbitrary properties, with keys of type string, and values of type boolean | string | number | datetime | structure."
    )]
    #[test]
    fn hook_hints() {
        let mut hints = HookHints::default();
        hints.hints.insert("key".to_string(), Value::Bool(true));
        hints
            .hints
            .insert("key2".to_string(), Value::String("value".to_string()));
        hints.hints.insert("key3".to_string(), Value::Int(42));
        hints.hints.insert("key4".to_string(), Value::Float(3.14));
        hints.hints.insert("key5".to_string(), Value::Array(vec![]));
        hints
            .hints
            .insert("key6".to_string(), Value::Struct(StructValue::default()));

        assert_eq!(hints.hints.len(), 6);
        assert_eq!(hints.hints.get("key"), Some(&Value::Bool(true)));
        assert_eq!(
            hints.hints.get("key2"),
            Some(&Value::String("value".to_string()))
        );
        assert_eq!(hints.hints.get("key3"), Some(&Value::Int(42)));
        assert_eq!(hints.hints.get("key4"), Some(&Value::Float(3.14)));
        assert_eq!(hints.hints.get("key5"), Some(&Value::Array(vec![])));
        assert_eq!(
            hints.hints.get("key6"),
            Some(&Value::Struct(StructValue::default()))
        );
    }

    #[spec(number = "4.2.2.1", text = "Hook hints MUST be immutable.")]
    #[test]
    fn hook_hints_mutability_checked_by_type_system() {}

    #[spec(
        number = "4.2.2.2",
        text = "The client metadata field in the hook context MUST be immutable."
    )]
    #[test]
    fn client_metadata_mutability_checked_by_type_system() {}

    #[spec(
        number = "4.2.2.3",
        text = "The provider metadata field in the hook context MUST be immutable."
    )]
    #[test]
    fn provider_metadata_mutability_checked_by_type_system() {}

    #[spec(number = "4.3.1", text = "Hooks MUST specify at least one stage.")]
    #[test]
    fn hook_interface_implementation_checked_by_type_system() {}

    #[spec(
        number = "4.3.2.1",
        text = "The before stage MUST run before flag resolution occurs. It accepts a hook context (required) and hook hints (optional) as parameters and returns either an evaluation context or nothing."
    )]
    #[test]
    fn hook_before_function_interface_implementation_checked_by_type_system() {}

    #[spec(
        number = "4.3.4",
        text = "Any evaluation context returned from a before hook MUST be passed to subsequent before hooks (via HookContext)."
    )]
    #[tokio::test]
    async fn before_hook_context_passing() {
        let mut mock_hook_1 = MockHook::new();
        let mut mock_hook_2 = MockHook::new();

        let mut api = OpenFeature::default();
        let mut client = api.create_named_client("test");
        let mut mock_provider = MockFeatureProvider::default();

        mock_provider.expect_hooks().return_const(vec![]);
        mock_provider.expect_initialize().return_const(());
        mock_provider
            .expect_metadata()
            .return_const(ProviderMetadata::default());
        mock_provider
            .expect_resolve_bool_value()
            .withf(|_, ctx| {
                assert_eq!(
                    ctx,
                    &EvaluationContext::default()
                        .with_targeting_key("mock_hook_1")
                        .with_custom_field("is", "a test")
                );
                true
            })
            .return_const(Ok(ResolutionDetails::new(true)));

        api.set_provider(mock_provider).await;
        drop(api);

        let flag_key = "flag";

        let eval_ctx = EvaluationContext::default().with_custom_field("is", "a test");

        let expected_eval_ctx = eval_ctx.clone();
        let client_metadata = client.metadata().clone();
        mock_hook_1
            .expect_before()
            .withf(move |ctx, _| {
                let hook_ctx_1 = HookContext {
                    flag_key,
                    flag_type: Type::Bool,
                    evaluation_context: &expected_eval_ctx,
                    default_value: Some(Value::Bool(false)),
                    provider_metadata: ProviderMetadata::default(),
                    client_metadata: client_metadata.clone(),
                };

                assert_eq!(ctx, &hook_ctx_1);
                true
            })
            .once()
            .returning(move |_, _| {
                Ok(Some(
                    EvaluationContext::default().with_targeting_key("mock_hook_1"),
                ))
            });

        let expected_eval_ctx_2 = EvaluationContext::default().with_targeting_key("mock_hook_1");
        let client_metadata = client.metadata().clone();
        mock_hook_2
            .expect_before()
            .withf(move |ctx, _| {
                let hook_ctx_1 = HookContext {
                    flag_key,
                    flag_type: Type::Bool,
                    evaluation_context: &expected_eval_ctx_2,
                    default_value: Some(Value::Bool(false)),
                    provider_metadata: ProviderMetadata::default(),
                    client_metadata: client_metadata.clone(),
                };

                assert_eq!(ctx, &hook_ctx_1);
                true
            })
            .once()
            .returning(move |_, _| Ok(None));

        mock_hook_1.expect_after().return_const(Ok(()));
        mock_hook_2.expect_after().return_const(Ok(()));
        mock_hook_1.expect_finally().return_const(());
        mock_hook_2.expect_finally().return_const(());

        // evaluation
        client = client.with_hook(mock_hook_1).with_hook(mock_hook_2);

        let result = client.get_bool_value(flag_key, Some(&eval_ctx), None).await;

        assert!(result.is_ok());
    }

    #[spec(
        number = "4.3.5",
        text = "When before hooks have finished executing, any resulting evaluation context MUST be merged with the existing evaluation context."
    )]
    #[tokio::test]
    async fn before_hook_context_merging() {
        let mut mock_hook = MockHook::new();

        let mut api = OpenFeature::default();
        api.set_evaluation_context(
            EvaluationContext::default()
                .with_custom_field("key", "api context")
                .with_custom_field("lowestPriority", true),
        )
        .await;

        let mut client = api.create_named_client("test");
        client.set_evaluation_context(
            EvaluationContext::default()
                .with_custom_field("key", "client context")
                .with_custom_field("lowestPriority", false)
                .with_custom_field("beatsClient", false),
        );

        mock_hook.expect_before().once().returning(move |_, _| {
            Ok(Some(
                EvaluationContext::default()
                    .with_custom_field("key", "hook value")
                    .with_custom_field("multiplier", 3),
            ))
        });

        mock_hook.expect_after().return_const(Ok(()));
        mock_hook.expect_finally().return_const(());

        let flag_key = "flag";
        let eval_ctx = EvaluationContext::default()
            .with_custom_field("key", "invocation context")
            .with_custom_field("on", true)
            .with_custom_field("beatsClient", true);

        let expected_ctx = EvaluationContext::default()
            .with_custom_field("key", "hook value")
            .with_custom_field("multiplier", 3)
            .with_custom_field("on", true)
            .with_custom_field("lowestPriority", false)
            .with_custom_field("beatsClient", true);

        let mut mock_provider = MockFeatureProvider::default();

        mock_provider.expect_hooks().return_const(vec![]);
        mock_provider.expect_initialize().return_const(());
        mock_provider
            .expect_metadata()
            .return_const(ProviderMetadata::default());
        mock_provider
            .expect_resolve_string_value()
            .withf(move |_, ctx| {
                assert_eq!(ctx, &expected_ctx);
                true
            })
            .return_const(Ok(ResolutionDetails::new("value")));

        api.set_provider(mock_provider).await;
        drop(api);

        client = client.with_hook(mock_hook);

        let result = client
            .get_string_value(flag_key, Some(&eval_ctx), None)
            .await;

        assert!(result.is_ok());
    }

    #[spec(
        number = "4.3.6",
        text = "The after stage MUST run after flag resolution occurs. It accepts a hook context (required), evaluation details (required) and hook hints (optional). It has no return value."
    )]
    #[tokio::test]
    async fn after_hook() {
        let mut mock_hook = MockHook::new();

        let mut api = OpenFeature::default();
        let mut client = api.create_client();
        let mut mock_provider = MockFeatureProvider::default();

        let mut seq = mockall::Sequence::new();

        mock_provider.expect_hooks().return_const(vec![]);
        mock_provider.expect_initialize().return_const(());
        mock_provider
            .expect_metadata()
            .return_const(ProviderMetadata::default());
        mock_provider
            .expect_resolve_bool_value()
            .once()
            .in_sequence(&mut seq)
            .return_const(Ok(ResolutionDetails::new(true)));

        api.set_provider(mock_provider).await;
        drop(api);

        mock_hook.expect_before().returning(|_, _| Ok(None));

        mock_hook
            .expect_after()
            .once()
            .in_sequence(&mut seq)
            .return_const(Ok(()));

        mock_hook.expect_finally().return_const(());

        // evaluation
        client = client.with_hook(mock_hook);

        let flag_key = "flag";
        let eval_ctx = EvaluationContext::default().with_custom_field("is", "a test");

        let result = client.get_bool_value(flag_key, Some(&eval_ctx), None).await;

        assert!(result.is_ok());
    }

    #[spec(
        number = "4.3.7",
        text = "The error hook MUST run when errors are encountered in the before stage, the after stage or during flag resolution. It accepts hook context (required), exception representing what went wrong (required), and hook hints (optional). It has no return value."
    )]
    #[tokio::test]
    async fn error_hook() {
        // error on `before` hook
        {
            let mut mock_hook = MockHook::new();

            let mut api = OpenFeature::default();
            let mut client = api.create_client();
            let mut mock_provider = MockFeatureProvider::default();

            let mut seq = mockall::Sequence::new();

            mock_provider.expect_hooks().return_const(vec![]);
            mock_provider.expect_initialize().return_const(());
            mock_provider.expect_resolve_bool_value().never();
            mock_provider
                .expect_metadata()
                .return_const(ProviderMetadata::default());

            api.set_provider(mock_provider).await;
            drop(api);

            mock_hook.expect_before().returning(|_, _| error());

            mock_hook
                .expect_error()
                .once()
                .in_sequence(&mut seq)
                .return_const(());

            mock_hook
                .expect_finally()
                .withf(|ctx, details, _| {
                    assert_eq!(ctx.flag_key, "flag");
                    assert_eq!(ctx.flag_type, Type::Bool);
                    assert_eq!(
                        ctx.evaluation_context,
                        &EvaluationContext::default().with_custom_field("is", "a test")
                    );
                    assert_eq!(ctx.default_value, Some(Value::Bool(false)));
                    assert_eq!(details.flag_key, "flag");
                    assert_eq!(details.value, Value::Bool(false));
                    assert_eq!(details.reason, Some(EvaluationReason::Error));
                    true
                })
                .return_const(());

            // evaluation
            client = client.with_hook(mock_hook);

            let flag_key = "flag";
            let eval_ctx = EvaluationContext::default().with_custom_field("is", "a test");

            let result = client.get_bool_value(flag_key, Some(&eval_ctx), None).await;

            assert!(result.is_err());
        }

        // error on evaluation
        {
            let mut mock_hook = MockHook::new();

            let mut api = OpenFeature::default();
            let mut client = api.create_client();
            let mut mock_provider = MockFeatureProvider::default();

            let mut seq = mockall::Sequence::new();

            mock_provider.expect_hooks().return_const(vec![]);
            mock_provider.expect_initialize().return_const(());
            mock_provider
                .expect_metadata()
                .return_const(ProviderMetadata::default());

            mock_hook.expect_before().returning(|_, _| Ok(None));

            mock_provider
                .expect_resolve_bool_value()
                .once()
                .in_sequence(&mut seq)
                .return_const(error());

            mock_hook
                .expect_error()
                .once()
                .in_sequence(&mut seq)
                .return_const(());

            mock_hook.expect_finally().return_const(());

            api.set_provider(mock_provider).await;
            drop(api);

            // evaluation
            client = client.with_hook(mock_hook);

            let flag_key = "flag";
            let eval_ctx = EvaluationContext::default().with_custom_field("is", "a test");

            let result = client.get_bool_value(flag_key, Some(&eval_ctx), None).await;

            assert!(result.is_err());
        }
    }

    #[spec(
        number = "4.3.8",
        text = "The finally hook MUST run after the before, after, and error stages. It accepts a hook context (required), evaluation details (required) and hook hints (optional). It has no return value."
    )]
    #[tokio::test]
    async fn finally_hook() {
        let mut mock_hook = MockHook::new();

        let mut api = OpenFeature::default();
        let mut client = api.create_client();
        let mut mock_provider = MockFeatureProvider::default();

        let mut seq = mockall::Sequence::new();

        mock_provider.expect_hooks().return_const(vec![]);
        mock_provider.expect_initialize().return_const(());
        mock_provider
            .expect_metadata()
            .return_const(ProviderMetadata::default());
        mock_provider
            .expect_resolve_bool_value()
            .return_const(Ok(ResolutionDetails::new(true)));

        api.set_provider(mock_provider).await;

        mock_hook
            .expect_before()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _| Ok(None));
        mock_hook
            .expect_after()
            .once()
            .in_sequence(&mut seq)
            .return_const(Ok(()));

        mock_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .withf(|ctx, details, _| {
                assert_eq!(ctx.flag_key, "flag");
                assert_eq!(ctx.flag_type, Type::Bool);
                assert_eq!(
                    ctx.evaluation_context,
                    &EvaluationContext::default().with_custom_field("is", "a test")
                );
                assert_eq!(ctx.default_value, Some(Value::Bool(false)));
                assert_eq!(details.flag_key, "flag");
                assert_eq!(details.value, Value::Bool(true));
                true
            })
            .return_const(());

        // evaluation
        client = client.with_hook(mock_hook);

        let flag_key = "flag";
        let eval_ctx = EvaluationContext::default().with_custom_field("is", "a test");

        let result = client.get_bool_value(flag_key, Some(&eval_ctx), None).await;

        assert!(result.is_ok());
    }

    #[spec(
        number = "4.4.1",
        text = "The API, Client, Provider, and invocation MUST have a method for registering hooks."
    )]
    #[spec(
        number = "4.4.2",
        text = "Hooks MUST be evaluated in the following order -> before: API, Client, Invocation, Provider. after: Provider, Invocation, Client, API. error(if applicable): Provider, Invocation, Client, API. finally: Provider, Invocation, Client, API."
    )]
    #[tokio::test]
    async fn hook_evaluation_order() {
        let mut mock_api_hook = MockHook::new();
        let mut mock_client_hook = MockHook::new();
        let mut mock_provider_hook = MockHook::new();
        let mut mock_invocation_hook = MockHook::new();

        let mut api = OpenFeature::default();
        let mut client = api.create_client();
        let mut provider = MockFeatureProvider::default();

        let mut seq = mockall::Sequence::new();

        // before: API, Client, Invocation, Provider
        mock_api_hook
            .expect_before()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _| Ok(None));
        mock_client_hook
            .expect_before()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _| Ok(None));
        mock_invocation_hook
            .expect_before()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _| Ok(None));
        mock_provider_hook
            .expect_before()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _| Ok(None));

        // evaluation
        provider
            .expect_resolve_bool_value()
            .once()
            .in_sequence(&mut seq)
            .return_const(Ok(ResolutionDetails::new(true)));

        // after: Provider, Invocation, Client, API
        mock_provider_hook
            .expect_after()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| Ok(()));
        mock_invocation_hook
            .expect_after()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| Ok(()));
        mock_client_hook
            .expect_after()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| Ok(()));
        mock_api_hook
            .expect_after()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| Ok(()));

        // finally: Provider, Invocation, Client, API
        mock_provider_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_invocation_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_client_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_api_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});

        provider
            .expect_hooks()
            .return_const(vec![HookWrapper::new(mock_provider_hook)]);
        provider.expect_initialize().return_const(());
        provider
            .expect_metadata()
            .return_const(ProviderMetadata::default());

        api.set_provider(provider).await;
        api.add_hook(mock_api_hook).await;
        client = client.with_hook(mock_client_hook);

        let eval = EvaluationOptions::default().with_hook(mock_invocation_hook);
        let _ = client.get_bool_value("flag", None, Some(&eval)).await;
    }

    #[spec(
        number = "4.4.3",
        text = "If a finally hook abnormally terminates, evaluation MUST proceed, including the execution of any remaining finally hooks."
    )]
    #[test]
    fn finally_hook_not_throw_checked_by_type_system() {}

    #[spec(
        number = "4.4.4",
        text = "If an error hook abnormally terminates, evaluation MUST proceed, including the execution of any remaining error hooks."
    )]
    #[test]
    fn error_hook_not_throw_checked_by_type_system() {}

    #[spec(
        number = "4.4.5",
        text = "If an error occurs in the before or after hooks, the error hooks MUST be invoked."
    )]
    #[tokio::test]
    async fn error_hook_invoked_on_error() {
        let mut mock_hook = MockHook::new();

        let mut api = OpenFeature::default();
        let mut client = api.create_client();
        let mut mock_provider = MockFeatureProvider::default();

        let mut seq = mockall::Sequence::new();

        mock_provider.expect_hooks().return_const(vec![]);
        mock_provider.expect_initialize().return_const(());
        mock_provider.expect_resolve_bool_value().never();
        mock_provider
            .expect_metadata()
            .return_const(ProviderMetadata::default());

        api.set_provider(mock_provider).await;

        mock_hook
            .expect_before()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _| error());

        mock_hook
            .expect_error()
            .once()
            .in_sequence(&mut seq)
            .return_const(());

        mock_hook.expect_finally().return_const(());

        // evaluation
        client = client.with_hook(mock_hook);

        let flag_key = "flag";
        let eval_ctx = EvaluationContext::default().with_custom_field("is", "a test");

        let result = client.get_bool_value(flag_key, Some(&eval_ctx), None).await;

        assert!(result.is_err());
    }

    #[spec(
        number = "4.4.6",
        text = "If an error occurs during the evaluation of before or after hooks, any remaining hooks in the before or after stages MUST NOT be invoked."
    )]
    #[tokio::test]
    async fn do_not_evaluate_remaining_hooks_on_error() {
        let mut mock_api_hook = MockHook::new();
        let mut mock_client_hook = MockHook::new();
        let mut mock_provider_hook = MockHook::new();
        let mut mock_invocation_hook = MockHook::new();

        let mut api = OpenFeature::default();
        let mut client = api.create_client();
        let mut provider = MockFeatureProvider::default();

        let mut seq = mockall::Sequence::new();

        // before: API, Client, Invocation, Provider
        mock_api_hook
            .expect_before()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _| Ok(None));
        mock_client_hook
            .expect_before()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _| error());

        // Remaining `before` and `after` hooks should not be called
        mock_invocation_hook.expect_before().never();
        mock_provider_hook.expect_before().never();

        // evaluation should not be called
        provider.expect_resolve_bool_value().never();

        // after: Provider, Invocation, Client, API
        mock_provider_hook.expect_after().never();
        mock_invocation_hook.expect_after().never();
        mock_client_hook.expect_after().never();
        mock_api_hook.expect_after().never();

        // error: Provider, Invocation, Client, API
        mock_provider_hook
            .expect_error()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_invocation_hook
            .expect_error()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_client_hook
            .expect_error()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_api_hook
            .expect_error()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});

        // finally: Provider, Invocation, Client, API
        mock_provider_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_invocation_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_client_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});
        mock_api_hook
            .expect_finally()
            .once()
            .in_sequence(&mut seq)
            .returning(|_, _, _| {});

        provider
            .expect_hooks()
            .return_const(vec![HookWrapper::new(mock_provider_hook)]);
        provider.expect_initialize().return_const(());
        provider
            .expect_metadata()
            .return_const(ProviderMetadata::default());

        api.set_provider(provider).await;
        api.add_hook(mock_api_hook).await;
        client = client.with_hook(mock_client_hook);

        let eval = EvaluationOptions::default().with_hook(mock_invocation_hook);
        let result = client.get_bool_value("flag", None, Some(&eval)).await;

        assert!(result.is_err());
    }

    #[spec(
        number = "4.4.7",
        text = "If an error occurs in the before hooks, the default value MUST be returned."
    )]
    #[test]
    fn default_value_covered_by_implementing_default_trait() {}

    fn error<T>() -> Result<T, EvaluationError> {
        Err(EvaluationError {
            code: EvaluationErrorCode::General("error".to_string()),
            message: None,
        })
    }
}