sentry-options 1.2.0

Rust client for sentry-options config system
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
//! Options client for reading validated configuration values.

pub mod features;

pub use features::{FeatureChecker, FeatureContext, features};

use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};

pub use sentry_options_validation::PropagationCallback;
use sentry_options_validation::{
    SchemaRegistry, ValidationError, ValuesStore, resolve_options_dir,
};
use serde_json::Value;
use thiserror::Error;

pub mod testing;

static GLOBAL_OPTIONS: OnceLock<Options> = OnceLock::new();

#[derive(Debug, Error)]
pub enum OptionsError {
    #[error("Options not initialized - call init() first")]
    NotInitialized,

    #[error("Options already initialized")]
    AlreadyInitialized,

    #[error("Unknown namespace: {0}")]
    UnknownNamespace(String),

    #[error("Unknown option '{key}' in namespace '{namespace}'")]
    UnknownOption { namespace: String, key: String },

    #[error("Schema error: {0}")]
    Schema(#[from] ValidationError),
}

pub type Result<T> = std::result::Result<T, OptionsError>;

/// Options store for reading configuration values.
pub struct Options {
    store: ValuesStore,
}

impl Options {
    /// Load options using fallback chain: `SENTRY_OPTIONS_DIR` env var, then `/etc/sentry-options`
    /// if it exists, otherwise `sentry-options/`.
    /// Expects `{dir}/schemas/` and `{dir}/values/` subdirectories.
    pub fn new() -> Result<Self> {
        Self::from_directory(&resolve_options_dir())
    }

    /// Like [`new`], but with a propagation callback that fires `(namespace, delay_secs)`
    /// whenever values are refreshed with a new `generated_at` timestamp.
    pub fn new_with_propagation_callback(callback: PropagationCallback) -> Result<Self> {
        let dir = resolve_options_dir();
        let registry = SchemaRegistry::from_directory(&dir.join("schemas"))?;
        Self::with_registry_and_values(registry, &dir.join("values"), Some(callback))
    }

    /// Load options from a specific directory (useful for testing).
    /// Expects `{base_dir}/schemas/` and `{base_dir}/values/` subdirectories.
    pub fn from_directory(base_dir: &Path) -> Result<Self> {
        let registry = SchemaRegistry::from_directory(&base_dir.join("schemas"))?;
        Self::with_registry_and_values(registry, &base_dir.join("values"), None)
    }

    /// Load options with schemas provided as in-memory JSON strings.
    /// Values are loaded from disk using the standard fallback chain.
    pub fn from_schemas(schemas: &[(&str, &str)]) -> Result<Self> {
        let registry = SchemaRegistry::from_schemas(schemas)?;
        Self::with_registry_and_values(registry, &resolve_options_dir().join("values"), None)
    }

    fn with_registry_and_values(
        registry: SchemaRegistry,
        values_dir: &Path,
        callback: Option<PropagationCallback>,
    ) -> Result<Self> {
        let registry = Arc::new(registry);
        let store = match callback {
            Some(cb) => ValuesStore::with_propagation_callback(registry, values_dir, cb)?,
            None => ValuesStore::new(registry, values_dir)?,
        };
        Ok(Self { store })
    }

    /// Get an option value, returning the schema default if not set.
    pub fn get(&self, namespace: &str, key: &str) -> Result<Value> {
        self.get_inner(namespace, key, false)
    }

    /// Like [`get`](Self::get), but always refreshes. Refresh incurs a cost
    /// so this should only be used in testing.
    pub fn get_forced(&self, namespace: &str, key: &str) -> Result<Value> {
        self.get_inner(namespace, key, true)
    }

    fn get_inner(&self, namespace: &str, key: &str, force_reload: bool) -> Result<Value> {
        if let Some(value) = testing::get_override(namespace, key) {
            return Ok(value);
        }

        let schema = self
            .store
            .registry()
            .get(namespace)
            .ok_or_else(|| OptionsError::UnknownNamespace(namespace.to_string()))?;

        let values_guard = if force_reload {
            self.store.force_load()
        } else {
            self.store.load()
        };

        if let Some(ns_values) = values_guard.get(namespace)
            && let Some(value) = ns_values.get(key)
        {
            return Ok(value.clone());
        }

        let default = schema
            .get_default(key)
            .ok_or_else(|| OptionsError::UnknownOption {
                namespace: namespace.to_string(),
                key: key.to_string(),
            })?;

        Ok(default.clone())
    }

    /// Validate that a key exists in the schema and the value matches the expected type.
    pub fn validate_override(&self, namespace: &str, key: &str, value: &Value) -> Result<()> {
        let schema = self
            .store
            .registry()
            .get(namespace)
            .ok_or_else(|| OptionsError::UnknownNamespace(namespace.to_string()))?;

        schema.validate_option(key, value)?;

        Ok(())
    }

    /// Check if an option has a value.
    ///
    /// Returns true if the option is defined and has a value, will return
    /// false if the option is defined and does not have a value.
    ///
    /// If the namespace or option are not defined, an Err will be returned.
    pub fn isset(&self, namespace: &str, key: &str) -> Result<bool> {
        let schema = self
            .store
            .registry()
            .get(namespace)
            .ok_or_else(|| OptionsError::UnknownNamespace(namespace.to_string()))?;

        if !schema.is_known_key(key) {
            return Err(OptionsError::UnknownOption {
                namespace: namespace.into(),
                key: key.into(),
            });
        }

        let values_guard = self.store.load();
        if let Some(ns_values) = values_guard.get(namespace) {
            Ok(ns_values.contains_key(key))
        } else {
            Ok(false)
        }
    }
}

/// Builder for initializing the global options store.
/// Define optional parameters with `with_*` methods, then finalize with `init()`
///
/// All settings are optional and independent:
/// - `with_directory` overrides the base directory
/// - `with_schemas` supplies schemas in memory instead of reading `{dir}/schemas/`
/// - `with_callback` registers a callback that fires on every value refresh.
///
#[derive(Default)]
pub struct InitBuilder<'a> {
    directory: Option<PathBuf>,
    schemas: Option<&'a [(&'a str, &'a str)]>,
    callback: Option<PropagationCallback>,
}

impl<'a> InitBuilder<'a> {
    pub fn new() -> Self {
        InitBuilder::default()
    }

    /// Override the base directory. Expects `{directory}/schemas/` and `{directory}/values/` subdirectories.
    /// Otherwise, defaults to the fallback chain: `SENTRY_OPTIONS_DIR` env var, then `/etc/sentry-options`
    pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
        self.directory = Some(directory.into());
        self
    }

    /// Provide schemas as in-memory `(namespace, json)` pairs instead of reading
    /// them from `{dir}/schemas/`, intended to be used with `include_str!`
    pub fn with_schemas(mut self, schemas: &'a [(&'a str, &'a str)]) -> Self {
        self.schemas = Some(schemas);
        self
    }

    /// Register a callback that fires `(namespace, delay_secs)` whenever values
    /// are refreshed with a new `generated_at` timestamp.
    pub fn with_callback(mut self, callback: PropagationCallback) -> Self {
        self.callback = Some(callback);
        self
    }

    /// Initialize the global options store from the inputs.
    ///
    /// Returns [`OptionsError::AlreadyInitialized`] if the store is already
    /// initialized, leaving the existing configuration untouched. Callers that
    /// want a no-op in that case can ignore the error with `.ok()`.
    pub fn init(self) -> Result<()> {
        if GLOBAL_OPTIONS.get().is_some() {
            return Err(OptionsError::AlreadyInitialized);
        }
        GLOBAL_OPTIONS
            .set(self.build_options()?)
            .map_err(|_| OptionsError::AlreadyInitialized)
    }

    /// Helper to return an `Options` with the configured inputs.
    /// Does not touch the global `OnceLock`.
    fn build_options(self) -> Result<Options> {
        let dir = self.directory.unwrap_or_else(resolve_options_dir);

        let registry = match self.schemas {
            Some(s) => SchemaRegistry::from_schemas(s)?,
            None => SchemaRegistry::from_directory(&dir.join("schemas"))?,
        };

        Options::with_registry_and_values(registry, &dir.join("values"), self.callback)
    }
}

/// Initialize global options using the fallback chain: `SENTRY_OPTIONS_DIR` env
/// var, then `/etc/sentry-options` if it exists, otherwise `sentry-options/`.
///
/// Shorthand for `InitBuilder::new().init()`. Idempotent: if already
/// initialized, returns `Ok(())` without re-loading. For directory, schema, or
/// callback overrides, use [`InitBuilder`].
pub fn init() -> Result<()> {
    ignore_already_initialized(InitBuilder::new().init())
}

/// Like [`init`], but with a callback that fires whenever values are refreshed
/// from disk with a new `generated_at` timestamp. The callback receives
/// `(namespace, delay_secs)`.
#[deprecated(
    since = "1.3.0",
    note = "use `InitBuilder::new().with_callback(cb).init()`"
)]
pub fn init_with_propagation_callback(callback: PropagationCallback) -> Result<()> {
    ignore_already_initialized(InitBuilder::new().with_callback(callback).init())
}

/// Initialize global options with schemas provided as in-memory JSON strings.
/// Values are loaded from disk using the standard fallback chain.
///
/// Idempotent: if already initialized (by `init()` or a prior `init_with_schemas()`),
/// returns `Ok(())` without updating schemas.
///
/// Use this when schemas are embedded in the binary via `include_str!`:
/// ```rust,ignore
/// init_with_schemas(&[
///     ("snuba", include_str!("sentry-options/schemas/snuba/schema.json")),
/// ])?;
/// ```
#[deprecated(
    since = "1.3.0",
    note = "use `InitBuilder::new().with_schemas(s).init()`"
)]
pub fn init_with_schemas(schemas: &[(&str, &str)]) -> Result<()> {
    ignore_already_initialized(InitBuilder::new().with_schemas(schemas).init())
}

/// legacy, deprecated system was idempotent, this preserves the behaviour
fn ignore_already_initialized(result: Result<()>) -> Result<()> {
    match result {
        Err(OptionsError::AlreadyInitialized) => Ok(()),
        other => other,
    }
}

/// Get a namespace handle for accessing options.
///
/// Returns an error if `init()` has not been called.
pub fn options(namespace: &str) -> Result<NamespaceOptions> {
    let opts = GLOBAL_OPTIONS.get().ok_or(OptionsError::NotInitialized)?;
    Ok(NamespaceOptions {
        namespace: namespace.to_string(),
        options: opts,
    })
}

/// Handle for accessing options within a specific namespace.
pub struct NamespaceOptions {
    namespace: String,
    options: &'static Options,
}

impl NamespaceOptions {
    /// Get an option value, returning the schema default if not set.
    pub fn get(&self, key: &str) -> Result<Value> {
        self.options.get(&self.namespace, key)
    }

    /// Like [`get`](Self::get), but always refreshes. Refresh incurs a cost
    /// so this should only be used in testing.
    pub fn get_forced(&self, key: &str) -> Result<Value> {
        self.options.get_forced(&self.namespace, key)
    }

    /// Check if an option has a key defined, or if the default is being used.
    pub fn isset(&self, key: &str) -> Result<bool> {
        self.options.isset(&self.namespace, key)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::fs;
    use tempfile::TempDir;

    fn create_schema(dir: &Path, namespace: &str, schema: &str) {
        let schema_dir = dir.join(namespace);
        fs::create_dir_all(&schema_dir).unwrap();
        fs::write(schema_dir.join("schema.json"), schema).unwrap();
    }

    fn create_values(dir: &Path, namespace: &str, values: &str) {
        let ns_dir = dir.join(namespace);
        fs::create_dir_all(&ns_dir).unwrap();
        fs::write(ns_dir.join("values.json"), values).unwrap();
    }

    #[test]
    fn test_get_value() {
        let temp = TempDir::new().unwrap();
        let schemas = temp.path().join("schemas");
        let values = temp.path().join("values");
        fs::create_dir_all(&schemas).unwrap();

        create_schema(
            &schemas,
            "test",
            r#"{
                "version": "1.0",
                "type": "object",
                "properties": {
                    "enabled": {
                        "type": "boolean",
                        "default": false,
                        "description": "Enable feature"
                    }
                }
            }"#,
        );
        create_values(&values, "test", r#"{"options": {"enabled": true}}"#);

        let options = Options::from_directory(temp.path()).unwrap();
        assert_eq!(options.get("test", "enabled").unwrap(), json!(true));
    }

    #[test]
    fn test_get_default() {
        let temp = TempDir::new().unwrap();
        let schemas = temp.path().join("schemas");
        let values = temp.path().join("values");
        fs::create_dir_all(&schemas).unwrap();
        fs::create_dir_all(&values).unwrap();

        create_schema(
            &schemas,
            "test",
            r#"{
                "version": "1.0",
                "type": "object",
                "properties": {
                    "timeout": {
                        "type": "integer",
                        "default": 30,
                        "description": "Timeout"
                    }
                }
            }"#,
        );

        let options = Options::from_directory(temp.path()).unwrap();
        assert_eq!(options.get("test", "timeout").unwrap(), json!(30));
    }

    #[test]
    fn test_unknown_namespace() {
        let temp = TempDir::new().unwrap();
        let schemas = temp.path().join("schemas");
        let values = temp.path().join("values");
        fs::create_dir_all(&schemas).unwrap();
        fs::create_dir_all(&values).unwrap();

        create_schema(
            &schemas,
            "test",
            r#"{"version": "1.0", "type": "object", "properties": {}}"#,
        );

        let options = Options::from_directory(temp.path()).unwrap();
        assert!(matches!(
            options.get("unknown", "key"),
            Err(OptionsError::UnknownNamespace(_))
        ));
    }

    #[test]
    fn test_unknown_option() {
        let temp = TempDir::new().unwrap();
        let schemas = temp.path().join("schemas");
        let values = temp.path().join("values");
        fs::create_dir_all(&schemas).unwrap();
        fs::create_dir_all(&values).unwrap();

        create_schema(
            &schemas,
            "test",
            r#"{
                "version": "1.0",
                "type": "object",
                "properties": {
                    "known": {"type": "string", "default": "x", "description": "Known"}
                }
            }"#,
        );

        let options = Options::from_directory(temp.path()).unwrap();
        assert!(matches!(
            options.get("test", "unknown"),
            Err(OptionsError::UnknownOption { .. })
        ));
    }

    #[test]
    fn test_missing_values_dir() {
        let temp = TempDir::new().unwrap();
        let schemas = temp.path().join("schemas");
        fs::create_dir_all(&schemas).unwrap();

        create_schema(
            &schemas,
            "test",
            r#"{
                "version": "1.0",
                "type": "object",
                "properties": {
                    "opt": {"type": "string", "default": "default_val", "description": "Opt"}
                }
            }"#,
        );

        let options = Options::from_directory(temp.path()).unwrap();
        assert_eq!(options.get("test", "opt").unwrap(), json!("default_val"));
    }

    #[test]
    fn isset_with_defined_and_undefined_keys() {
        let temp = TempDir::new().unwrap();
        let schemas = temp.path().join("schemas");
        fs::create_dir_all(&schemas).unwrap();

        let values = temp.path().join("values");
        create_values(&values, "test", r#"{"options": {"has-value": "yes"}}"#);

        create_schema(
            &schemas,
            "test",
            r##"{
                "version": "1.0",
                "type": "object",
                "properties": {
                    "has-value": {"type": "string", "default": "", "description": ""},
                    "defined-with-default": {"type": "string", "default": "default_val", "description": "Opt"},
                    "feature.organizations:my-flag": {"$ref": "#/definitions/Feature"}
                }
            }"##,
        );

        let options = Options::from_directory(temp.path()).unwrap();
        assert!(options.isset("test", "not-defined").is_err());
        assert!(!options.isset("test", "defined-with-default").unwrap());
        assert!(options.isset("test", "has-value").unwrap());
        // Feature keys are known (no UnknownOption error) but unset -> false.
        assert!(
            !options
                .isset("test", "feature.organizations:my-flag")
                .unwrap()
        );
    }

    #[test]
    fn test_from_schemas_get_default() {
        let schema = r#"{
            "version": "1.0",
            "type": "object",
            "properties": {
                "enabled": {
                    "type": "boolean",
                    "default": false,
                    "description": "Enable feature"
                }
            }
        }"#;

        let registry = SchemaRegistry::from_schemas(&[("test", schema)]).unwrap();
        let default = registry
            .get("test")
            .unwrap()
            .get_default("enabled")
            .unwrap();
        assert_eq!(*default, json!(false));
    }

    #[test]
    fn test_from_schemas_with_values() {
        let temp = TempDir::new().unwrap();
        let values_dir = temp.path().join("values");
        create_values(&values_dir, "test", r#"{"options": {"enabled": true}}"#);

        let schema = r#"{
            "version": "1.0",
            "type": "object",
            "properties": {
                "enabled": {
                    "type": "boolean",
                    "default": false,
                    "description": "Enable feature"
                }
            }
        }"#;

        let registry = Arc::new(SchemaRegistry::from_schemas(&[("test", schema)]).unwrap());
        let (loaded_values, _) = registry.load_values_json(&values_dir).unwrap();
        assert_eq!(loaded_values["test"]["enabled"], json!(true));
    }

    #[test]
    fn test_from_schemas_invalid_json() {
        let result = SchemaRegistry::from_schemas(&[("test", "not valid json")]);
        assert!(result.is_err());
    }

    const BOOL_SCHEMA: &str = r#"{
        "version": "1.0",
        "type": "object",
        "properties": {
            "enabled": {"type": "boolean", "default": false, "description": "x"}
        }
    }"#;

    #[test]
    fn builder_with_directory() {
        let temp = TempDir::new().unwrap();
        let schemas = temp.path().join("schemas");
        let values = temp.path().join("values");
        fs::create_dir_all(&schemas).unwrap();
        create_schema(&schemas, "test", BOOL_SCHEMA);
        create_values(&values, "test", r#"{"options": {"enabled": true}}"#);

        let options = InitBuilder::new()
            // without this, schemas wouldn't be found and this test would fail
            .with_directory(temp.path())
            .build_options()
            .unwrap();
        assert_eq!(options.get("test", "enabled").unwrap(), json!(true));
    }

    #[test]
    fn builder_with_schemas() {
        let options = InitBuilder::new()
            // without this, init would fail as schemas are never saved on disk
            .with_schemas(&[("test", BOOL_SCHEMA)])
            .build_options()
            .unwrap();
        assert_eq!(options.get("test", "enabled").unwrap(), json!(false));
    }

    #[test]
    fn get_forced_sees_change() {
        let temp = TempDir::new().unwrap();
        let schemas = temp.path().join("schemas");
        let values = temp.path().join("values");
        fs::create_dir_all(&schemas).unwrap();
        create_schema(&schemas, "test", BOOL_SCHEMA);
        create_values(&values, "test", r#"{"options": {"enabled": true}}"#);

        let options = Options::from_directory(temp.path()).unwrap();
        assert_eq!(options.get("test", "enabled").unwrap(), json!(true));

        create_values(&values, "test", r#"{"options": {"enabled": false}}"#);

        // Cached read still returns the old value
        assert_eq!(options.get("test", "enabled").unwrap(), json!(true));
        // Forced read picks up the change
        assert_eq!(options.get_forced("test", "enabled").unwrap(), json!(false));
    }
}