open-feature-flagd 0.2.1

The official flagd provider for OpenFeature.
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
//! [Generated by cargo-readme: `cargo readme --no-title --no-license > README.md`]::
//!  # flagd Provider for OpenFeature
//!
//! A Rust implementation of the OpenFeature provider for flagd, enabling dynamic
//! feature flag evaluation in your applications.
//!
//! This provider supports multiple evaluation modes, advanced targeting rules, caching strategies,
//! and connection management. It is designed to work seamlessly with the OpenFeature SDK and the flagd service.
//!
//! ## Core Features
//!
//! - **Multiple Evaluation Modes**
//!     - **RPC Resolver (Remote Evaluation):** Uses gRPC to perform flag evaluations remotely at a flagd instance. Supports bi-directional streaming, retry backoff, and custom name resolution (including Envoy support).
//!     - **REST Resolver:** Uses the OpenFeature Remote Evaluation Protocol (OFREP) over HTTP to evaluate flags.
//!     - **In-Process Resolver:** Performs evaluations locally using an embedded evaluation engine. Flag configurations can be retrieved via gRPC (sync mode).
//!     - **File Resolver:** Operates entirely from a flag definition file, updating on file changes in a best-effort manner.
//!
//! - **Advanced Targeting**
//!     - **Fractional Rollouts:** Uses consistent hashing (implemented via murmurhash3) to split traffic between flag variants in configurable proportions.
//!     - **Semantic Versioning:** Compare values using common operators such as '=', '!=', '<', '<=', '>', '>=', '^', and '~'.
//!     - **String Operations:** Custom operators for performing “starts_with” and “ends_with” comparisons.
//!     - **Complex Targeting Rules:** Leverages JSONLogic and custom operators to support nested conditions and dynamic evaluation.
//!
//! - **Caching Strategies**
//!     - Built-in support for LRU caching as well as an in-memory alternative. Flag evaluation results can be cached and later returned with a “CACHED” reason until the configuration updates.
//!
//! - **Connection Management**
//!     - Automatic connection establishment with configurable retries, timeout settings, and custom TLS or Unix-socket options.
//!     - Support for upstream name resolution including a custom resolver for Envoy proxy integration.
//!
//! ## Installation
//! Add the dependency in your `Cargo.toml`:
//! ```bash
//! cargo add open-feature-flagd
//! cargo add open-feature
//! ```
//!
//! ## Cargo Features
//!
//! This crate uses cargo features to allow clients to include only the evaluation modes they need,
//! keeping the dependency footprint minimal. By default, all features are enabled.
//!
//! | Feature | Description | Enabled by Default |
//! |---------|-------------|-------------------|
//! | `rpc` | gRPC-based remote evaluation via flagd service | ✅ |
//! | `rest` | HTTP/OFREP-based remote evaluation | ✅ |
//! | `in-process` | Local evaluation with embedded engine (includes File mode) | ✅ |
//!
//! ### Using Specific Features
//!
//! To include only specific evaluation modes:
//!
//! ```toml
//! # Only RPC evaluation
//! open-feature-flagd = { version = "0.0.8", default-features = false, features = ["rpc"] }
//!
//! # Only REST evaluation (lightweight, no gRPC dependencies)
//! open-feature-flagd = { version = "0.0.8", default-features = false, features = ["rest"] }
//!
//! # Only in-process/file evaluation
//! open-feature-flagd = { version = "0.0.8", default-features = false, features = ["in-process"] }
//!
//! # RPC and REST (no local evaluation engine)
//! open-feature-flagd = { version = "0.0.8", default-features = false, features = ["rpc", "rest"] }
//! ```
//!
//! Then integrate it into your application:
//!
//! ```rust,no_run
//! use open_feature_flagd::{FlagdOptions, FlagdProvider, ResolverType};
//! use open_feature::provider::FeatureProvider;
//! use open_feature::EvaluationContext;
//!
//! #[tokio::main]
//! async fn main() {
//!     // Example using the REST resolver mode.
//!     let provider = FlagdProvider::new(FlagdOptions {
//!         host: "localhost".to_string(),
//!         port: 8016,
//!         resolver_type: ResolverType::Rest,
//!         ..Default::default()
//!     }).await.unwrap();
//!
//!     let context = EvaluationContext::default().with_targeting_key("user-123");
//!     let result = provider.resolve_bool_value("bool-flag", &context).await.unwrap();
//!     println!("Flag value: {}", result.value);
//! }
//! ```
//!
//! ## Evaluation Modes
//! ### Remote Resolver (RPC)
//! In RPC mode, the provider communicates with flagd via gRPC. It supports features like streaming updates, retry mechanisms, and name resolution (including Envoy).
//!
//! ```rust,no_run
//! use open_feature_flagd::{FlagdOptions, FlagdProvider, ResolverType};
//! use open_feature::provider::FeatureProvider;
//! use open_feature::EvaluationContext;
//!
//! #[tokio::main]
//! async fn main() {
//!     let provider = FlagdProvider::new(FlagdOptions {
//!         host: "localhost".to_string(),
//!         port: 8013,
//!         resolver_type: ResolverType::Rpc,
//!         ..Default::default()
//!     }).await.unwrap();
//!
//!     let context = EvaluationContext::default().with_targeting_key("user-123");
//!     let bool_result = provider.resolve_bool_value("feature-enabled", &context).await.unwrap();
//!     println!("Feature enabled: {}", bool_result.value);
//! }
//! ```
//!
//! ### REST Resolver
//! In REST mode the provider uses the OpenFeature Remote Evaluation Protocol (OFREP) over HTTP.
//! It is useful when gRPC is not an option.
//! ```rust,no_run
//! use open_feature_flagd::{FlagdOptions, FlagdProvider, ResolverType};
//! use open_feature::provider::FeatureProvider;
//! use open_feature::EvaluationContext;
//!
//! #[tokio::main]
//! async fn main() {
//!     let provider = FlagdProvider::new(FlagdOptions {
//!         host: "localhost".to_string(),
//!         port: 8016,
//!         resolver_type: ResolverType::Rest,
//!         ..Default::default()
//!     }).await.unwrap();
//!
//!     let context = EvaluationContext::default().with_targeting_key("user-456");
//!     let result = provider.resolve_string_value("feature-variant", &context).await.unwrap();
//!     println!("Variant: {}", result.value);
//! }
//! ```
//!
//! ### In-Process Resolver
//! In-process evaluation is performed locally. Flag configurations are sourced via gRPC sync stream.
//! This mode supports advanced targeting operators (fractional, semver, string comparisons)
//! using the built-in evaluation engine.
//! ```rust,no_run
//! use open_feature_flagd::{CacheSettings, FlagdOptions, FlagdProvider, ResolverType};
//! use open_feature::provider::FeatureProvider;
//! use open_feature::EvaluationContext;
//!
//! #[tokio::main]
//! async fn main() {
//!     let provider = FlagdProvider::new(FlagdOptions {
//!         host: "localhost".to_string(),
//!         port: 8015,
//!         resolver_type: ResolverType::InProcess,
//!         selector: Some("my-service".to_string()),
//!         cache_settings: Some(CacheSettings::default()),
//!         ..Default::default()
//!     }).await.unwrap();
//!
//!     let context = EvaluationContext::default()
//!         .with_targeting_key("user-abc")
//!         .with_custom_field("environment", "production")
//!         .with_custom_field("semver", "2.1.0");
//!
//!     let dark_mode = provider.resolve_bool_value("dark-mode", &context).await.unwrap();
//!     println!("Dark mode enabled: {}", dark_mode.value);
//! }
//! ```
//!
//! ### File Mode
//! File mode is an in-process variant where flag configurations are read from a file.
//! This is useful for development or environments without network access.
//! ```rust,no_run
//! use open_feature_flagd::{FlagdOptions, FlagdProvider, ResolverType};
//! use open_feature::provider::FeatureProvider;
//! use open_feature::EvaluationContext;
//!
//! #[tokio::main]
//! async fn main() {
//!     let file_path = "./path/to/flagd-config.json".to_string();
//!     let provider = FlagdProvider::new(FlagdOptions {
//!         host: "localhost".to_string(),
//!         resolver_type: ResolverType::File,
//!         source_configuration: Some(file_path),
//!         ..Default::default()
//!     }).await.unwrap();
//!
//!     let context = EvaluationContext::default();
//!     let result = provider.resolve_int_value("rollout-percentage", &context).await.unwrap();
//!     println!("Rollout percentage: {}", result.value);
//! }
//! ```
//!
//! ## Configuration Options
//! Configurations can be provided as constructor options or via environment variables (with constructor options taking priority). The following options are supported:
//!
//! | Option                                  | Env Variable                            | Type / Supported Value            | Default                             | Compatible Resolver            |
//! |-----------------------------------------|-----------------------------------------|-----------------------------------|-------------------------------------|--------------------------------|
//! | Host                                    | FLAGD_HOST                              | string                            | "localhost"                         | RPC, REST, In-Process, File    |
//! | Port                                    | FLAGD_PORT                              | number                            | 8013 (RPC), 8016 (REST)             | RPC, REST, In-Process, File    |
//! | Target URI                              | FLAGD_TARGET_URI                        | string                            | ""                                  | RPC, In-Process                |
//! | TLS                                     | FLAGD_TLS                               | boolean                           | false                               | RPC, In-Process                |
//! | Socket Path                             | FLAGD_SOCKET_PATH                       | string                            | ""                                  | RPC                            |
//! | Certificate Path                        | FLAGD_SERVER_CERT_PATH                  | string                            | ""                                  | RPC, In-Process                |
//! | Cache Type (LRU / In-Memory / Disabled) | FLAGD_CACHE                             | string ("lru", "mem", "disabled") | In-Process: disabled, others: lru   | RPC, In-Process, File          |
//! | Cache TTL (Seconds)                     | FLAGD_CACHE_TTL                         | number                            | 60                                  | RPC, In-Process, File          |
//! | Max Cache Size                          | FLAGD_MAX_CACHE_SIZE                    | number                            | 1000                                | RPC, In-Process, File          |
//! | Offline File Path                       | FLAGD_OFFLINE_FLAG_SOURCE_PATH          | string                            | ""                                  | File                           |
//! | Retry Backoff (ms)                      | FLAGD_RETRY_BACKOFF_MS                  | number                            | 1000                                | RPC, In-Process                |
//! | Retry Backoff Maximum (ms)              | FLAGD_RETRY_BACKOFF_MAX_MS              | number                            | 120000                              | RPC, In-Process                |
//! | Retry Grace Period                      | FLAGD_RETRY_GRACE_PERIOD                | number                            | 5                                   | RPC, In-Process                |
//! | Event Stream Deadline (ms)              | FLAGD_STREAM_DEADLINE_MS                | number                            | 600000                              | RPC                            |
//! | Offline Poll Interval (ms)              | FLAGD_OFFLINE_POLL_MS                   | number                            | 5000                                | File                           |
//! | Source Selector                         | FLAGD_SOURCE_SELECTOR                   | string                            | ""                                  | In-Process                     |
//!
//! ## License
//! Apache 2.0 - See [LICENSE](./../../LICENSE) for more information.
//!

pub mod cache;
pub mod error;
pub mod resolver;

use crate::error::FlagdError;
#[cfg(feature = "in-process")]
use crate::resolver::in_process::resolver::{FileResolver, InProcessResolver};
use async_trait::async_trait;
#[cfg(feature = "rpc")]
use open_feature::EvaluationContextFieldValue;
use open_feature::provider::{FeatureProvider, ProviderMetadata, ResolutionDetails};
use open_feature::{EvaluationContext, EvaluationError, StructValue, Value};
#[cfg(feature = "rest")]
use resolver::rest::RestResolver;
use tracing::debug;
use tracing::instrument;

#[cfg(feature = "rpc")]
use std::collections::BTreeMap;
use std::sync::Arc;

pub use cache::{CacheService, CacheSettings, CacheType};
#[cfg(feature = "rpc")]
pub use resolver::rpc::RpcResolver;

// Include the generated protobuf code
#[cfg(any(feature = "rpc", feature = "in-process"))]
pub mod flagd {
    #[cfg(feature = "rpc")]
    pub mod evaluation {
        pub mod v1 {
            include!(concat!(env!("OUT_DIR"), "/flagd.evaluation.v1.rs"));
        }
    }
    #[cfg(feature = "in-process")]
    pub mod sync {
        pub mod v1 {
            include!(concat!(env!("OUT_DIR"), "/flagd.sync.v1.rs"));
        }
    }
}

/// Configuration options for the flagd provider
#[derive(Debug, Clone)]
pub struct FlagdOptions {
    /// Host address for the service
    pub host: String,
    /// Port number for the service
    pub port: u16,
    /// Target URI for custom name resolution (e.g. "envoy://service/flagd")
    pub target_uri: Option<String>,
    /// Type of resolver to use
    pub resolver_type: ResolverType,
    /// Whether to use TLS for connections (uses HTTPS/gRPCS)
    /// When enabled, connections will use TLS with system/webpki root certificates by default.
    /// For self-signed or custom CA certificates, also set `cert_path`.
    pub tls: bool,
    /// Path to a PEM-encoded CA certificate file for TLS connections.
    /// Use this to connect to flagd servers using self-signed or custom CA certificates.
    /// When provided, this certificate is used as the trusted CA instead of system roots.
    /// Can also be set via the `FLAGD_SERVER_CERT_PATH` environment variable.
    /// Example: "/path/to/ca-cert.pem"
    pub cert_path: Option<String>,
    /// Request timeout in milliseconds
    pub deadline_ms: u32,
    /// Cache configuration settings
    pub cache_settings: Option<CacheSettings>,
    /// Initial backoff duration in milliseconds for retry attempts (default: 1000ms)
    /// Not supported in OFREP (REST) evaluation
    pub retry_backoff_ms: u32,
    /// Maximum backoff duration in milliseconds for retry attempts, prevents exponential backoff from growing indefinitely (default: 120000ms)
    /// Not supported in OFREP (REST) evaluation
    pub retry_backoff_max_ms: u32,
    /// Maximum number of retry attempts before giving up (default: 5)
    /// Not supported in OFREP (REST) evaluation
    pub retry_grace_period: u32,
    /// Source selector for filtering flag configurations
    /// Used to scope flag sync requests in in-process evaluation
    pub selector: Option<String>,
    /// Unix domain socket path for connecting to flagd
    /// When provided, this takes precedence over host:port configuration
    /// Example: "/var/run/flagd.sock"
    /// Only works with GRPC resolver
    pub socket_path: Option<String>,
    /// Source configuration for file-based resolver
    pub source_configuration: Option<String>,
    /// The deadline in milliseconds for event streaming operations. Set to 0 to disable.
    /// Recommended to prevent infrastructure from killing idle connections.
    pub stream_deadline_ms: u32,
    /// HTTP/2 keepalive time in milliseconds. Sends pings to keep connections alive during
    /// idle periods, allowing RPCs to start quickly without delay. Set to 0 to disable.
    pub keep_alive_time_ms: u64,
    /// Offline polling interval in milliseconds
    pub offline_poll_interval_ms: Option<u32>,
    /// Provider ID for identifying this provider instance to flagd
    /// Used in in-process resolver for sync requests
    pub provider_id: Option<String>,
}
/// Type of resolver to use for flag evaluation
#[derive(Debug, Clone, PartialEq)]
pub enum ResolverType {
    /// Remote evaluation using gRPC connection to flagd service
    #[cfg(feature = "rpc")]
    Rpc,
    /// Remote evaluation using REST connection to flagd service
    #[cfg(feature = "rest")]
    Rest,
    /// Local evaluation with embedded flag engine using gRPC connection
    #[cfg(feature = "in-process")]
    InProcess,
    /// Local evaluation with no external dependencies
    #[cfg(feature = "in-process")]
    File,
}
impl Default for FlagdOptions {
    fn default() -> Self {
        let resolver_type = Self::default_resolver_type();

        let port = Self::default_port(&resolver_type);

        #[allow(unused_mut)]
        let mut options = Self {
            host: std::env::var("FLAGD_HOST").unwrap_or_else(|_| "localhost".to_string()),
            port: std::env::var("FLAGD_PORT")
                .ok()
                .and_then(|p| p.parse().ok())
                .unwrap_or(port),
            target_uri: std::env::var("FLAGD_TARGET_URI").ok(),
            resolver_type,
            tls: std::env::var("FLAGD_TLS")
                .map(|v| v.to_lowercase() == "true")
                .unwrap_or(false),
            cert_path: std::env::var("FLAGD_SERVER_CERT_PATH").ok(),
            deadline_ms: std::env::var("FLAGD_DEADLINE_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(500),
            retry_backoff_ms: std::env::var("FLAGD_RETRY_BACKOFF_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1000),
            retry_backoff_max_ms: std::env::var("FLAGD_RETRY_BACKOFF_MAX_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(120000),
            retry_grace_period: std::env::var("FLAGD_RETRY_GRACE_PERIOD")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(5),
            stream_deadline_ms: std::env::var("FLAGD_STREAM_DEADLINE_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(600000),
            keep_alive_time_ms: std::env::var("FLAGD_KEEP_ALIVE_TIME_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(0), // Disabled by default, per gherkin spec
            socket_path: std::env::var("FLAGD_SOCKET_PATH").ok(),
            selector: std::env::var("FLAGD_SOURCE_SELECTOR").ok(),
            cache_settings: Some(CacheSettings::default()),
            source_configuration: std::env::var("FLAGD_OFFLINE_FLAG_SOURCE_PATH").ok(),
            offline_poll_interval_ms: Some(
                std::env::var("FLAGD_OFFLINE_POLL_MS")
                    .ok()
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(5000),
            ),
            provider_id: std::env::var("FLAGD_PROVIDER_ID").ok(),
        };

        #[cfg(feature = "in-process")]
        {
            let resolver_env_set = std::env::var("FLAGD_RESOLVER").is_ok();
            if options.source_configuration.is_some() && !resolver_env_set {
                // Only override to File if FLAGD_RESOLVER wasn't explicitly set
                options.resolver_type = ResolverType::File;
            }
            // Disable caching for in-process/file modes per spec (caching is RPC-only)
            if matches!(
                options.resolver_type,
                ResolverType::InProcess | ResolverType::File
            ) {
                options.cache_settings = None;
            }
        }

        options
    }
}

impl FlagdOptions {
    fn default_resolver_type() -> ResolverType {
        if let Ok(r) = std::env::var("FLAGD_RESOLVER") {
            match r.to_uppercase().as_str() {
                #[cfg(feature = "rpc")]
                "RPC" => return ResolverType::Rpc,
                #[cfg(feature = "rest")]
                "REST" => return ResolverType::Rest,
                #[cfg(feature = "in-process")]
                "IN-PROCESS" | "INPROCESS" => return ResolverType::InProcess,
                #[cfg(feature = "in-process")]
                "FILE" | "OFFLINE" => return ResolverType::File,
                _ => {}
            }
        }
        // Return first available resolver type as default
        #[cfg(feature = "rpc")]
        return ResolverType::Rpc;
        #[cfg(all(feature = "rest", not(feature = "rpc")))]
        return ResolverType::Rest;
        #[cfg(all(feature = "in-process", not(feature = "rpc"), not(feature = "rest")))]
        return ResolverType::InProcess;
        #[cfg(not(any(feature = "rpc", feature = "rest", feature = "in-process")))]
        compile_error!("At least one resolver feature must be enabled: rpc, rest, or in-process");
    }

    fn default_port(resolver_type: &ResolverType) -> u16 {
        match resolver_type {
            #[cfg(feature = "rpc")]
            ResolverType::Rpc => 8013,
            #[cfg(feature = "in-process")]
            ResolverType::InProcess => 8015,
            #[cfg(feature = "rest")]
            ResolverType::Rest => 8016,
            #[allow(unreachable_patterns)]
            _ => 8013,
        }
    }
}

/// Main provider implementation for flagd
#[derive(Clone)]
pub struct FlagdProvider {
    /// The underlying feature flag resolver
    provider: Arc<dyn FeatureProvider + Send + Sync>,
    /// Optional caching layer
    cache: Option<Arc<CacheService<Value>>>,
}

impl FlagdProvider {
    #[instrument(skip(options))]
    pub async fn new(options: FlagdOptions) -> Result<Self, FlagdError> {
        debug!("Initializing FlagdProvider with options: {:?}", options);

        // Validate File resolver configuration
        #[cfg(feature = "in-process")]
        if options.resolver_type == ResolverType::File && options.source_configuration.is_none() {
            return Err(FlagdError::Config(
                "File resolver requires 'source_configuration' (FLAGD_OFFLINE_FLAG_SOURCE_PATH) to be set".to_string()
            ));
        }

        let provider: Arc<dyn FeatureProvider + Send + Sync> = match options.resolver_type {
            #[cfg(feature = "rpc")]
            ResolverType::Rpc => {
                debug!("Using RPC resolver");
                Arc::new(RpcResolver::new(&options).await?)
            }
            #[cfg(feature = "rest")]
            ResolverType::Rest => {
                debug!("Using REST resolver");
                Arc::new(RestResolver::new(&options).await?)
            }
            #[cfg(feature = "in-process")]
            ResolverType::InProcess => {
                debug!("Using in-process resolver");
                Arc::new(InProcessResolver::new(&options).await?)
            }
            #[cfg(feature = "in-process")]
            ResolverType::File => {
                debug!("Using file resolver");
                Arc::new(
                    FileResolver::new(
                        options
                            .source_configuration
                            .expect("source_configuration validated above"),
                        options.cache_settings.clone(),
                    )
                    .await?,
                )
            }
        };

        Ok(Self {
            provider,
            cache: options
                .cache_settings
                .map(|settings| Arc::new(CacheService::new(settings))),
        })
    }
}

impl std::fmt::Debug for FlagdProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FlagdProvider")
            .field("cache", &self.cache)
            .finish()
    }
}

#[cfg(feature = "rpc")]
pub(crate) fn convert_context(context: &EvaluationContext) -> Option<prost_types::Struct> {
    let mut fields = BTreeMap::new();

    if let Some(targeting_key) = &context.targeting_key {
        fields.insert(
            "targetingKey".to_string(),
            prost_types::Value {
                kind: Some(prost_types::value::Kind::StringValue(targeting_key.clone())),
            },
        );
    }

    for (key, value) in &context.custom_fields {
        let prost_value = match value {
            EvaluationContextFieldValue::String(s) => prost_types::Value {
                kind: Some(prost_types::value::Kind::StringValue(s.clone())),
            },
            EvaluationContextFieldValue::Bool(b) => prost_types::Value {
                kind: Some(prost_types::value::Kind::BoolValue(*b)),
            },
            EvaluationContextFieldValue::Int(i) => prost_types::Value {
                kind: Some(prost_types::value::Kind::NumberValue(*i as f64)),
            },
            EvaluationContextFieldValue::Float(f) => prost_types::Value {
                kind: Some(prost_types::value::Kind::NumberValue(*f)),
            },
            EvaluationContextFieldValue::DateTime(dt) => prost_types::Value {
                kind: Some(prost_types::value::Kind::StringValue(dt.to_string())),
            },
            EvaluationContextFieldValue::Struct(s) => prost_types::Value {
                kind: Some(prost_types::value::Kind::StringValue(format!("{:?}", s))),
            },
        };
        fields.insert(key.clone(), prost_value);
    }

    Some(prost_types::Struct { fields })
}

#[cfg(feature = "rpc")]
pub(crate) fn convert_proto_struct_to_struct_value(
    proto_struct: prost_types::Struct,
) -> StructValue {
    let fields = proto_struct
        .fields
        .into_iter()
        .map(|(key, value)| {
            (
                key,
                match value.kind.unwrap() {
                    prost_types::value::Kind::NullValue(_) => Value::String(String::new()),
                    prost_types::value::Kind::NumberValue(n) => Value::Float(n),
                    prost_types::value::Kind::StringValue(s) => Value::String(s),
                    prost_types::value::Kind::BoolValue(b) => Value::Bool(b),
                    prost_types::value::Kind::StructValue(s) => Value::String(format!("{:?}", s)),
                    prost_types::value::Kind::ListValue(l) => Value::String(format!("{:?}", l)),
                },
            )
        })
        .collect();

    StructValue { fields }
}

impl FlagdProvider {
    async fn get_cached_value<T>(
        &self,
        flag_key: &str,
        context: &EvaluationContext,
        value_converter: impl Fn(Value) -> Option<T>,
    ) -> Option<T> {
        if let Some(cache) = &self.cache
            && let Some(cached_value) = cache.get(flag_key, context).await
        {
            return value_converter(cached_value);
        }
        None
    }
}

#[async_trait]
impl FeatureProvider for FlagdProvider {
    fn metadata(&self) -> &ProviderMetadata {
        self.provider.metadata()
    }

    async fn resolve_bool_value(
        &self,
        flag_key: &str,
        context: &EvaluationContext,
    ) -> Result<ResolutionDetails<bool>, EvaluationError> {
        if let Some(value) = self
            .get_cached_value(flag_key, context, |v| match v {
                Value::Bool(b) => Some(b),
                _ => None,
            })
            .await
        {
            return Ok(ResolutionDetails::new(value));
        }

        let result = self.provider.resolve_bool_value(flag_key, context).await?;

        if let Some(cache) = &self.cache {
            cache
                .add(flag_key, context, Value::Bool(result.value))
                .await;
        }

        Ok(result)
    }

    async fn resolve_int_value(
        &self,
        flag_key: &str,
        context: &EvaluationContext,
    ) -> Result<ResolutionDetails<i64>, EvaluationError> {
        if let Some(value) = self
            .get_cached_value(flag_key, context, |v| match v {
                Value::Int(i) => Some(i),
                _ => None,
            })
            .await
        {
            return Ok(ResolutionDetails::new(value));
        }

        let result = self.provider.resolve_int_value(flag_key, context).await?;

        if let Some(cache) = &self.cache {
            cache.add(flag_key, context, Value::Int(result.value)).await;
        }

        Ok(result)
    }

    async fn resolve_float_value(
        &self,
        flag_key: &str,
        context: &EvaluationContext,
    ) -> Result<ResolutionDetails<f64>, EvaluationError> {
        if let Some(value) = self
            .get_cached_value(flag_key, context, |v| match v {
                Value::Float(f) => Some(f),
                _ => None,
            })
            .await
        {
            return Ok(ResolutionDetails::new(value));
        }

        let result = self.provider.resolve_float_value(flag_key, context).await?;

        if let Some(cache) = &self.cache {
            cache
                .add(flag_key, context, Value::Float(result.value))
                .await;
        }

        Ok(result)
    }

    async fn resolve_string_value(
        &self,
        flag_key: &str,
        context: &EvaluationContext,
    ) -> Result<ResolutionDetails<String>, EvaluationError> {
        if let Some(value) = self
            .get_cached_value(flag_key, context, |v| match v {
                Value::String(s) => Some(s),
                _ => None,
            })
            .await
        {
            return Ok(ResolutionDetails::new(value));
        }

        let result = self
            .provider
            .resolve_string_value(flag_key, context)
            .await?;

        if let Some(cache) = &self.cache {
            cache
                .add(flag_key, context, Value::String(result.value.clone()))
                .await;
        }

        Ok(result)
    }

    async fn resolve_struct_value(
        &self,
        flag_key: &str,
        context: &EvaluationContext,
    ) -> Result<ResolutionDetails<StructValue>, EvaluationError> {
        if let Some(value) = self
            .get_cached_value(flag_key, context, |v| match v {
                Value::Struct(s) => Some(s),
                _ => None,
            })
            .await
        {
            return Ok(ResolutionDetails::new(value));
        }

        let result = self
            .provider
            .resolve_struct_value(flag_key, context)
            .await?;

        if let Some(cache) = &self.cache {
            cache
                .add(flag_key, context, Value::Struct(result.value.clone()))
                .await;
        }

        Ok(result)
    }
}