optify 0.1.2__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: optify
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -26,11 +26,11 @@ build-backend = "maturin"
26
26
 
27
27
  [package]
28
28
  name = "optify"
29
- version = "0.1.2"
29
+ version = "0.1.3"
30
30
 
31
31
  [tool.poetry]
32
32
  name = "optify"
33
- version = "0.1.2"
33
+ version = "0.1.3"
34
34
  description = "Simplifies getting the right configuration options for a process using pre-loaded configurations from files to manage options for experiments or flights."
35
35
  authors = ["Justin D. Harris"]
36
36
  maintainers = ["Justin D. Harris"]
@@ -124,6 +124,31 @@ dependencies = [
124
124
  "libc",
125
125
  ]
126
126
 
127
+ [[package]]
128
+ name = "crossbeam-deque"
129
+ version = "0.8.6"
130
+ source = "registry+https://github.com/rust-lang/crates.io-index"
131
+ checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
132
+ dependencies = [
133
+ "crossbeam-epoch",
134
+ "crossbeam-utils",
135
+ ]
136
+
137
+ [[package]]
138
+ name = "crossbeam-epoch"
139
+ version = "0.9.18"
140
+ source = "registry+https://github.com/rust-lang/crates.io-index"
141
+ checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
142
+ dependencies = [
143
+ "crossbeam-utils",
144
+ ]
145
+
146
+ [[package]]
147
+ name = "crossbeam-utils"
148
+ version = "0.8.21"
149
+ source = "registry+https://github.com/rust-lang/crates.io-index"
150
+ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
151
+
127
152
  [[package]]
128
153
  name = "crunchy"
129
154
  version = "0.2.3"
@@ -159,6 +184,12 @@ dependencies = [
159
184
  "const-random",
160
185
  ]
161
186
 
187
+ [[package]]
188
+ name = "either"
189
+ version = "1.15.0"
190
+ source = "registry+https://github.com/rust-lang/crates.io-index"
191
+ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
192
+
162
193
  [[package]]
163
194
  name = "encoding_rs"
164
195
  version = "0.8.35"
@@ -287,9 +318,10 @@ checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e"
287
318
 
288
319
  [[package]]
289
320
  name = "optify"
290
- version = "0.6.1"
321
+ version = "0.6.2"
291
322
  dependencies = [
292
323
  "config",
324
+ "rayon",
293
325
  "serde",
294
326
  "serde_derive",
295
327
  "serde_json",
@@ -299,7 +331,7 @@ dependencies = [
299
331
 
300
332
  [[package]]
301
333
  name = "optify-python"
302
- version = "0.1.2"
334
+ version = "0.1.3"
303
335
  dependencies = [
304
336
  "optify",
305
337
  "pyo3",
@@ -453,6 +485,26 @@ dependencies = [
453
485
  "proc-macro2",
454
486
  ]
455
487
 
488
+ [[package]]
489
+ name = "rayon"
490
+ version = "1.10.0"
491
+ source = "registry+https://github.com/rust-lang/crates.io-index"
492
+ checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa"
493
+ dependencies = [
494
+ "either",
495
+ "rayon-core",
496
+ ]
497
+
498
+ [[package]]
499
+ name = "rayon-core"
500
+ version = "1.12.1"
501
+ source = "registry+https://github.com/rust-lang/crates.io-index"
502
+ checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
503
+ dependencies = [
504
+ "crossbeam-deque",
505
+ "crossbeam-utils",
506
+ ]
507
+
456
508
  [[package]]
457
509
  name = "ron"
458
510
  version = "0.8.1"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "optify-python"
3
- version = "0.1.2"
3
+ version = "0.1.3"
4
4
  edition = "2021"
5
5
 
6
6
  description = "Simplifies getting the right configuration options for a process using pre-loaded configurations from files (JSON, YAML, etc.) to manage options for experiments or flights. This library is mainly made to support building implementations for other languages such as Node.js, Python, and Ruby. It is not meant to be consumed directly yet."
@@ -14,5 +14,5 @@ name = "optify"
14
14
  crate-type = ["cdylib"]
15
15
 
16
16
  [dependencies]
17
- optify = { path = "../../rust/optify", version = "0.6.1" }
17
+ optify = { path = "../../rust/optify", version = "0.6.2" }
18
18
  pyo3 = "0.24.1"
@@ -19,7 +19,7 @@ impl PyOptionsProvider {
19
19
  fn get_options_json(&self, key: &str, feature_names: Vec<String>) -> String {
20
20
  self.0
21
21
  .get_options(key, &feature_names)
22
- .expect("Failed to get options")
22
+ .expect("key and feature names should be valid")
23
23
  .to_string()
24
24
  }
25
25
  }
@@ -35,7 +35,7 @@ impl PyOptionsProviderBuilder {
35
35
  let path = std::path::Path::new(&directory);
36
36
  self.0
37
37
  .add_directory(path)
38
- .expect("Failed to add the directory");
38
+ .expect("directory contents should be valid");
39
39
  // TODO Try to avoid cloning
40
40
  Self(self.0.clone())
41
41
  }
@@ -44,7 +44,7 @@ impl PyOptionsProviderBuilder {
44
44
  PyOptionsProvider(
45
45
  self.0
46
46
  .build()
47
- .expect("Failed to build the options provider"),
47
+ .expect("OptionsProvider should be built successfully"),
48
48
  )
49
49
  }
50
50
  }
@@ -1,10 +1,8 @@
1
- import os
2
- import json
3
1
  from pathlib import Path
4
- import sys
5
2
 
6
3
  from optify import OptionsProviderBuilder
7
4
 
5
+
8
6
  def test_features():
9
7
  test_suites_dir = (Path(__file__) / '../../../../tests/test_suites').resolve()
10
8
  builder = OptionsProviderBuilder()
@@ -17,7 +15,5 @@ def test_features():
17
15
  try:
18
16
  provider.get_options_json('key', ['A'])
19
17
  assert False, "Should have raised an error"
20
- except:
21
- # Can't get pyo3_runtime.PanicException because can't import it and catching `Exception` doesn't work either.
22
- e = sys.exc_info()[1]
23
- assert str(e) == "Failed to get options: \"configuration property \\\"key\\\" not found\""
18
+ except BaseException as e:
19
+ assert str(e) == "key and feature names should be valid: \"configuration property \\\"key\\\" not found\""
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "optify"
3
- version = "0.6.1"
3
+ version = "0.6.2"
4
4
  edition = "2021"
5
5
 
6
6
  description = "Simplifies getting the right configuration options for a process using pre-loaded configurations from files (JSON, YAML, etc.) to manage options for experiments or flights. This library is mainly made to support building implementations for other languages such as Node.js, Python, and Ruby. It is not meant to be consumed directly yet."
@@ -18,6 +18,7 @@ exclude = [
18
18
 
19
19
  [dependencies]
20
20
  config = "0.15.6"
21
+ rayon = "1.10.0"
21
22
  serde = "1.0.217"
22
23
  serde_derive = "1.0.217"
23
24
  serde_json = "1.0.140"
@@ -26,3 +27,8 @@ walkdir = "2.5.0"
26
27
 
27
28
  [dev-dependencies]
28
29
  regex = "1.11.1"
30
+ criterion = "0.5.1"
31
+
32
+ [[bench]]
33
+ name = "loading_benchmark"
34
+ harness = false
@@ -0,0 +1,105 @@
1
+ use criterion::{black_box, criterion_group, criterion_main, Criterion};
2
+ use optify::builder::OptionsProviderBuilder;
3
+ use std::fs;
4
+ use std::io::Write;
5
+ use std::path::Path;
6
+
7
+ struct TestDirGuard {
8
+ dir: &'static Path,
9
+ }
10
+
11
+ impl TestDirGuard {
12
+ fn new(dir: &'static Path) -> Self {
13
+ Self { dir }
14
+ }
15
+ }
16
+
17
+ impl Drop for TestDirGuard {
18
+ fn drop(&mut self) {
19
+ cleanup_test_files(self.dir);
20
+ }
21
+ }
22
+
23
+ fn create_test_files(dir: &Path, num_files: usize) {
24
+ cleanup_test_files(dir);
25
+ fs::create_dir_all(dir).unwrap();
26
+
27
+ for i in 0..num_files / 2 {
28
+ let file_path = dir.join(format!("test_{}.json", i));
29
+ let mut file = fs::File::create(&file_path).unwrap();
30
+
31
+ // Create a test configuration file with some realistic content
32
+ let content = format!(
33
+ r#"{{
34
+ "metadata": {{
35
+ "aliases": ["alias_{}_1", "alias_{}_2"]
36
+ }},
37
+ "options": {{
38
+ "setting1": "value1",
39
+ "setting2": 42,
40
+ "setting3": true,
41
+ "nested": {{
42
+ "field1": "nested_value",
43
+ "field2": [1, 2, 3]
44
+ }}
45
+ }}
46
+ }}"#,
47
+ i, i,
48
+ );
49
+
50
+ file.write_all(content.as_bytes()).unwrap();
51
+ }
52
+
53
+ for i in num_files / 2..num_files {
54
+ let file_path = dir.join(format!("test_{}.yaml", i));
55
+ let mut file = fs::File::create(&file_path).unwrap();
56
+
57
+ let content = format!(
58
+ r#"metadata:
59
+ aliases:
60
+ - alias_y_{}_1
61
+ - alias_y_{}_2
62
+ options:
63
+ setting1: value1
64
+ setting2: 42
65
+ setting3: true
66
+ nested:
67
+ field1: nested_value
68
+ field2: [1, 2, 3]
69
+ "#,
70
+ i, i,
71
+ );
72
+ file.write_all(content.as_bytes()).unwrap();
73
+ }
74
+ }
75
+
76
+ fn cleanup_test_files(dir: &Path) {
77
+ fs::remove_dir_all(dir).unwrap_or_default();
78
+ }
79
+
80
+ fn benchmark_loading(c: &mut Criterion) {
81
+ let test_dir = Path::new("bench_test_files");
82
+ let num_files = 100;
83
+ let _guard = TestDirGuard::new(test_dir);
84
+ let test_build = false;
85
+
86
+ create_test_files(test_dir, num_files);
87
+
88
+ let mut group = c.benchmark_group(format!("file_loading-{}", num_files));
89
+
90
+ group.bench_function("parallel loading", |b| {
91
+ b.iter(|| {
92
+ let mut builder = OptionsProviderBuilder::new();
93
+ builder.add_directory(black_box(test_dir)).unwrap();
94
+ if test_build {
95
+ // Ensure that there are no errors in the builder.
96
+ builder.build().unwrap();
97
+ }
98
+ })
99
+ });
100
+
101
+ group.finish();
102
+ }
103
+
104
+ criterion_group!(benches, benchmark_loading);
105
+ criterion_main!(benches);
@@ -1,7 +1,7 @@
1
1
  use config;
2
+ use rayon::prelude::*;
2
3
  use std::collections::{HashMap, HashSet};
3
4
  use std::path::Path;
4
- use walkdir::WalkDir;
5
5
 
6
6
  use crate::provider::{Aliases, Features, OptionsProvider, Sources};
7
7
  use crate::schema::feature::FeatureConfiguration;
@@ -125,7 +125,7 @@ fn resolve_imports(
125
125
  };
126
126
  let options_as_json: serde_json::Value = options_as_config_value
127
127
  .try_deserialize()
128
- .expect("Error deserializing the configuration as JSON.");
128
+ .expect("configuration should be deserializable to JSON");
129
129
  let options_as_json_str = serde_json::to_string(&options_as_json).unwrap();
130
130
  let source = config::File::from_str(&options_as_json_str, config::FileFormat::Json);
131
131
  sources.insert(canonical_feature_name.to_owned(), source);
@@ -141,6 +141,14 @@ fn resolve_imports(
141
141
  Ok(())
142
142
  }
143
143
 
144
+ /// The result of loading a feature configuration file.
145
+ struct LoadingResult {
146
+ canonical_feature_name: String,
147
+ source: config::File<config::FileSourceString, config::FileFormat>,
148
+ imports: Option<Vec<String>>,
149
+ metadata: OptionsMetadata,
150
+ }
151
+
144
152
  impl OptionsProviderBuilder {
145
153
  pub fn new() -> Self {
146
154
  OptionsProviderBuilder {
@@ -152,99 +160,22 @@ impl OptionsProviderBuilder {
152
160
  }
153
161
 
154
162
  pub fn add_directory(&mut self, directory: &Path) -> Result<&Self, String> {
155
- for entry in WalkDir::new(directory) {
156
- let entry = entry.unwrap();
157
- let path = entry.path();
158
- if !path.is_file() {
159
- continue;
160
- }
161
- // Skip .md files because they are not handled by the `config` library and we may have README.md files in the directory.
162
- if path.extension().and_then(|s| s.to_str()) == Some("md") {
163
- continue;
164
- }
165
-
166
- // TODO Optimization: Find a more efficient way to build a more generic view of the file.
167
- // The `config` library is helpful because it handles many file types.
168
- // It would also be nice to support comments in .json files, even though it is not standard.
169
- // The `config` library does support .json5 which supports comments.
170
- let file = config::File::from(path);
171
- let config_for_path = match config::Config::builder().add_source(file).build() {
172
- Ok(conf) => conf,
173
- Err(e) => {
174
- return Err(format!(
175
- "Error loading file '{}': {e}",
176
- path.to_string_lossy(),
177
- ))
178
- }
179
- };
180
-
181
- let feature_config: FeatureConfiguration = match config_for_path.try_deserialize() {
182
- Ok(v) => v,
183
- Err(e) => {
184
- return Err(format!(
185
- "Error deserializing configuration for file '{}': {e}",
186
- path.to_string_lossy(),
187
- ))
188
- }
189
- };
190
-
191
- let options_as_json_str = match feature_config.options {
192
- None => "{}".to_owned(),
193
- Some(options) => {
194
- let options_as_json: serde_json::Value =
195
- options.try_deserialize().map_err(|e| {
196
- format!(
197
- "Error deserializing options for '{:?}': {e}",
198
- path.to_string_lossy()
199
- )
200
- })?;
201
- serde_json::to_string(&options_as_json).unwrap()
202
- }
203
- };
204
- let source = config::File::from_str(&options_as_json_str, config::FileFormat::Json);
205
- let canonical_feature_name = get_canonical_feature_name(path, directory);
206
-
207
- if self
208
- .sources
209
- .insert(canonical_feature_name.clone(), source)
210
- .is_some()
211
- {
212
- return Err(format!(
213
- "Error when loading '{}'. The canonical feature name for the file, '{canonical_feature_name}', was already added. It may be an alias for another feature.",
214
- path.to_string_lossy()
215
- ));
216
- }
217
-
218
- if let Some(imports) = feature_config.imports {
219
- self.imports.insert(canonical_feature_name.clone(), imports);
220
- }
221
-
222
- add_alias(
223
- &mut self.aliases,
224
- &canonical_feature_name,
225
- &canonical_feature_name,
226
- )?;
227
-
228
- // Handle metadata.
229
- // Add aliases.
230
- // Ensure name is set.
231
- let metadata = match feature_config.metadata {
232
- Some(mut metadata) => {
233
- if let Some(ref aliases) = metadata.aliases {
234
- for alias in aliases {
235
- add_alias(&mut self.aliases, alias, &canonical_feature_name)?;
236
- }
237
- }
238
- metadata.name = Some(canonical_feature_name.clone());
239
- metadata
240
- }
241
- None => {
242
- OptionsMetadata::new(None, None, None, Some(canonical_feature_name.clone()))
243
- }
244
- };
245
-
246
- self.features
247
- .insert(canonical_feature_name.clone(), metadata.clone());
163
+ let loading_results: Vec<Result<LoadingResult, String>> = walkdir::WalkDir::new(directory)
164
+ .into_iter()
165
+ .par_bridge()
166
+ .filter_map(|entry| {
167
+ Self::process_entry(
168
+ entry
169
+ .unwrap_or_else(|_| {
170
+ panic!("Error walking directory: {}", directory.display())
171
+ })
172
+ .path(),
173
+ directory,
174
+ )
175
+ })
176
+ .collect();
177
+ for loading_result in loading_results {
178
+ self.process_loading_result(&loading_result)?;
248
179
  }
249
180
 
250
181
  Ok(self)
@@ -275,4 +206,101 @@ impl OptionsProviderBuilder {
275
206
  &self.sources,
276
207
  ))
277
208
  }
209
+
210
+ fn process_entry(path: &Path, directory: &Path) -> Option<Result<LoadingResult, String>> {
211
+ // Skip .md files because they are not handled by the `config` library and we may have README.md files in the directory.
212
+ if !path.is_file() || path.extension().filter(|e| *e == "md").is_some() {
213
+ return None;
214
+ }
215
+
216
+ // TODO Optimization: Find a more efficient way to build a more generic view of the file.
217
+ // The `config` library is helpful because it handles many file types.
218
+ // It would also be nice to support comments in .json files, even though it is not standard.
219
+ // The `config` library does support .json5 which supports comments.
220
+ let file = config::File::from(path);
221
+ let config_for_path = match config::Config::builder().add_source(file).build() {
222
+ Ok(conf) => conf,
223
+ Err(e) => {
224
+ return Some(Err(format!(
225
+ "Error loading file '{}': {e}",
226
+ path.to_string_lossy(),
227
+ )))
228
+ }
229
+ };
230
+
231
+ let feature_config: FeatureConfiguration = match config_for_path.try_deserialize() {
232
+ Ok(v) => v,
233
+ Err(e) => {
234
+ return Some(Err(format!(
235
+ "Error deserializing configuration for file '{:?}': {e}",
236
+ path.to_string_lossy(),
237
+ )))
238
+ }
239
+ };
240
+
241
+ let options_as_json_str = match feature_config.options {
242
+ Some(options) => match options.try_deserialize::<serde_json::Value>() {
243
+ Ok(options_as_json) => serde_json::to_string(&options_as_json).unwrap(),
244
+ Err(e) => {
245
+ return Some(Err(format!(
246
+ "Error deserializing options for '{:?}': {e}",
247
+ path.to_string_lossy()
248
+ )))
249
+ }
250
+ },
251
+ None => "{}".to_owned(),
252
+ };
253
+ let source = config::File::from_str(&options_as_json_str, config::FileFormat::Json);
254
+ let canonical_feature_name = get_canonical_feature_name(path, directory);
255
+
256
+ // Ensure the name is set in the metadata.
257
+ let metadata = match feature_config.metadata {
258
+ Some(mut metadata) => {
259
+ metadata.name = Some(canonical_feature_name.clone());
260
+ metadata
261
+ }
262
+ None => OptionsMetadata::new(None, None, Some(canonical_feature_name.clone()), None),
263
+ };
264
+
265
+ Some(Ok(LoadingResult {
266
+ canonical_feature_name,
267
+ source,
268
+ imports: feature_config.imports,
269
+ metadata,
270
+ }))
271
+ }
272
+
273
+ fn process_loading_result(
274
+ &mut self,
275
+ loading_result: &Result<LoadingResult, String>,
276
+ ) -> Result<(), String> {
277
+ let info = loading_result.as_ref().expect("the file should be loaded");
278
+ let canonical_feature_name = &info.canonical_feature_name;
279
+ if self
280
+ .sources
281
+ .insert(canonical_feature_name.clone(), info.source.clone())
282
+ .is_some()
283
+ {
284
+ return Err(format!(
285
+ "Error when loading feature. The canonical feature name '{canonical_feature_name}' was already added. It may be an alias for another feature."
286
+ ));
287
+ }
288
+ if let Some(imports) = &info.imports {
289
+ self.imports
290
+ .insert(canonical_feature_name.clone(), imports.clone());
291
+ }
292
+ add_alias(
293
+ &mut self.aliases,
294
+ canonical_feature_name,
295
+ canonical_feature_name,
296
+ )?;
297
+ if let Some(ref aliases) = info.metadata.aliases {
298
+ for alias in aliases {
299
+ add_alias(&mut self.aliases, alias, canonical_feature_name)?;
300
+ }
301
+ }
302
+ self.features
303
+ .insert(canonical_feature_name.clone(), info.metadata.clone());
304
+ Ok(())
305
+ }
278
306
  }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes