newton-regorus 0.2.0

A fast, lightweight Rego (OPA policy language) interpreter with Newton extensions
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#![allow(
    clippy::panic,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::shadow_unrelated,
    clippy::assertions_on_result_states
)] // registry tests unwrap/panic to assert outcomes

use super::super::registry::*;
use crate::{schema::Schema, *};
use serde_json::json;

type String = Rc<str>;
type SchemaRegistryError = RegistryError;

#[test]
fn test_schema_registry_new() {
    let registry = SchemaRegistry::new("test");
    assert!(registry.is_empty());
    assert_eq!(registry.len(), 0);
}

#[test]
fn test_schema_registry_register_success() {
    let registry = SchemaRegistry::new("test");
    let schema = create_test_schema();

    let result = registry.register("test_schema", schema.clone());
    assert!(result.is_ok());
    assert_eq!(registry.len(), 1);
    assert!(registry.contains("test_schema"));
}

#[test]
fn test_schema_registry_register_duplicate() {
    let registry = SchemaRegistry::new("test");
    let schema = create_test_schema();

    // Register first time - should succeed
    let result1 = registry.register("test_schema", schema.clone());
    assert!(result1.is_ok());

    // Register again with same name - should fail
    let result2 = registry.register("test_schema", schema);
    assert!(result2.is_err());

    if let Err(SchemaRegistryError::AlreadyExists { name, .. }) = result2 {
        assert_eq!(name, "test_schema".into());
    } else {
        panic!("Expected AlreadyExists error");
    }
}

#[test]
fn test_schema_registry_get() {
    let registry = SchemaRegistry::new("test");
    let schema = create_test_schema();

    // Get non-existent schema
    assert!(registry.get("non_existent").is_none());

    // Register and get existing schema
    registry.register("test_schema", schema.clone()).unwrap();
    let retrieved = registry.get("test_schema");
    assert!(retrieved.is_some());

    // Verify it's the same schema (Rc comparison)
    let retrieved_schema = retrieved.unwrap();
    assert!(Rc::ptr_eq(&schema, &retrieved_schema));
}

#[test]
fn test_schema_registry_remove() {
    let registry = SchemaRegistry::new("test");
    let schema = create_test_schema();

    // Remove non-existent schema
    assert!(registry.remove("non_existent").is_none());

    // Register, then remove
    registry.register("test_schema", schema.clone()).unwrap();
    assert_eq!(registry.len(), 1);

    let removed = registry.remove("test_schema");
    assert!(removed.is_some());
    assert_eq!(registry.len(), 0);
    assert!(!registry.contains("test_schema"));

    // Verify it's the same schema
    let removed_schema = removed.unwrap();
    assert!(Rc::ptr_eq(&schema, &removed_schema));
}

#[test]
fn test_schema_registry_list_names() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");

    // Empty registry
    assert!(registry.list_names().is_empty());

    // Add multiple schemas
    let schema1 = create_test_schema();
    let schema2 = create_test_schema();

    registry.register("schema_a", schema1).unwrap();
    registry.register("schema_b", schema2).unwrap();

    let names = registry.list_names();
    assert_eq!(names.len(), 2);
    assert!(names.contains(&"schema_a".into()));
    assert!(names.contains(&"schema_b".into()));
}

#[test]
fn test_schema_registry_clear() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    // Add some schemas
    registry.register("schema1", schema.clone()).unwrap();
    registry.register("schema2", schema).unwrap();
    assert_eq!(registry.len(), 2);

    // Clear all
    registry.clear();
    assert!(registry.is_empty());
    assert_eq!(registry.len(), 0);
    assert!(registry.list_names().is_empty());
}

#[test]
fn test_error_display() {
    let error = SchemaRegistryError::AlreadyExists {
        name: "test_schema".into(),
        registry: "test".into(),
    };
    let error_message = format!("{error}");
    assert_eq!(
        error_message,
        "test registration failed: An item with the name 'test_schema' is already registered."
    );

    let invalid_error = SchemaRegistryError::InvalidName {
        name: " ".into(),
        registry: "test".into(),
    };
    let invalid_error_message = format!("{invalid_error}");
    assert_eq!(
        invalid_error_message,
        "test registration failed: The name ' ' is invalid (empty or whitespace-only names are not allowed)."
    );
}

#[test]
#[cfg(feature = "std")]
fn test_concurrent_access() {
    use std::{sync::Barrier, thread};

    // Create a fresh registry for this test to avoid interference
    let test_registry = Rc::new(SchemaRegistry::new("TestSchemaRegistry"));

    let barrier = Rc::new(Barrier::new(4));
    let mut handles = vec![];

    // Spawn multiple threads trying to register schemas
    for i in 0..4 {
        let barrier = Rc::clone(&barrier);
        let registry = Rc::clone(&test_registry);
        let handle = thread::spawn(move || {
            let schema = create_test_schema();
            barrier.wait();

            // Each thread tries to register a schema with unique name
            let name = format!("schema_{i}");
            registry.register(name, schema)
        });
        handles.push(handle);
    }

    // Wait for all threads to complete
    let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

    // All registrations should succeed
    for result in results {
        assert!(result.is_ok());
    }

    // Should have exactly 4 schemas registered
    assert_eq!(test_registry.len(), 4);
}

#[test]
#[cfg(feature = "std")]
fn test_concurrent_duplicate_registration() {
    use std::{sync::Barrier, thread};

    // Create a fresh registry for this test to avoid interference
    let test_registry = Rc::new(SchemaRegistry::new("TestSchemaRegistry"));

    let barrier = Rc::new(Barrier::new(3));
    let mut handles = vec![];

    // Spawn multiple threads trying to register the same schema name
    for _ in 0..3 {
        let barrier = Rc::clone(&barrier);
        let registry = Rc::clone(&test_registry);
        let handle = thread::spawn(move || {
            let schema = create_test_schema();
            barrier.wait();

            // All threads try to register with the same name
            registry.register("duplicate_name", schema)
        });
        handles.push(handle);
    }

    // Wait for all threads to complete
    let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

    // Only one should succeed, others should fail
    let successes = results.iter().filter(|r| r.is_ok()).count();
    let failures = results.iter().filter(|r| r.is_err()).count();

    assert_eq!(successes, 1);
    assert_eq!(failures, 2);
    assert_eq!(test_registry.len(), 1);
}

// Helper function to create a test schema
fn create_test_schema() -> Rc<Schema> {
    let schema_json = json!({
        "type": "string",
        "description": "A test schema"
    });

    let schema = Schema::from_serde_json_value(schema_json).unwrap();
    Rc::new(schema)
}

// Corner case tests
#[test]
fn test_empty_schema_name() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    // Empty string as schema name should fail
    let result = registry.register("", schema);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        SchemaRegistryError::InvalidName { .. }
    ));
    assert!(!registry.contains(""));
    assert_eq!(registry.len(), 0);
    assert!(registry.is_empty());
}

#[test]
fn test_unicode_schema_names() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    // Test various Unicode characters
    let unicode_names = vec![
        "схема",     // Cyrillic
        "スキーマ",  // Japanese
        "模式",      // Chinese
        "🚀schema",  // Emoji
        "café-münü", // Accented characters
        "ñoño",      // Spanish characters
    ];

    for name in &unicode_names {
        let result = registry.register(*name, schema.clone());
        assert!(
            result.is_ok(),
            "Failed to register schema with name: {name}"
        );
        assert!(registry.contains(name));
    }

    assert_eq!(registry.len(), unicode_names.len());

    // Verify all names are listed
    let listed_names = registry.list_names();
    for name in &unicode_names {
        let name: String = (*name).into();
        assert!(listed_names.contains(&name));
    }
}

#[test]
fn test_very_long_schema_name() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    // Create a very long name (1000 characters)
    let long_name: String = "a".repeat(1000).into();

    let result = registry.register(long_name.clone(), schema);
    assert!(result.is_ok());
    assert!(registry.contains(&long_name));

    let retrieved = registry.get(&long_name);
    assert!(retrieved.is_some());
}

#[test]
fn test_special_character_schema_names() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    let special_names = vec![
        "schema-with-dashes",
        "schema_with_underscores",
        "schema.with.dots",
        "schema:with:colons",
        "schema/with/slashes",
        "schema with spaces",
        "schema\twith\ttabs",
        "schema\nwith\nnewlines",
        "UPPERCASE_SCHEMA",
        "MixedCaseSchema",
        "123numeric456",
        "!@#$%^&*()",
        "\"quoted\"",
        "'single-quoted'",
        "[bracketed]",
        "{curly}",
        "(parentheses)",
    ];

    for name in &special_names {
        let result = registry.register(*name, schema.clone());
        assert!(
            result.is_ok(),
            "Failed to register schema with name: {name}"
        );
        assert!(registry.contains(name));
    }

    assert_eq!(registry.len(), special_names.len());
}

#[test]
fn test_whitespace_only_names() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    let whitespace_names = vec![
        " ",        // Single space
        "\t",       // Tab
        "\n",       // Newline
        "\r",       // Carriage return
        "  ",       // Multiple spaces
        "\t\t",     // Multiple tabs
        " \t\n\r ", // Mixed whitespace
    ];

    for name in &whitespace_names {
        let result = registry.register(*name, schema.clone());
        assert!(
            result.is_err(),
            "Expected error for whitespace name: {name:?}"
        );
        assert!(matches!(
            result.unwrap_err(),
            SchemaRegistryError::InvalidName { .. }
        ));
        assert!(!registry.contains(name));
    }

    assert_eq!(registry.len(), 0);
}

#[test]
fn test_valid_names_with_whitespace() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    let valid_names = vec![
        "schema name",       // Space in the middle
        " schema",           // Leading space but not only whitespace
        "schema ",           // Trailing space but not only whitespace
        "my\tschema",        // Tab in the middle
        "multi word schema", // Multiple words
    ];

    for name in &valid_names {
        let result = registry.register(*name, schema.clone());
        assert!(result.is_ok(), "Expected success for valid name: {name:?}");
        assert!(registry.contains(name));
    }

    assert_eq!(registry.len(), valid_names.len());
}

#[test]
fn test_same_schema_different_names() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    // Register the same schema instance with different names
    let names = vec!["name1", "name2", "name3"];

    for name in &names {
        let result = registry.register(*name, schema.clone());
        assert!(result.is_ok());
    }

    assert_eq!(registry.len(), names.len());

    // All should point to the same schema instance
    for name in &names {
        let retrieved = registry.get(name).unwrap();
        assert!(Rc::ptr_eq(&schema, &retrieved));
    }
}

#[test]
fn test_register_after_remove_and_clear() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    // Register, remove, then register again with same name
    registry.register("test", schema.clone()).unwrap();
    assert!(registry.contains("test"));

    registry.remove("test");
    assert!(!registry.contains("test"));

    // Should be able to register again with same name
    let result = registry.register("test", schema.clone());
    assert!(result.is_ok());
    assert!(registry.contains("test"));

    // Clear and register again
    registry.clear();
    assert!(registry.is_empty());

    let result = registry.register("test", schema);
    assert!(result.is_ok());
    assert!(registry.contains("test"));
}

#[test]
fn test_case_sensitive_names() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    // Register schemas with different cases of the same name
    let case_variants = vec!["test", "Test", "TEST", "tEsT"];

    for name in &case_variants {
        let result = registry.register(*name, schema.clone());
        assert!(
            result.is_ok(),
            "Failed to register schema with name: {name}"
        );
    }

    assert_eq!(registry.len(), case_variants.len());

    // All should be treated as different schemas
    for name in &case_variants {
        assert!(registry.contains(name));
        let retrieved = registry.get(name);
        assert!(retrieved.is_some());
    }
}

#[test]
fn test_error_after_schema_removal() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema = create_test_schema();

    // Register schema
    registry.register("test", schema.clone()).unwrap();

    // Remove it
    registry.remove("test");

    // Try to register again - should succeed
    let result = registry.register("test", schema);
    assert!(result.is_ok());
}

#[test]
fn test_mixed_operations_sequence() {
    let registry = SchemaRegistry::new("TestSchemaRegistry");
    let schema1 = create_test_schema();
    let schema2 = create_test_schema();

    // Complex sequence of operations
    registry.register("a", schema1.clone()).unwrap();
    registry.register("b", schema2.clone()).unwrap();
    assert_eq!(registry.len(), 2);

    // Try duplicate - should fail
    assert!(registry.register("a", schema1.clone()).is_err());
    assert_eq!(registry.len(), 2);

    // Remove one
    registry.remove("a");
    assert_eq!(registry.len(), 1);

    // Register with removed name - should succeed
    registry.register("a", schema1).unwrap();
    assert_eq!(registry.len(), 2);

    // Clear and verify
    registry.clear();
    assert!(registry.is_empty());
    assert!(registry.list_names().is_empty());
}