breaker_machines 0.5.0 → 0.6.0

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.
Files changed (76) hide show
  1. checksums.yaml +4 -4
  2. data/ext/breaker_machines_native/Cargo.toml +8 -0
  3. data/ext/breaker_machines_native/core/Cargo.toml +18 -0
  4. data/ext/breaker_machines_native/core/examples/basic.rs +61 -0
  5. data/ext/breaker_machines_native/core/src/builder.rs +232 -0
  6. data/ext/breaker_machines_native/core/src/bulkhead.rs +223 -0
  7. data/ext/breaker_machines_native/core/src/callbacks.rs +58 -0
  8. data/ext/breaker_machines_native/core/src/circuit.rs +1156 -0
  9. data/ext/breaker_machines_native/core/src/classifier.rs +177 -0
  10. data/ext/breaker_machines_native/core/src/errors.rs +47 -0
  11. data/ext/breaker_machines_native/core/src/lib.rs +62 -0
  12. data/ext/breaker_machines_native/core/src/storage.rs +377 -0
  13. data/ext/breaker_machines_native/extconf.rb +40 -0
  14. data/ext/breaker_machines_native/ffi/Cargo.toml +16 -0
  15. data/ext/breaker_machines_native/ffi/src/lib.rs +218 -0
  16. data/ext/breaker_machines_native/target/debug/build/clang-sys-d961dfabd5f43fba/out/common.rs +355 -0
  17. data/ext/breaker_machines_native/target/debug/build/clang-sys-d961dfabd5f43fba/out/dynamic.rs +276 -0
  18. data/ext/breaker_machines_native/target/debug/build/clang-sys-d961dfabd5f43fba/out/macros.rs +49 -0
  19. data/ext/breaker_machines_native/target/debug/build/rb-sys-2bb7281aac8faec8/out/bindings-0.9.117-mri-arm64-darwin24-3.4.7.rs +8936 -0
  20. data/ext/breaker_machines_native/target/debug/build/rb-sys-54cb99ea6aeab8bc/out/bindings-0.9.117-mri-arm64-darwin24-3.4.7.rs +8936 -0
  21. data/ext/breaker_machines_native/target/debug/build/rb-sys-9e64a270c6421e93/out/bindings-0.9.117-mri-arm64-darwin24-3.4.7.rs +8936 -0
  22. data/ext/breaker_machines_native/target/debug/build/rb-sys-e627030114d3fc19/out/bindings-0.9.117-mri-arm64-darwin24-3.4.7.rs +8936 -0
  23. data/ext/breaker_machines_native/target/package/breaker-machines-0.1.0/Cargo.toml +48 -0
  24. data/ext/breaker_machines_native/target/package/breaker-machines-0.1.0/examples/basic.rs +61 -0
  25. data/ext/breaker_machines_native/target/package/breaker-machines-0.1.0/src/builder.rs +154 -0
  26. data/ext/breaker_machines_native/target/package/breaker-machines-0.1.0/src/callbacks.rs +55 -0
  27. data/ext/breaker_machines_native/target/package/breaker-machines-0.1.0/src/circuit.rs +607 -0
  28. data/ext/breaker_machines_native/target/package/breaker-machines-0.1.0/src/errors.rs +38 -0
  29. data/ext/breaker_machines_native/target/package/breaker-machines-0.1.0/src/lib.rs +58 -0
  30. data/ext/breaker_machines_native/target/package/breaker-machines-0.1.0/src/storage.rs +377 -0
  31. data/ext/breaker_machines_native/target/package/breaker-machines-0.2.0/Cargo.toml +48 -0
  32. data/ext/breaker_machines_native/target/package/breaker-machines-0.2.0/examples/basic.rs +61 -0
  33. data/ext/breaker_machines_native/target/package/breaker-machines-0.2.0/src/builder.rs +173 -0
  34. data/ext/breaker_machines_native/target/package/breaker-machines-0.2.0/src/callbacks.rs +55 -0
  35. data/ext/breaker_machines_native/target/package/breaker-machines-0.2.0/src/circuit.rs +855 -0
  36. data/ext/breaker_machines_native/target/package/breaker-machines-0.2.0/src/errors.rs +38 -0
  37. data/ext/breaker_machines_native/target/package/breaker-machines-0.2.0/src/lib.rs +58 -0
  38. data/ext/breaker_machines_native/target/package/breaker-machines-0.2.0/src/storage.rs +377 -0
  39. data/ext/breaker_machines_native/target/package/breaker-machines-0.5.0/Cargo.toml +48 -0
  40. data/ext/breaker_machines_native/target/package/breaker-machines-0.5.0/examples/basic.rs +61 -0
  41. data/ext/breaker_machines_native/target/package/breaker-machines-0.5.0/src/builder.rs +154 -0
  42. data/ext/breaker_machines_native/target/package/breaker-machines-0.5.0/src/callbacks.rs +55 -0
  43. data/ext/breaker_machines_native/target/package/breaker-machines-0.5.0/src/circuit.rs +607 -0
  44. data/ext/breaker_machines_native/target/package/breaker-machines-0.5.0/src/errors.rs +38 -0
  45. data/ext/breaker_machines_native/target/package/breaker-machines-0.5.0/src/lib.rs +58 -0
  46. data/ext/breaker_machines_native/target/package/breaker-machines-0.5.0/src/storage.rs +377 -0
  47. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/Cargo.toml +48 -0
  48. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/examples/basic.rs +61 -0
  49. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/src/builder.rs +232 -0
  50. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/src/bulkhead.rs +223 -0
  51. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/src/callbacks.rs +58 -0
  52. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/src/circuit.rs +1156 -0
  53. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/src/classifier.rs +177 -0
  54. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/src/errors.rs +47 -0
  55. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/src/lib.rs +62 -0
  56. data/ext/breaker_machines_native/target/package/breaker-machines-0.6.0/src/storage.rs +377 -0
  57. data/ext/breaker_machines_native/target/release/build/clang-sys-ef8ad8b846ac8b75/out/common.rs +355 -0
  58. data/ext/breaker_machines_native/target/release/build/clang-sys-ef8ad8b846ac8b75/out/dynamic.rs +276 -0
  59. data/ext/breaker_machines_native/target/release/build/clang-sys-ef8ad8b846ac8b75/out/macros.rs +49 -0
  60. data/ext/breaker_machines_native/target/release/build/rb-sys-064bf9961dd17810/out/bindings-0.9.117-mri-arm64-darwin24-3.4.7.rs +8936 -0
  61. data/lib/breaker_machines/circuit/async_state_management.rb +1 -1
  62. data/lib/breaker_machines/circuit/base.rb +2 -1
  63. data/lib/breaker_machines/circuit/coordinated_state_management.rb +3 -3
  64. data/lib/breaker_machines/circuit/native.rb +127 -0
  65. data/lib/breaker_machines/circuit/state_callbacks.rb +17 -5
  66. data/lib/breaker_machines/circuit/state_management.rb +1 -1
  67. data/lib/breaker_machines/native_extension.rb +36 -0
  68. data/lib/breaker_machines/native_speedup.rb +6 -0
  69. data/lib/breaker_machines/storage/bucket_memory.rb +4 -1
  70. data/lib/breaker_machines/storage/memory.rb +4 -1
  71. data/lib/breaker_machines/storage/native.rb +90 -0
  72. data/lib/breaker_machines/version.rb +1 -1
  73. data/lib/breaker_machines.rb +98 -11
  74. data/lib/breaker_machines_native/breaker_machines_native.bundle +0 -0
  75. data/sig/breaker_machines.rbs +20 -8
  76. metadata +99 -6
@@ -0,0 +1,16 @@
1
+ [package]
2
+ name = "breaker_machines_native"
3
+ version = "0.5.1"
4
+ edition = "2024"
5
+ authors = ["Abdelkader Boudih <terminale@gmail.com>"]
6
+ license = "MIT"
7
+
8
+ [lib]
9
+ crate-type = ["cdylib"]
10
+
11
+ [dependencies]
12
+ breaker-machines = { workspace = true }
13
+ magnus = { version = "0.7", features = ["embed"] }
14
+
15
+ [build-dependencies]
16
+ rb-sys = "0.9"
@@ -0,0 +1,218 @@
1
+ //! Ruby FFI bindings for breaker_machines
2
+ //!
3
+ //! This crate provides Magnus-based Ruby bindings for the breaker-machines library.
4
+ //! It exposes:
5
+ //! - Thread-safe storage backend for circuit breaker event tracking
6
+ //! - Complete circuit breaker with state machine
7
+
8
+ use breaker_machines::{CircuitBreaker, Config, EventKind, MemoryStorage, StorageBackend};
9
+ use magnus::{Error, Module, Object, RArray, RHash, Ruby, function, method};
10
+ use std::sync::Arc;
11
+
12
+ /// Ruby wrapper for the native storage backend
13
+ #[magnus::wrap(class = "BreakerMachinesNative::Storage")]
14
+ struct RubyStorage {
15
+ inner: Arc<MemoryStorage>,
16
+ }
17
+
18
+ impl RubyStorage {
19
+ /// Create a new storage instance
20
+ fn new() -> Self {
21
+ Self {
22
+ inner: Arc::new(MemoryStorage::new()),
23
+ }
24
+ }
25
+
26
+ /// Record a successful operation
27
+ fn record_success(&self, circuit_name: String, duration: f64) {
28
+ self.inner.record_success(&circuit_name, duration);
29
+ }
30
+
31
+ /// Record a failed operation
32
+ fn record_failure(&self, circuit_name: String, duration: f64) {
33
+ self.inner.record_failure(&circuit_name, duration);
34
+ }
35
+
36
+ /// Count successful operations within time window
37
+ fn success_count(&self, circuit_name: String, window_seconds: f64) -> usize {
38
+ self.inner.success_count(&circuit_name, window_seconds)
39
+ }
40
+
41
+ /// Count failed operations within time window
42
+ fn failure_count(&self, circuit_name: String, window_seconds: f64) -> usize {
43
+ self.inner.failure_count(&circuit_name, window_seconds)
44
+ }
45
+
46
+ /// Clear all events for a circuit
47
+ fn clear(&self, circuit_name: String) {
48
+ self.inner.clear(&circuit_name);
49
+ }
50
+
51
+ /// Clear all events for all circuits
52
+ fn clear_all(&self) {
53
+ self.inner.clear_all();
54
+ }
55
+
56
+ /// Get event log for a circuit (returns array of hashes)
57
+ fn event_log(&self, circuit_name: String, limit: usize) -> RArray {
58
+ let events = self.inner.event_log(&circuit_name, limit);
59
+ let array = RArray::new();
60
+
61
+ for event in events {
62
+ // Create a Ruby hash for each event
63
+ let hash = RHash::new();
64
+
65
+ // Set event type
66
+ let type_sym = match event.kind {
67
+ EventKind::Success => "success",
68
+ EventKind::Failure => "failure",
69
+ };
70
+
71
+ let _ = hash.aset(magnus::Symbol::new("type"), type_sym);
72
+ let _ = hash.aset(magnus::Symbol::new("timestamp"), event.timestamp);
73
+ let _ = hash.aset(
74
+ magnus::Symbol::new("duration_ms"),
75
+ (event.duration * 1000.0).round(),
76
+ );
77
+
78
+ let _ = array.push(hash);
79
+ }
80
+
81
+ array
82
+ }
83
+ }
84
+
85
+ /// Ruby wrapper for the native circuit breaker
86
+ #[magnus::wrap(class = "BreakerMachinesNative::Circuit")]
87
+ struct RubyCircuit {
88
+ inner: std::cell::RefCell<CircuitBreaker>,
89
+ }
90
+
91
+ impl RubyCircuit {
92
+ /// Create a new circuit breaker
93
+ ///
94
+ /// @param name [String] Circuit name
95
+ /// @param config [Hash] Configuration hash with keys:
96
+ /// - failure_threshold: Number of failures to open circuit (default: 5)
97
+ /// - failure_window_secs: Time window for counting failures (default: 60.0)
98
+ /// - half_open_timeout_secs: Timeout before attempting reset (default: 30.0)
99
+ /// - success_threshold: Successes needed to close from half-open (default: 2)
100
+ fn new(name: String, config_hash: RHash) -> Result<Self, Error> {
101
+ use magnus::TryConvert;
102
+
103
+ // Extract config values with proper type conversion
104
+ let failure_threshold: usize = config_hash
105
+ .get(magnus::Symbol::new("failure_threshold"))
106
+ .and_then(|v| usize::try_convert(v).ok())
107
+ .unwrap_or(5);
108
+
109
+ let failure_window_secs: f64 = config_hash
110
+ .get(magnus::Symbol::new("failure_window_secs"))
111
+ .and_then(|v| f64::try_convert(v).ok())
112
+ .unwrap_or(60.0);
113
+
114
+ let half_open_timeout_secs: f64 = config_hash
115
+ .get(magnus::Symbol::new("half_open_timeout_secs"))
116
+ .and_then(|v| f64::try_convert(v).ok())
117
+ .unwrap_or(30.0);
118
+
119
+ let success_threshold: usize = config_hash
120
+ .get(magnus::Symbol::new("success_threshold"))
121
+ .and_then(|v| usize::try_convert(v).ok())
122
+ .unwrap_or(2);
123
+
124
+ let jitter_factor: f64 = config_hash
125
+ .get(magnus::Symbol::new("jitter_factor"))
126
+ .and_then(|v| f64::try_convert(v).ok())
127
+ .unwrap_or(0.0);
128
+
129
+ let failure_rate_threshold: Option<f64> = config_hash
130
+ .get(magnus::Symbol::new("failure_rate_threshold"))
131
+ .and_then(|v| f64::try_convert(v).ok());
132
+
133
+ let minimum_calls: usize = config_hash
134
+ .get(magnus::Symbol::new("minimum_calls"))
135
+ .and_then(|v| usize::try_convert(v).ok())
136
+ .unwrap_or(20);
137
+
138
+ let config = Config {
139
+ failure_threshold: Some(failure_threshold),
140
+ failure_rate_threshold,
141
+ minimum_calls,
142
+ failure_window_secs,
143
+ half_open_timeout_secs,
144
+ success_threshold,
145
+ jitter_factor,
146
+ };
147
+
148
+ Ok(Self {
149
+ inner: std::cell::RefCell::new(CircuitBreaker::new(name, config)),
150
+ })
151
+ }
152
+
153
+ /// Record a successful operation
154
+ fn record_success(&self, duration: f64) {
155
+ self.inner.borrow().record_success(duration);
156
+ }
157
+
158
+ /// Record a failed operation and attempt to trip the circuit
159
+ fn record_failure(&self, duration: f64) {
160
+ let mut circuit = self.inner.borrow_mut();
161
+ circuit.record_failure(duration);
162
+ circuit.check_and_trip();
163
+ }
164
+
165
+ /// Check if circuit is open
166
+ fn is_open(&self) -> bool {
167
+ self.inner.borrow().is_open()
168
+ }
169
+
170
+ /// Check if circuit is closed
171
+ fn is_closed(&self) -> bool {
172
+ self.inner.borrow().is_closed()
173
+ }
174
+
175
+ /// Get current state name (lowercase for Ruby compatibility)
176
+ fn state_name(&self) -> String {
177
+ self.inner.borrow().state_name().to_lowercase()
178
+ }
179
+
180
+ /// Reset the circuit (clear all events)
181
+ fn reset(&self) {
182
+ self.inner.borrow_mut().reset();
183
+ }
184
+ }
185
+
186
+ /// Initialize the Ruby extension
187
+ #[magnus::init]
188
+ fn init(ruby: &Ruby) -> Result<(), Error> {
189
+ // Create BreakerMachinesNative module
190
+ let module = ruby.define_module("BreakerMachinesNative")?;
191
+
192
+ // Define Storage class
193
+ let storage_class = module.define_class("Storage", ruby.class_object())?;
194
+
195
+ // Storage instance methods
196
+ storage_class.define_singleton_method("new", function!(RubyStorage::new, 0))?;
197
+ storage_class.define_method("record_success", method!(RubyStorage::record_success, 2))?;
198
+ storage_class.define_method("record_failure", method!(RubyStorage::record_failure, 2))?;
199
+ storage_class.define_method("success_count", method!(RubyStorage::success_count, 2))?;
200
+ storage_class.define_method("failure_count", method!(RubyStorage::failure_count, 2))?;
201
+ storage_class.define_method("clear", method!(RubyStorage::clear, 1))?;
202
+ storage_class.define_method("clear_all", method!(RubyStorage::clear_all, 0))?;
203
+ storage_class.define_method("event_log", method!(RubyStorage::event_log, 2))?;
204
+
205
+ // Define Circuit class
206
+ let circuit_class = module.define_class("Circuit", ruby.class_object())?;
207
+
208
+ // Circuit instance methods
209
+ circuit_class.define_singleton_method("new", function!(RubyCircuit::new, 2))?;
210
+ circuit_class.define_method("record_success", method!(RubyCircuit::record_success, 1))?;
211
+ circuit_class.define_method("record_failure", method!(RubyCircuit::record_failure, 1))?;
212
+ circuit_class.define_method("is_open", method!(RubyCircuit::is_open, 0))?;
213
+ circuit_class.define_method("is_closed", method!(RubyCircuit::is_closed, 0))?;
214
+ circuit_class.define_method("state_name", method!(RubyCircuit::state_name, 0))?;
215
+ circuit_class.define_method("reset", method!(RubyCircuit::reset, 0))?;
216
+
217
+ Ok(())
218
+ }
@@ -0,0 +1,355 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ use std::cell::RefCell;
4
+ use std::collections::HashMap;
5
+ use std::env;
6
+ use std::path::{Path, PathBuf};
7
+ use std::process::Command;
8
+
9
+ use glob::{MatchOptions, Pattern};
10
+
11
+ //================================================
12
+ // Commands
13
+ //================================================
14
+
15
+ thread_local! {
16
+ /// The errors encountered by the build script while executing commands.
17
+ static COMMAND_ERRORS: RefCell<HashMap<String, Vec<String>>> = RefCell::default();
18
+ }
19
+
20
+ /// Adds an error encountered by the build script while executing a command.
21
+ fn add_command_error(name: &str, path: &str, arguments: &[&str], message: String) {
22
+ COMMAND_ERRORS.with(|e| {
23
+ e.borrow_mut()
24
+ .entry(name.into())
25
+ .or_default()
26
+ .push(format!(
27
+ "couldn't execute `{} {}` (path={}) ({})",
28
+ name,
29
+ arguments.join(" "),
30
+ path,
31
+ message,
32
+ ))
33
+ });
34
+ }
35
+
36
+ /// A struct that prints the errors encountered by the build script while
37
+ /// executing commands when dropped (unless explictly discarded).
38
+ ///
39
+ /// This is handy because we only want to print these errors when the build
40
+ /// script fails to link to an instance of `libclang`. For example, if
41
+ /// `llvm-config` couldn't be executed but an instance of `libclang` was found
42
+ /// anyway we don't want to pollute the build output with irrelevant errors.
43
+ #[derive(Default)]
44
+ pub struct CommandErrorPrinter {
45
+ discard: bool,
46
+ }
47
+
48
+ impl CommandErrorPrinter {
49
+ pub fn discard(mut self) {
50
+ self.discard = true;
51
+ }
52
+ }
53
+
54
+ impl Drop for CommandErrorPrinter {
55
+ fn drop(&mut self) {
56
+ if self.discard {
57
+ return;
58
+ }
59
+
60
+ let errors = COMMAND_ERRORS.with(|e| e.borrow().clone());
61
+
62
+ if let Some(errors) = errors.get("llvm-config") {
63
+ println!(
64
+ "cargo:warning=could not execute `llvm-config` one or more \
65
+ times, if the LLVM_CONFIG_PATH environment variable is set to \
66
+ a full path to valid `llvm-config` executable it will be used \
67
+ to try to find an instance of `libclang` on your system: {}",
68
+ errors
69
+ .iter()
70
+ .map(|e| format!("\"{}\"", e))
71
+ .collect::<Vec<_>>()
72
+ .join("\n "),
73
+ )
74
+ }
75
+
76
+ if let Some(errors) = errors.get("xcode-select") {
77
+ println!(
78
+ "cargo:warning=could not execute `xcode-select` one or more \
79
+ times, if a valid instance of this executable is on your PATH \
80
+ it will be used to try to find an instance of `libclang` on \
81
+ your system: {}",
82
+ errors
83
+ .iter()
84
+ .map(|e| format!("\"{}\"", e))
85
+ .collect::<Vec<_>>()
86
+ .join("\n "),
87
+ )
88
+ }
89
+ }
90
+ }
91
+
92
+ #[cfg(test)]
93
+ lazy_static::lazy_static! {
94
+ pub static ref RUN_COMMAND_MOCK: std::sync::Mutex<
95
+ Option<Box<dyn Fn(&str, &str, &[&str]) -> Option<String> + Send + Sync + 'static>>,
96
+ > = std::sync::Mutex::new(None);
97
+ }
98
+
99
+ /// Executes a command and returns the `stdout` output if the command was
100
+ /// successfully executed (errors are added to `COMMAND_ERRORS`).
101
+ fn run_command(name: &str, path: &str, arguments: &[&str]) -> Option<String> {
102
+ #[cfg(test)]
103
+ if let Some(command) = &*RUN_COMMAND_MOCK.lock().unwrap() {
104
+ return command(name, path, arguments);
105
+ }
106
+
107
+ let output = match Command::new(path).args(arguments).output() {
108
+ Ok(output) => output,
109
+ Err(error) => {
110
+ let message = format!("error: {}", error);
111
+ add_command_error(name, path, arguments, message);
112
+ return None;
113
+ }
114
+ };
115
+
116
+ if output.status.success() {
117
+ Some(String::from_utf8_lossy(&output.stdout).into_owned())
118
+ } else {
119
+ let message = format!("exit code: {}", output.status);
120
+ add_command_error(name, path, arguments, message);
121
+ None
122
+ }
123
+ }
124
+
125
+ /// Executes the `llvm-config` command and returns the `stdout` output if the
126
+ /// command was successfully executed (errors are added to `COMMAND_ERRORS`).
127
+ pub fn run_llvm_config(arguments: &[&str]) -> Option<String> {
128
+ let path = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".into());
129
+ run_command("llvm-config", &path, arguments)
130
+ }
131
+
132
+ /// Executes the `xcode-select` command and returns the `stdout` output if the
133
+ /// command was successfully executed (errors are added to `COMMAND_ERRORS`).
134
+ pub fn run_xcode_select(arguments: &[&str]) -> Option<String> {
135
+ run_command("xcode-select", "xcode-select", arguments)
136
+ }
137
+
138
+ //================================================
139
+ // Search Directories
140
+ //================================================
141
+ // These search directories are listed in order of
142
+ // preference, so if multiple `libclang` instances
143
+ // are found when searching matching directories,
144
+ // the `libclang` instances from earlier
145
+ // directories will be preferred (though version
146
+ // takes precedence over location).
147
+ //================================================
148
+
149
+ /// `libclang` directory patterns for Haiku.
150
+ const DIRECTORIES_HAIKU: &[&str] = &[
151
+ "/boot/home/config/non-packaged/develop/lib",
152
+ "/boot/home/config/non-packaged/lib",
153
+ "/boot/system/non-packaged/develop/lib",
154
+ "/boot/system/non-packaged/lib",
155
+ "/boot/system/develop/lib",
156
+ "/boot/system/lib",
157
+ ];
158
+
159
+ /// `libclang` directory patterns for Linux (and FreeBSD).
160
+ const DIRECTORIES_LINUX: &[&str] = &[
161
+ "/usr/local/llvm*/lib*",
162
+ "/usr/local/lib*/*/*",
163
+ "/usr/local/lib*/*",
164
+ "/usr/local/lib*",
165
+ "/usr/lib*/*/*",
166
+ "/usr/lib*/*",
167
+ "/usr/lib*",
168
+ ];
169
+
170
+ /// `libclang` directory patterns for macOS.
171
+ const DIRECTORIES_MACOS: &[&str] = &[
172
+ "/usr/local/opt/llvm*/lib/llvm*/lib",
173
+ "/Library/Developer/CommandLineTools/usr/lib",
174
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
175
+ "/usr/local/opt/llvm*/lib",
176
+ ];
177
+
178
+ /// `libclang` directory patterns for Windows.
179
+ ///
180
+ /// The boolean indicates whether the directory pattern should be used when
181
+ /// compiling for an MSVC target environment.
182
+ const DIRECTORIES_WINDOWS: &[(&str, bool)] = &[
183
+ // LLVM + Clang can be installed using Scoop (https://scoop.sh).
184
+ // Other Windows package managers install LLVM + Clang to other listed
185
+ // system-wide directories.
186
+ ("C:\\Users\\*\\scoop\\apps\\llvm\\current\\lib", true),
187
+ ("C:\\MSYS*\\MinGW*\\lib", false),
188
+ ("C:\\Program Files*\\LLVM\\lib", true),
189
+ ("C:\\LLVM\\lib", true),
190
+ // LLVM + Clang can be installed as a component of Visual Studio.
191
+ // https://github.com/KyleMayes/clang-sys/issues/121
192
+ ("C:\\Program Files*\\Microsoft Visual Studio\\*\\VC\\Tools\\Llvm\\**\\lib", true),
193
+ ];
194
+
195
+ /// `libclang` directory patterns for illumos
196
+ const DIRECTORIES_ILLUMOS: &[&str] = &[
197
+ "/opt/ooce/llvm-*/lib",
198
+ "/opt/ooce/clang-*/lib",
199
+ ];
200
+
201
+ //================================================
202
+ // Searching
203
+ //================================================
204
+
205
+ /// Finds the files in a directory that match one or more filename glob patterns
206
+ /// and returns the paths to and filenames of those files.
207
+ fn search_directory(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
208
+ // Escape the specified directory in case it contains characters that have
209
+ // special meaning in glob patterns (e.g., `[` or `]`).
210
+ let directory = Pattern::escape(directory.to_str().unwrap());
211
+ let directory = Path::new(&directory);
212
+
213
+ // Join the escaped directory to the filename glob patterns to obtain
214
+ // complete glob patterns for the files being searched for.
215
+ let paths = filenames
216
+ .iter()
217
+ .map(|f| directory.join(f).to_str().unwrap().to_owned());
218
+
219
+ // Prevent wildcards from matching path separators to ensure that the search
220
+ // is limited to the specified directory.
221
+ let mut options = MatchOptions::new();
222
+ options.require_literal_separator = true;
223
+
224
+ paths
225
+ .map(|p| glob::glob_with(&p, options))
226
+ .filter_map(Result::ok)
227
+ .flatten()
228
+ .filter_map(|p| {
229
+ let path = p.ok()?;
230
+ let filename = path.file_name()?.to_str().unwrap();
231
+
232
+ // The `libclang_shared` library has been renamed to `libclang-cpp`
233
+ // in Clang 10. This can cause instances of this library (e.g.,
234
+ // `libclang-cpp.so.10`) to be matched by patterns looking for
235
+ // instances of `libclang`.
236
+ if filename.contains("-cpp.") {
237
+ return None;
238
+ }
239
+
240
+ Some((path.parent().unwrap().to_owned(), filename.into()))
241
+ })
242
+ .collect::<Vec<_>>()
243
+ }
244
+
245
+ /// Finds the files in a directory (and any relevant sibling directories) that
246
+ /// match one or more filename glob patterns and returns the paths to and
247
+ /// filenames of those files.
248
+ fn search_directories(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
249
+ let mut results = search_directory(directory, filenames);
250
+
251
+ // On Windows, `libclang.dll` is usually found in the LLVM `bin` directory
252
+ // while `libclang.lib` is usually found in the LLVM `lib` directory. To
253
+ // keep things consistent with other platforms, only LLVM `lib` directories
254
+ // are included in the backup search directory globs so we need to search
255
+ // the LLVM `bin` directory here.
256
+ if target_os!("windows") && directory.ends_with("lib") {
257
+ let sibling = directory.parent().unwrap().join("bin");
258
+ results.extend(search_directory(&sibling, filenames));
259
+ }
260
+
261
+ results
262
+ }
263
+
264
+ /// Finds the `libclang` static or dynamic libraries matching one or more
265
+ /// filename glob patterns and returns the paths to and filenames of those files.
266
+ pub fn search_libclang_directories(filenames: &[String], variable: &str) -> Vec<(PathBuf, String)> {
267
+ // Search only the path indicated by the relevant environment variable
268
+ // (e.g., `LIBCLANG_PATH`) if it is set.
269
+ if let Ok(path) = env::var(variable).map(|d| Path::new(&d).to_path_buf()) {
270
+ // Check if the path is a matching file.
271
+ if let Some(parent) = path.parent() {
272
+ let filename = path.file_name().unwrap().to_str().unwrap();
273
+ let libraries = search_directories(parent, filenames);
274
+ if libraries.iter().any(|(_, f)| f == filename) {
275
+ return vec![(parent.into(), filename.into())];
276
+ }
277
+ }
278
+
279
+ // Check if the path is directory containing a matching file.
280
+ return search_directories(&path, filenames);
281
+ }
282
+
283
+ let mut found = vec![];
284
+
285
+ // Search the `bin` and `lib` directories in the directory returned by
286
+ // `llvm-config --prefix`.
287
+ if let Some(output) = run_llvm_config(&["--prefix"]) {
288
+ let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
289
+ found.extend(search_directories(&directory.join("bin"), filenames));
290
+ found.extend(search_directories(&directory.join("lib"), filenames));
291
+ found.extend(search_directories(&directory.join("lib64"), filenames));
292
+ }
293
+
294
+ // Search the toolchain directory in the directory returned by
295
+ // `xcode-select --print-path`.
296
+ if target_os!("macos") {
297
+ if let Some(output) = run_xcode_select(&["--print-path"]) {
298
+ let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
299
+ let directory = directory.join("Toolchains/XcodeDefault.xctoolchain/usr/lib");
300
+ found.extend(search_directories(&directory, filenames));
301
+ }
302
+ }
303
+
304
+ // Search the directories in the `LD_LIBRARY_PATH` environment variable.
305
+ if let Ok(path) = env::var("LD_LIBRARY_PATH") {
306
+ for directory in env::split_paths(&path) {
307
+ found.extend(search_directories(&directory, filenames));
308
+ }
309
+ }
310
+
311
+ // Determine the `libclang` directory patterns.
312
+ let directories: Vec<&str> = if target_os!("haiku") {
313
+ DIRECTORIES_HAIKU.into()
314
+ } else if target_os!("linux") || target_os!("freebsd") {
315
+ DIRECTORIES_LINUX.into()
316
+ } else if target_os!("macos") {
317
+ DIRECTORIES_MACOS.into()
318
+ } else if target_os!("windows") {
319
+ let msvc = target_env!("msvc");
320
+ DIRECTORIES_WINDOWS
321
+ .iter()
322
+ .filter(|d| d.1 || !msvc)
323
+ .map(|d| d.0)
324
+ .collect()
325
+ } else if target_os!("illumos") {
326
+ DIRECTORIES_ILLUMOS.into()
327
+ } else {
328
+ vec![]
329
+ };
330
+
331
+ // We use temporary directories when testing the build script so we'll
332
+ // remove the prefixes that make the directories absolute.
333
+ let directories = if test!() {
334
+ directories
335
+ .iter()
336
+ .map(|d| d.strip_prefix('/').or_else(|| d.strip_prefix("C:\\")).unwrap_or(d))
337
+ .collect::<Vec<_>>()
338
+ } else {
339
+ directories
340
+ };
341
+
342
+ // Search the directories provided by the `libclang` directory patterns.
343
+ let mut options = MatchOptions::new();
344
+ options.case_sensitive = false;
345
+ options.require_literal_separator = true;
346
+ for directory in directories.iter() {
347
+ if let Ok(directories) = glob::glob_with(directory, options) {
348
+ for directory in directories.filter_map(Result::ok).filter(|p| p.is_dir()) {
349
+ found.extend(search_directories(&directory, filenames));
350
+ }
351
+ }
352
+ }
353
+
354
+ found
355
+ }